Android : Get list item id and use it outside of OnItemClickListener

on Monday, September 15, 2014


I'm having troubles with a specific situation in my OnItemClickListener. I have a button inside a Custom Adapter that isn't working until I tap on the item list.


I need to get a list item ID from a listview and use it outside of listener so I'm doing it like this:



public class MyActivity extends ActionBarActivity {
final Context context = this;

long matchId;
int matchPosition;


Listener: private class listLongClickListener implements android.widget.AdapterView.OnItemLongClickListener { @Override public boolean onItemLongClick (AdapterView parent, View view, int position, long id) {



matchID = id;
matchPosition = position;


I want to use id and position in a Button click listener defined in XML so



<Button
android:id="@+id/button_plus"
android:layout_width="0dp"
android:layout_height="match_parent"
android:focusable="false"
android:focusableInTouchMode="false"
android:layout_weight="1"
android:onClick="plusItem"/>


And plusItem is:



public void plusItem(View view) {
final Database db = new Database(getApplicationContext());
db.open();

final Cursor cartCursor = db.fetchProducts();
startManagingCursor(cartCursor);

cartCursor.moveToPosition(matchPosition);
int quantity = cartCursor.getColumnIndex("quantity");
int price = cartCursor.getColumnIndex("price");

q = cartCursor.getInt(quantity);
p = cartCursor.getFloat(price);


if((""+q).equals("99")){
Toast.makeText(getApplicationContext(), "99 is Max", Toast.LENGTH_SHORT).show();
} else {
String id = String.valueOf(matchId);

int fin = q + 1;
float tot = fin * p;

db.editProduct(id, "" + fin, "" + tot);

final SimpleCursorAdapter cartCursorAdapter = new SimpleCursorAdapter(
this,
R.layout.list_item,
cartCursor,
new String[]{Database.ProductsMetaData.PRODUCT_PRODUCT_KEY,
Database.ProductsMetaData.PRODUCT_PRICE_KEY,
Database.ProductsMetaData.PRODUCT_QUANTITY_KEY,
Database.ProductsMetaData.PRODUCT_TOTAL_KEY,
Database.ProductsMetaData.PRODUCT_VALUE_KEY,
},
new int[]{R.id.product,
R.id.price,
R.id.quantity,
R.id.total,
R.id.value,
},
1);

cartCursor.requery();

cartCursorAdapter.changeCursor(cartCursor);
list.setAdapter(cartCursorAdapter);
}


}


However, In order to make it do is work I have to tap on the list item first; If I have more than one element in my list and I tap on one of them, then the buttons in the other items works only for that one I tapped on.


I already made another kind-of this and it worked well with a share utility. Any suggestion?


0 comments:

Post a Comment