fix multitouch?? or not?? - Nexus One Q&A, Help & Troubleshooting

MotionEvent http://android-developers.blogspot.com/?hl=en
The Android framework’s primary point of access for touch data is the android.view.MotionEvent class. Passed to your views through the onTouchEvent and onInterceptTouchEvent methods, MotionEvent contains data about “pointers,” or active touch points on the device’s screen. Through a MotionEvent you can obtain X/Y coordinates as well as size and pressure for each pointer. MotionEvent.getAction() returns a value describing what kind of motion event occurred.
One of the more common uses of touch input is letting the user drag an object around the screen. We can accomplish this in our View class from above by implementing onTouchEvent as follows:
@Override
public boolean onTouchEvent(MotionEvent ev) {
final int action = ev.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN: {
final float x = ev.getX();
final float y = ev.getY();
// Remember where we started
mLastTouchX = x;
mLastTouchY = y;
break;
}
case MotionEvent.ACTION_MOVE: {
final float x = ev.getX();
final float y = ev.getY();
// Calculate the distance moved
final float dx = x - mLastTouchX;
final float dy = y - mLastTouchY;
// Move the object
mPosX += dx;
mPosY += dy;
// Remember this touch position for the next move event
mLastTouchX = x;
mLastTouchY = y;
// Invalidate to request a redraw
invalidate();
break;
}
}
return true;
}
The code above has a bug on devices that support multiple pointers. While dragging the image around the screen, place a second finger on the touchscreen then lift the first finger. The image jumps! What’s happening? We’re calculating the distance to move the object based on the last known position of the default pointer. When the first finger is lifted, the second finger becomes the default pointer and we have a large delta between pointer positions which our code dutifully applies to the object’s location.
If all you want is info about a single pointer’s location, the methods MotionEvent.getX() and MotionEvent.getY() are all you need. MotionEvent was extended in Android 2.0 (Eclair) to report data about multiple pointers and new actions were added to describe multitouch events. MotionEvent.getPointerCount() returns the number of active pointers. getX and getY now accept an index to specify which pointer’s data to retrieve.

anyone know?

You don't have much code up there but...
"mLastTouchX = x;
mLastTouchY = y;"
I assume those are globals... and the fact is that both action down and action move use those at the same time if you use two fingers...
EX:
-finger down create mlasttouchx&y at lets says 0,0 and you move to 1,1 enabling action move to correct it...
-keep finger still and add second finger...
-second finger changes the SAME variables of the previous item
-lift first finger so on action up theres no update (since you have no action up)
I'm not sure HOW to fix this issue (I've never tried multitouch) but your code doesn't support it.
How about adding some toggle variables and add an action up so on release it updates the points OR try using pointers (up to 3 as far as i can see probably for multitouch)
http://developer.android.com/reference/android/view/MotionEvent.html

Related

Java...HELP!

For homework, we're required to write code for a cash register. Basically what it does is it prints out a menu and asks the user for input. At the end it prints out the order along with the total.
The part I am having trouble with is how do I make something like this:
Code:
Hamburger Hamburger Hamburger
display as this:
Code:
(3) Hamburger
We're told to think in terms of parallel arrays, but seeing as I missed that class, I am a bit lost.
If wanted, I can put up what code I have.
Thanks in advance.
can you post all your code?
Here is what I have.
I haven't written anything in my code that would relate to the problem I am having because I do not know where to start.
Code:
import java.util.Scanner;
import java.util.ArrayList;
public class CashRegister{
public static void main(String[]args){
Scanner scan=new Scanner(System.in);
ArrayList<String> list=new ArrayList<String>();
Register reg=new Register();
int b;
do{
String [] item = new String[11];
item [0]="Hot Dog";
item [1]="Hamburger";
item [2]="Soda";
item [3]="Chips";
item [4]="Ice Cream";
item [5]="Shave Ice";
item [6]="Cookie";
item [7]="Plate Lunch";
item [8]="French Fries";
item [9]="Shake";
item [10]="Order Complete";
for (int a=0;a<item.length;a++){
System.out.println((a+1)+". "+item[a]);}
b=scan.nextInt();
if (b==1){
list.add(item[0]);
reg.add(2.50);}
if (b==2){
list.add(item[1]);
reg.add(3.00);}
if (b==3){
list.add(item[2]);
reg.add(1.25);}
if (b==4){
list.add(item[3]);
reg.add(1.50);}
if (b==5){
list.add(item[4]);
reg.add(2.00);}
if (b==6){
list.add(item[5]);
reg.add(2.00);}
if (b==7){
list.add(item[6]);
reg.add(1.00);}
if (b==8){
list.add(item[7]);
reg.add(5.00);}
if (b==9){
list.add(item[8]);
reg.add(2.50);}
if (b==10){
list.add(item[9]);
reg.add(3.00);}
}
while (b != 11);
System.out.println("");
System.out.println("Your order contains: ");
System.out.println(list);
System.out.print("Your order costs: $");
double f=reg.getTotal();
System.out.format("%.2f %n",f);
}}
class Register{
double total=0;
public void add (double b){
total=total+b;}
public double getTotal(){
return total;}
}
I looked into your code and I can see what you want to do. I came up with a way to do it, however, I don't think it will be an efficient code (I'm not really familiar with Java).
I'm sure someone with more knowledge with Java could help you with this.
If you don't mind, could you post what you came up with or maybe point me in the right direction? Thanks
Sent from 234 Elm Street
We're told to think in terms of parallel arrays, but seeing as I missed that class, I am a bit lost.
If wanted, I can put up what code I have.
Thanks in advance.
Click to expand...
Click to collapse
Woops! I haven't read that, here is the almost much more cleaner solution.
There are several things that could be done (checking for valid input for example, ...) but i think thats to much for now.
Code:
import java.util.ArrayList;
import java.util.Scanner;
public class CashRegister {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList<String> order = new ArrayList<String>();
Register reg = new Register();
// init & declare the array outside the loop
String[] menu = new String[] { "Hot Dog", "Hamburger", "Soda", "Chips",
"Ice Cream", "Shave Ice", "Cookie", "Plate Lunch",
"French Fries", "Shake" };
double[] prices = new double[] { 2.50, 3.00, 1.25, 1.50, 2.00, 2.00,
1.00, 5.00, 2.50, 3.00 };
// every order contains a amount int
int[] amountOf = new int[10];
for (int a = 0; a < menu.length; a++) {
System.out.println((a) + ". " + menu[a]);
}
System.out.println("10. " + "Order Complete");
System.out.print("Please choose from the menu:");
int input;
do {
input = scan.nextInt();
if (input >= 0 && input <= 10) {
reg.add(prices[input]);
amountOf[input]++;
}
}
while (input != 11);
System.out.println("");
System.out.println("Your order contains: ");
// System.out.println(list);
// calculate the amount of items from the order
for (int singleItem = 0; singleItem < menu.length; singleItem++) {
for (int menuIndex = 0; menuIndex < order.size(); menuIndex++) {
if (order.get(menuIndex).equals(menu[singleItem])) {
amountOf[singleItem]++;
}
}
}
// print the receipt
for (int i = 0; i < amountOf.length; i++) {
if (amountOf[i] > 0) {
System.out.println("(" + amountOf[i] + ") " + menu[i]);
}
}
System.out.print("Your order costs: $");
double f = reg.getTotal();
System.out.format("%.2f %n", f);
}
}
class Register {
private double total = 0;
public void add(double b) {
total = total + b;
}
public double getTotal() {
return total;
}
}
Thanks for your help. Now I can rest until the next assignment...which is tonight.
slow_DC4 said:
Thanks for your help. Now I can rest until the next assignment...which is tonight.
Click to expand...
Click to collapse
You know where to ask
Hi, sadly, it's me again seeking for some help.
This is what we are supposed to do
Code:
In this assignment you will use the techniques you used in lab to create an interactive vending machine. You must use Arraylists to store the information about the items for sale in the machine. Use the class you created in Assignment 5 in your ArrayLists.
Only the first item in a slot can be sold.
Hint:
Declaring and ArrayList of ArrayLists
Where Type is your class:
ArrayList<ArrayList<Type>> array;
You must also add each ArrayList to the ArrayList
array.add(new ArrayList<Type>());
End Hint
All Methods listed should be public:
Items will follow the restrictions delineated in Assignment 5. (You should leverage the abilities built into that class)
You will create a VendingMachine class that has at least the following methods:
VendingMachine(int numSlots, int maxItems)
This constructor will set up the object so that numSlots is the number of slots the machine has. MaxItems will be the maximum number of items that can be placed in each slot.
void menu()
This method will print a list of the items available, their price and the slot it is in. Only the first item in a slot will be printed. If a slot is Empty “Empty” should be printed with $0.00 for the price. Will also print out the current amount held in the machine.
boolean load(int slotNum, String name, double price, int quantity)
This method will load items into the machine. slotNum will be the slot that the items will be placed in, name will be the name of the item in the machine and price the price. Quantity is the number of this item that should be added. If the quantity exceeds the current capacity of the slot it should add nothing to the slot and return false. If the loading is successful return true.
int capacity(int slotNum)
returns the number of spaces empty in the slot specified.
void insertMoney( double money)
Will increase the amount of money in the machine by the amount of money (will not do anything if money is negative)
double returnMoney()
Will set amount of money in the machine to 0 and return the amount that was in the machine.
boolean select(int slotNumber)
Attempts to purchase the item in the slotnumber selected it returns true if the sale was successful and false if it was not. For a successful sale the amount held in the machine must be greater than the selected item. There must also be a valid item to be sold (the slot is not empty). If the item is sold the amount in the machine should be decreased by the price of the item. The first items in the slot should be removed.
This is what I have:
Code:
import java.util.ArrayList;
class itemVend{
public String item;
public double price;
final double maxPrice=99.99;
public itemVend(String item, double price){
this.item=item;
this.price=price;
}
public String getItem(){
if (item.length()>20){
item=item.substring(0,20);
}
System.out.println(item);
return item;
}
public double getPrice(){
if (price>=100.00){
price=99.99;
}
String priceNormal=String.format("%.2f",price);
System.out.format("$%5s",priceNormal);
double nPrice=Double.valueOf(priceNormal);
return nPrice;
}
}
class VendingMachine{
int numSlots;
int maxItems;
int slotNum;
String name;
double price;
int quantity;
double total;
double money;
int [] NumSlot=new int[numSlots];
int [] SlotAdd=new int [maxItems];
ArrayList<ArrayList<VendingMachine>> VendM;
public VendingMachine(int numSlots, int maxItems){
this.numSlots=numSlots;
this.maxItems=maxItems;
}
/*
public void menu(){
for (int x=0;x<numSlots;x++){
System.out.print(NumSlot[x]+","+name+","+price);
}
}
*/
public boolean load (int slotNum, String name, double price,int quantity){
if (quantity<=maxItems){
this.slotNum=slotNum;
this.name=name;
this.price=price;
itemVend IV=new itemVend(name,price);
this.quantity=quantity;
return true;
}
else {
return false;
}
}
public int capacity (int slotNum){
int emptySpace=maxItems-quantity;
return emptySpace;
}
public void insertMoney (double money){
total=total+money;
}
public boolean select(int slotNum){
if ((money>price)){
total=total-price;
return true;
}
else {
return false;
}
}
}
It's not quite done yet, and I'm sure that I have a lot of errors, because I am getting a little frustrated. The parts that I am having the most difficulty with is the VendingMachine constructor and the printing of the menu. Also I don't understand how the hint applies.
I think I may have figured out the menu problem:
Code:
public void menu(){
for (int x=0;x<VendNumber.size();x++){
System.out.println("Slot number: "+VendNumber.get(x)+", Item Name: "+VendItemName.get(x)+", Item Price: $"+ItemPrice.get(x));
}
}
Assignment 5 refers to the itemVend class.
Thanks in advance.
I'll take a look at this at the weekend, maybe tomorrow.

[Q] How to avoid reboot for changes to take effect

Hello!
I've decided to change Smooth System Progress Bars module to use a navigation drawer and use fragments inside a "container". In order to do that, I had to "convert" my previously "Main activity" into a fragment. I've followed these instructions in order to achieve that.
But now I'm forced to reboot the phone to see the changes take effect. If I don't reboot, the values applied are the ones defined by default on the module's code.
More than that, every time I change anything on a PreferenceFragment (which has another options but nothing related to user's progress bars customization), the behavior is the same.
After rebooting, everything becomes as it should be. That's odd.
Since I'm fairly new to android programming, I really could use some help in order to understand this.
Can anyone help me?
I'm sorry for double posting.
I've just realized that this issue has nothing to do with fragments.
The problem exists even if I convert everything back to activities.
So this means that this started to happen immediately after I've implemented a navigation drawer. What could be wrong?
Any ideas?
Sorry once again.
I've solved my issue.
Discovered that the problem resided on NavigationDrawerFragment.java.
Somewhere along the code this happens:
Code:
/**
* Per the design guidelines, you should show the drawer on launch until the user manually
* expands it. This shared preference tracks this.
*/
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
--- some more code ---
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Read in the flag indicating whether or not the user has demonstrated awareness of the
// drawer. See PREF_USER_LEARNED_DRAWER for details.
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
// Select either the default item (0) or the last selected item.
selectItem(mCurrentSelectedPosition);
}
So, the problem is, in order to use that small feature (make the user aware of the drawer) the default AOSP code uses this:
Code:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
And that, my friends, compromises any of your SharedPreferences and/or XSharedPreferences.
I can live well without that small feature...deleted it from my module.
Everything is ok now.
:victory:

How do you get the number of items in a spinner control

I am trying to use m_BTArrayAdapter.getCount()
However this function returns 0 regardless of what is in the spinner popup.
I found some doco on this function: http://developer.android.com/reference/android/widget/ArrayAdapter.html#getCount%28%29
"public int getCount ()"
That is - no description. So what does that mean? In android Studio this function is redundant?
There are no other functions that I can see that tell you how many items there are in an ArrayAdapter or in the spinner control itself.
Surely I don't have to resort to a counter in my BT listener function to keep count of how many items are added to the adapter????
Code:
void setupBTListener()
{
m_BTArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item);
final Spinner spinnerBluetooth = (Spinner)findViewById(id.spinner_bluetooth);
spinnerBluetooth.setAdapter(m_BTArrayAdapter);
Can anyone explain to me why m_BTArrayAdapter.getCount() returns non zero inside my listener function but zero in the code below?
Code:
m_BTArrayAdapter.clear();
if (m_BTAdapter.isDiscovering())
m_BTAdapter.cancelDiscovery();
m_BTAdapter.startDiscovery();
long longStart = System.currentTimeMillis(),
longTimer;
boolean bDone = false;
while (m_BTAdapter.isDiscovering() && !bDone)
{
longTimer = System.currentTimeMillis();
//bDone = (longTimer - longStart) < 5000;
}
bEnable = m_BTArrayAdapter.getCount() > 0;
spinnerBluetooth.setEnabled(bEnable);
buttonConnect.setEnabled(bEnable);
buttonSearch.setEnabled(true);

Optical Dust Sensor GP2Y1010AU0F

Hi there, i am looking for some help to configure the optical dust sensor in C++ language. What i need it to do is to be able to detect any dust particles and im able to retrieve the reading and display it on an 20x4 character LCD Display connected to a PIC18F4550 Microcontroller. But the problem is this Optical Dust sensor is really confusing and i have troubles configuring it.
The Optical Dust sensor is just another part of my project and this is the code for the Dust sensor, would love to receive some help or correction on the codes thanks! :
void ADC_dust()
{
int length;
float volt_reading;
char result;
char error[] = "ERROR! ";
ADCON0= 0X0D; //convert channel 3.
PORTAbits.RA4 = 0; //turn on LED
Delay10KTCYx(4); //wait for reading to become stable
ADCON0bits.GO = 1; // This is bit0 of ADCON0, START CONVERSION NOW
while(ADCON0bits.GO == 1); // Waiting for DONE
PORTAbits.RA4 = 1;
//volt_reading = ((ADRES-50+0.1-0.1)/614)*0.52; //*check if vdd change overtime
volt_reading = (ADRES*5.0)/1024; //*check if vdd change overtime
volt_reading = (volt_reading*(5/29))-(3/29);
// Update LCD dust values
displaydec(volt_reading, 3, 0xD9); // Display dust value
lcd_write_data('m');
lcd_write_data('g');
lcd_write_data(0x2F); // To write '/' 0010x1111
lcd_write_data('m'); // write '3'
lcd_write_data(0x33);
lcd_write_data(' ');
lcd_write_data(' ');
// Update Thingspeak dust Values
length = dec2buf(volt_reading, 3); // Convert dust value into string
ESP8266_SendData(length, '4'); // Update Thingspeak Pressure value (Field 4)
}

issue dealing with random function.

Code:
public void random(View view){
int min = 0;
int max = 5;
int ran = Random.nextInt((max - min) + 1) + min;
TextView t = (TextView) findViewById(R.id.msg);
t.setText(ran);
}
screwing up on the random line giving error => Error25, 31) error: non-static method nextInt(int) cannot be referenced from a static context
====================================
Edit
====================================
redid it
Code:
public void random(View view){
Random rand = new Random();
int number = rand.nextInt(10)+1;
TextView t = (TextView) findViewById(R.id.msg);
t.setText(""+number);
}
Random is not based on the cpu clock, but the seed used can be based on the current time for example.
How it works
As anything that happens in a computer, the result of a calculation is deterministic and cannot be really random. Basically, the random function remembers the latest returned value, and calculates the new one starting from the old one, for example:
X(i) = (a*X(i-1) + b)mod where a, b and n are constants
so a (pseudo)random function actually returns a predictable sequence of numbers based on the first value. In C you can specify the first value (seed) with srand():
srand(time(NULL));
For example in this way you initialize the seed to the current number of seconds. But if you know the starting value, again the sequence is predictable.
Problems
This is not good for numerous reasons, mainly related to security: for example, if you have a web session identified by a random number given from the server to the user at login, and an attacker is able to predict it, this can be used to impersonate the real user.
Usually is the same with the other programming languages. The only way to get better random numbers, is to rely also on inputs given by the user, such as mouse movements, key press and so on. This gives more unpredictability to the generated value, and this is how OS number generators such as /dev/random work.

Categories

Resources