How to get info from ListFragment - android

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.

Related

Android getting data out of listview

I'm at the moment programming an APP with an listview which is filled with data from an SQLite Table like this:
public void printDatabase(){
Cursor c = handler.getAllRows();
String[] fieldNames = new String[] {DBHandler.COLUMN_WORKER_ID, DBHandler.COLUMN_WORKER_NAME, DBHandler.COLUMN_WORKER_SURNAME, DBHandler.COLUMN_WORKER_COST};
int[] toView = new int[] {R.id.item_worker_id, R.id.item_worker_name, R.id.item_worker_surname, R.id.item_worker_cost};
SimpleCursorAdapter cAdapter;
cAdapter = new SimpleCursorAdapter(getBaseContext(), R.layout.worker_items, c, fieldNames, toView, 0);
list = (ListView) findViewById(R.id.worker_listView);
list.setAdapter(cAdapter);
}
Now I'd like to get the data from the listview of an item by clicking the item. I've searched everywhere to find a solution for this and found this:
class ItemListener implements AdapterView.OnItemClickListener{
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Object o = list.getItemAtPosition(i);
String s = list.toString();
}
}
But all I get from this is the reference to the cursor I've used for filling the listview. What do I need to get the data from the listview?
You are half way to your solution already.
Cursor itemCursor = (Cursor) list.getItemAtPosition(i);
This returns you a cursor pointing to the row that is clicked. You can get the data out of it like:
class ItemListener implements AdapterView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Cursor itemCursor = (Cursor) list.getItemAtPosition(i);
String workerId = itemCursor.getString(itemCursor.getColumnIndex(DBHandler. COLUMN_WORKER_ID));
String workerName = itemCursor.getString(itemCursor.getColumnIndex(DBHandler.COLUMN_WORKER_NAME));
String workerSurname = itemCursor.getString(itemCursor.getColumnIndex(DBHandler.COLUMN_WORKER_SURNAME));
String workerCost = itemCursor.getString(itemCursor.getColumnIndex(DBHandler.COLUMN_WORKER_COST));
}
}
Make the cursor global ;
Cursor cursor ;
In your OnItemClick
class ItemListener implements AdapterView.OnItemClickListener{
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
cursor.moveToPosition(position);
String Id = cursor.getString(itemCursor.getColumnIndex(DBHandler. COLUMN_WORKER_ID));
}
}
Try this:
class ItemListener implements AdapterView.OnItemClickListener{
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
TextView textView = (TextView) view.findViewById(R.id.list_content);
String text = textView.getText().toString();
//Log.d("Choosen: " + text);
}}

Adding onListItemLick/onItemLongClick in a ListFragment

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");
}

How I can use onListItem to start a new activity with the ListView Value?

Hi I have a android application and i use a sqlite database and a listview in my Activity.
Now I want to use onListItemClick but I don_t know how I can get the value that I click and open a new activity with this value :(
here my code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show);
mHelper = new DatenbankManager(this);
mDatenbank = mHelper.getReadableDatabase();
ladeDaten();
}
my ladeDaten method:
private void ladeDaten() {
Cursor KlassenCursor = mDatenbank.rawQuery(KLASSEN_SELECT_ROW, null);
startManagingCursor(KlassenCursor);
android.widget.SimpleCursorAdapter KlassenAdapter = new android.widget.SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,
KlassenCursor,
new String[] {"name"},
new int[] {
android.R.id.text1
});
setListAdapter(KlassenAdapter);
}
Here my onListItemClick that don't work :(
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
String selection = l.getItemAtPosition(position).toString();
Toast.makeText(this, selection, Toast.LENGTH_LONG).show();
}
I think you using cursor to get data from the database.Instead of using onListItemClick() use onItemClickListener() To get the listView item details use the following code
yourlistview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Cursor cursor = (Cursor) parent.getItemAtPosition(position);
String itemid = cursor.getString(cursor.getColumnIndex("ColumnName");//Repeat for other values
//Start the activity here
Intent todayreview = new Intent(ReviewPayment.this,
ReviewandResend.class);
todayreview.putExtra("iteid", itemid);
startActivity(todayreview);
}
});
To use onListItemClick Add extends ListActivity.
public class MainActivity extends ListActivity
But i think it is better to use onItemClick() like Vino said

Access a database value on a ListView

I have a database of webpages like this:
import android.provider.BaseColumns;
public interface ThreadDatabase extends BaseColumns {
String TABLE_NAME = "Threads";
String TITLE = "Title";
String DESCRIPTION = "Description";
String URL = "Url";
String[] COLUMNS = new String[] { _ID, TITLE, DESCRIPTION, URL };
}
And a Listview in my Activity with a SimpleCursorAdapter that displays Title and Descripton in every row.
Cursor c = dbhelper.getDatabase();
setListAdapter(new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_2, c, new String[] {
ThreadDatabase.TITLE, ThreadDatabase.DESCRIPTION },
new int[] { android.R.id.text1, android.R.id.text2, })
How could I redefine onListItemClick method so that when I click on the item the right url is opened?
protected void onListItemClick(ListView l, View v, int position, long id) {
???Missing part???
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
}
I'm assuming your activity extends ListActivity. If so, in onListItemClick(), all you need to do is:
protected void onListItemClick(ListView l, View v, int position, long id) {
Cursor item = (Cursor)getListAdapter().getItem(position);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
}
You need a reference to your SimpleCursorAdapter so initialize it to a field.
Assuming you have a field mAdapter, you can get the cursor like this:
protected void onListItemClick(ListView l, View v, int position, long id) {
Cursor cursor = (Cursor) mAdapter.getItem(position);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
}
Hope that helps.

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