Adding onListItemLick/onItemLongClick in a ListFragment - android

SOLVED IN A COMMENT: Adding onListItemLick/onItemLongClick in a ListFragment
The problem was generated from an ImageButton in the layout of the single element in the ListFragment that was stealing the input even with the focusable element set to false, so i had to remove it from the layout.
I've got a ListFragment populated by an extended class of SimpleCursorAdapter (mainly for overriding the newView method) but I wanted to add an AlertDialog when the user presses (or long presses) an item in the list the adapter generated.
I've tryed both onListItemClick and onItemLongClick with a simple log write using Log.d method but nothing happens in both cases and i don't know where is the problem since the code is really simple:
public class FragmentD extends ListFragment {
private SQLiteDatabase db;
#Override
public void onActivityCreated (Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
myDatabase myDBHelper = new myDatabase(getActivity());
db = myDBHelper.getWritableDatabase();
Log.d("DB", "Insert fatto");
String[] res_columns = new String[] {myDatabase.COLUMN2, myDatabase.COLUMN2,};
String sortOrder = myDatabase.COLUMN1 + " DESC";
String where = "*";
Cursor testCursor = db.rawQuery("select * from " + database.DATABASE_TABLE, null);
myAdapter adapter = new myAdapter(getActivity(),
R.layout.list_element,
testCursor,
res_columns,
new int[] { },
0);
setListAdapter(adapter);
}
#Override
public void onListItemClick (ListView l, View v, int pos, long id) {
super.onListItemClick(l, v, pos, id);
Log.d("CLICK", "pressed");
}

Edited Answer:
Maybe the components of the layout were stealing the input from other components of the layout

I have got two solution
Simply Override onListItemClick
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Log.i("position",position);
}
On the root layout. Add this code
android:descendantFocusability="blocksDescendants"
Hope it helps

Add the super constructor and override it:
#Override
public void onListItemClick (ListView l, View v, int pos, long id) {
super.onListItemClick(l, v, pos, id);
Log.d("CLICK", "pressed");
}
EDIT: try this code
public class FragmentD extends ListFragment {
private SQLiteDatabase db;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(YOUR LISTFRAGMENT LAYOUT HERE, container, false);
myDatabase myDBHelper = new myDatabase(getActivity());
db = myDBHelper.getWritableDatabase();
Log.d("DB", "Insert fatto");
String[] res_columns = new String[] {myDatabase.COLUMN2, myDatabase.COLUMN2,};
String sortOrder = myDatabase.COLUMN1 + " DESC";
String where = "*";
Cursor testCursor = db.rawQuery("select * from " + database.DATABASE_TABLE, null);
myAdapter adapter = new myAdapter(getActivity(),
R.layout.list_element,
testCursor,
res_columns,
new int[] { },
0);
setListAdapter(adapter);
return v;
}
#Override
public void onListItemClick (ListView l, View v, int pos, long id) {
super.onListItemClick(l, v, pos, id);
Log.d("CLICK", "pressed");
}

Related

How to get info from ListFragment

I have a ListFragment that is populated using a CursorLoader. Once the ListFragment is populated, I have an OnItemClickListener method in which I want to identify which item from the List Fragment the user chose. How do I do this? I've tried:
String item = getListAdapter().getItem(position);
String item = getListAdapter().getItem(position).toString();
and
String item = (String) ((Fragment) getListAdapter().getItem(position)).getString(0);
where position is an integer passed to the onClickItemListener method like so:
public void onListItemClick(ListView l, View v, int position, long id)
All of these throw Cast Exceptions of one type or another. I'm stumped. This seems like a simple thing to do. For your reference, here's how the List Fragment is populated:
private SimpleCursorAdapter mAdapter;
private static final String[] PROJECTION = new String[] { "_id", "stitchname" };
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Intent myData = getActivity().getIntent();
Bundle info = myData.getExtras();
String[] dataColumns = { "stitchname" };
int[] viewIDs = { R.id.stitchlist1 };
mAdapter = new SimpleCursorAdapter(getActivity(), R.layout.stitchlist, null, dataColumns, viewIDs, 0);
setListAdapter(mAdapter);
getLoaderManager().initLoader(0, info, (LoaderCallbacks<Cursor>) this);
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String selection = "stitchlevel=?";
String[] selectionArgs = new String[] {args.getString("Level")};
return (Loader<Cursor>) new CursorLoader(getActivity(), STITCHES_URI, PROJECTION, selection, selectionArgs, null);
}
Any suggestions would be most welcome, thanks!
You are overriding the wrong method. You said you are using an ListFragment, so you may have been declaring your CursorAdapter/ArrayAdapter somewhere in your Fragment. In that case, do the following:
class yourFragemt extends ListFragment{
//Member Variable
private SimpleCursorAdapter mAdapter;
....
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
Cursor c = (Cursor) mAdapter.getItem(pos);
String value = c.getString(c
.getColumnIndex(ColumnIndex));
}
}
The answer is as follows:
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Cursor c = ((SimpleCursorAdapter)l.getAdapter()).getCursor();
c.moveToPosition(position);
String item = c.getString(1);
}
I got the answer from the second link provided to me by Georgy Gobozov in a comment, above.

remove an item from listview

I need to change the method onListItemClick () to delete the items on the list .. ideas?
I do not know how to adapt it into my class. I have a Db class I and an Helper class.
Here is the code:
Cursor cursor = db.rawQuery("select * from " + PRODUCT_TABLE, null);
setListAdapter(new CursorAdapter(this, cursor, true) {
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent){
TextView textView = new TextView(ProdottiSelectionActivity.this);
return textView;
}
#Override
public void bindView (View view, Context context, Cursor cursor){
TextView textView = (TextView) view;
textView.append(cursor.getString(1));
textView.append("\n");
textView.append(cursor.getString(2));
textView.append("\n");
textView.append(cursor.getString(3));
textView.append("\n");
textView.append(cursor.getString(4));
}
});
}
#Override
protected void onDestroy(){
super.onDestroy();
dbHelper.close();
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
setResult(1, new Intent(String.valueOf(id)));
finish();
}
You will need something like following
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
db.open();
//you have to determine user clicked on which item
String[] whereArgs={String.valueOf(item_id)};
db.delete(DATABASE_TABLE_4,"item_id = ?",whereArgs);
cursor.requery(); //deprecated
adapter.notifyDataSetChanged(); //deprecated
db.close();
}
Run a delete query on the database, that would update the list view as well.
db.execSQL("delete from " + PRODUCT_TABLE + " where id = 1", null);
for example if you want to delete a product with id = 1, or you could also use the delete method.
Also see the questions
Android db.delete(); on ListActivity
Android Delete Query
which are similar to your question.

how to implement onitem click listener in SimpleCursorAdapter

I have the following code snippet.
public class ImageStoreActivity extends ListActivity {
private DBHelper mDB;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDB = new DBHelper(this);
mDB.Reset();
Bitmap img = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
mDB.createItemEntry(new ListObject(img, "x", "999999", "blah"));
mDB.createItemEntry(new ListObject(img, "y", "56789", "blah blah"));
mDB.createItemEntry(new ListObject(img, "Pfirsich", "4112344", "blaflakf"));
mDB.createItemEntry(new ListObject(img, "Zitrone", "4023232", "511131"));
String[] columns = {mDB.KEY_ID, mDB.KEY_IMG, mDB.KEY_NAME, mDB.KEY_PHONE, mDB.KEY_RELATION};
String table = mDB.RELATION_TABLE;
Cursor c = mDB.getHandle().query(table, columns, null, null, null, null, null);
startManagingCursor(c);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.main,
c,
new String[] {mDB.KEY_IMG, mDB.KEY_NAME, mDB.KEY_PHONE, mDB.KEY_RELATION},
new int[] {R.id.img, R.id.txt, R.id.textview,R.id.textview1});
adapter.setViewBinder(new ItemViewBinder());
setListAdapter(adapter);
}
}
how do i add this code
public void onItemClick(AdapterView parentView, View v,
int position, long id) {}
to the above code. please help me
add this code after setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// add the array list here..
}
});
Override the onListItemClick() method, like this,
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
// Do something here
...
}

SimpleCursorAdapter and ViewBinder - Binding data to ListView items to be retrieved on click

So I've got a ListView (using a ListActivity) that I'm populating from a SQLiteDatabase. I'm trying to attach the ID (PK) of the row to the view, so that onListItemClick of each list item, I can do stuff with that ID.
I've read that arbitrary data can be set to a View using setTag and retrieved with getTag(I haven't actually had this work successfully yet, so this may be the problem). Here's a pared down version of what I'm using (for simplicity/brevity):
public class Favorites extends ListActivity {
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
FavoritesDB db = FavoritesDB.getInstance(this);
Cursor c = db.fetchFavorites();
startManagingCursor(c);
String[] columns = new String[] { "_id" };
int[] to = new int[] { R.id.word };
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.favorite, c, columns, to);
adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
view.setTag(cursor.getInt(0));
return true;
}
});
setListAdapter(adapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Object wordID = v.getTag();
Toast.makeText(getBaseContext(), "ID=" + wordID, 1).show();
}
}
The ListView is being populated, and the Toast does show up, but it's always "ID=null", so apparently the ID isn't being set in the ViewBinder call to setTag(or isn't being retrieved property with getTag).
This depends on your implementation of R.layout.favorite. If you have this layout contains a parent view with child TextViews for e.g. the tag you set is for the TextViews while the View v received from the onListItemClick() is the parent View. You need to make sure that you receive the tag for the same view you set by using:
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Object wordID = v.getChild(0).getTag();
Toast.makeText(getBaseContext(), "ID=" + wordID, 1).show();
}
You probably should get the cursor from the adapter. This way if your cursor gets replaced you are still are still getting a valid cursor.
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Cursor cursor = adapter.getCursor();
cursor.moveToPosition(position);
String id = cursor.getString(cursor.getColumnIndex("primary key field name in database");
Toast.makeText(getBaseContext(), "ID=" + id, 1).show();
}
NOTE :
your adapter must be declared as a SimpleCursorAdapter other wise you should downcast it.

Android: Listview's onItemClick() event not getting called

Following is my code :
public class TestActivity extends ListActivity {
private Cursor cursor;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
fillData();
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
// Get the item that was clicked
Object o = this.getListAdapter().getItem(position);
String keyword = o.toString();
Toast.makeText(this, "You selected: " + keyword, Toast.LENGTH_LONG)
.show();
}
private void fillData() {
TermsData_DataHelper termsDataHelper = new TermsData_DataHelper(
TestActivity.this);
cursor = termsDataHelper.fetchAllCategories();
startManagingCursor(cursor);
String[] names = new String[] { "name" };
int[] to = new int[] { R.id.label };
// Now create an array adapter and set it to display using our row
SimpleCursorAdapter categories = new SimpleCursorAdapter(this,
R.layout.terms_row, cursor, names, to);
setListAdapter(categories);
}
}
When I click on a row in the listview, I don't see any Toast. Can anybody tell me where am I making a mistake.
Thanks in advance.
I was having a similar problem and found that after removing android:clickable="true" from my list items, the onListItemClick() was being triggered just fine. I hope this helps.
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
String mString = parent.getItemAtPosition(position).toString();
//will give you the text of current line or
int i = parent.getItemAtPosition(position);
//if you want just position number
}
The solution is to override protected void onListItemClick (ListView l, View v, int position, long id) method.
I had this problem also. I solved it by Removing this from my TextView in the the layout XML.
android:textIsSelectable="true"

Categories

Resources