I have a ListView where each ListItem has 2 TextViews in it's layout. I'd like to pass the values of those TextViews to another activity when the ListItem is clicked. All my attempts have failed, so i ask you how can i do that? How can i pass the SQLite ROW_ID, the values of R.id.text1 and R.id.text2?
Cursor cursor = database.getAllNames();
adapter = new SimpleCursorAdapter(this, R.layout.listrow, cursor,
new String[] { Database.KEY_DATE , Database.KEY_NAME },
new int[] {R.id.text1, R.id.text2}, 0);
listView = (ListView) findViewById(R.id.list);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(SendingData.this, ReceivingData.class);
intent.putExtra("id", id); //this should pass the SQLite ROW_ID
intent.putExtra("date", date); //this should pass the value of R.id.text1
intent.putExtra("name", name); //this should pass the value of R.id.text2
startActivity(intent);
}
});
Use this to retrieve the data from the SQLLite database.
cursor.getString(c.getColumnIndex(Database.columns[i])) // i is the index of the column whose details you want to fetch
And then you can pass them as parameters in intent.putExtra.
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Cursor cursor = null;
cursor = (Cursor) parent.getItemAtPosition(position);
Intent intent = new Intent(SendingData.this, ReceivingData.class);
intent.putExtra("id", cursor.getInt(cursor.getColumnIndex(Database.columns[0]))); //assuming that the first column in your database table is the row_id
intent.putExtra("date", cursor.getString(cursor.getColumnIndex(Database.columns[1]))); //assuming that the second column in your database table is the text1
intent.putExtra("name", cursor.getString(cursor.getColumnIndex(Database.columns[2]))); //assuming that the third column in your database table is the text2
startActivity(intent);
}
});
You can do it by taking the data directly from the view without having to access the cursor (and using the row id passed in the onItemClick method as you are already doing).:
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView text1 = (TextView) view.findViewById(R.id.text1);
TextView text2 = (TextView) view.findViewById(R.id.text1);
String date = text1.getText().tostring();
String name = text2.getText().tostring();
Intent intent = new Intent(SendingData.this, ReceivingData.class);
intent.putExtra("id", id); //this should pass the SQLite ROW_ID
intent.putExtra("date", date); //this should pass the value of R.id.text1
intent.putExtra("name", name); //this should pass the value of R.id.text2
startActivity(intent);
}
});
Related
I have been struggling using some tutorial for passing a listview option to a new activity and make it the title (I will do other stuff with it later). I have set up a OnClickListener by what is best to put inside it
ListView listView1 = (ListView) findViewById(R.id.sportslist);
String[] items = { "Archery", "Badminton", "Cricket", "Dodgeball", "Equestrian", "Football", "Golf", "Handball", "Ice Hockey", "Ju Jitsu", "Karate", "Lacrosse", "Mountain Biking", "Netball" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
listView1.setAdapter(adapter);
listView1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,int position, long id)
?????
}
});
Thanks
EDIT:Extra code
final TextView changetitle = (TextView) findViewById(R.id.detailedsocietyname);
changetitle.setText(name);
For of all you will need to get the item that was selected:
final String selected = items[position];
Or as doctoror drive has suggested
final String selected = (String) parent.getSelectedItem();
Then you will need to pass that string as an extra to your new activity
Intent i = new Intent(getApplicationContext(), MyClass.class);
i.putExtra("name", selected);
startActivity (i);
And then finally in your next activity
Intent in = getIntent();
String name = in.getStringExtra(("name"));//gets name from intent
public void onItemClick(AdapterView parent, View view,int position, long id)
String str = items[position];
Intent in = new Intent(getApplicationContext(), NextClass.class);
in.putExtra("itemkey", str);
startActivity (in);
}
in public void onItemClick(AdapterView<?> parent, View view,int position, long id) add this code.
Intent i = new Intent(getApplicationContext(), NextClass.class);
i.putExtra("selectedItem", items[position]);
startActivity (i);
for getting value in NextClass Activitiy :
String SelectedItem = getIntent().getStringExtra("selectedItem");
Add the following to you Activity where you have listview
following is the variable that will contain the value that you want to pass to other activity
Declare it before Oncreate statement
// Activity_1
public final static String send_to_other_activity="ListViewSelected_ID";
Add the following code to the listView1.setOnItemClickListener
Intent i= new Intent(Recipe_List.this,Recipe_View.class);
i.putExtra(send_to_other_activity, string.valueof(position));
// itz (key-value) pair on the left key thru which u will access it on other place. on the right value that you want to pass
// Iam passing posiion to other activity here
startActivity(i);
Now on other activity extract this value from the key by adding following statement to the oonCreate of other activity
//Activity_2
getdata_from_list =getIntent().getStringExtra(Activity_1.send_to_other_activity);
now you have teh desired value in getdata_from_list
I have a cursor in my main activity to query two columns of the database and display them using a simple cursor adapter.
private Cursor doQuery() {
return(db.getReadableDatabase().rawQuery("SELECT RestaurantID AS _id, RestaurantName, StoreNo "
+ "FROM RestaurantList ORDER BY RestaurantName", null));
}
public void onPostExecute() {
SimpleCursorAdapter adapter;
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB) {
adapter=new SimpleCursorAdapter(this, R.layout.activity_all_restaurants,
doQuery(), new String[] {
RestaurantDB.colRestaurantName,
RestaurantDB.colRestaurantStore },
new int[] { R.id.title, R.id.value },
0);
}
else {
adapter=new SimpleCursorAdapter(this, R.layout.activity_all_restaurants,
doQuery(), new String[] {
RestaurantDB.colRestaurantName,
RestaurantDB.colRestaurantStore },
new int[] { R.id.title, R.id.value });
}
setListAdapter(adapter);
}
What I want to do is that when the users click on a particular item, another activity will pop up giving the users more information, which means I need to display the data stored in many other columns of the same item too. My question is how I can do that. I thought I should use onListItemClick, but I don't know how to associate the item selected in the main activity to the new activity.
Also, in the main activity, I have two textviews in the list that display colRestaurantName and colRestaurantStore respectively. When I use onListItemClick, how can I just retrieve colRestaurantName?
I can do the following to retrieve the position, but I don't know how I can use it in the new activity:
#Override
public void onListItemClick(ListView parent, View v, int position,
long id){
Cursor c = ((SimpleCursorAdapter)parent.getAdapter()).getCursor();
selection = String.valueOf(c.getPosition());
Intent i = new Intent(AllRestaurants.this, RestaurantsInfo.class);
i.putExtra("restaurantSelection", selection);
startActivity(i);
}
Thanks.
implement onListItemClick for listview and get textview text and send it to next activity as:
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
TextView tv = (TextView)v.findViewById(R.id.title);
String strcolRestaurantName=tv.getText().toString();
Intent intent =new Intent(CurrentActivity.this,NextActivity.class);
Bundle bundle = new Bundle();
bundle.putString("RestaurantName",strcolRestaurantName);
intent.putExtras(bundle);
startActivity(intent);
}}
and in NextActivity get Intent as in onCreate :
Intent i = getIntent();
Bundle extras = i.getExtras();
String strRestaurantName = extras.getString("RestaurantName");
I have a listView which loads data from SQLite database and right now I would want to implement an onclicklistener to the list. When users click on the list, it should bring them to the next activity and load the corresponding data into TextView. My question is how would I pass the data of the list for example it is a list of "Topics" and user click on the topic "My Home". I want to pass the topic "My Home" to the next activity so that I know which corresponding data to be retrieved respectively.
How do I go about it? Do I "putExtras" to the new Intent? or there is another way. Below are part of my codes which display the listview:
ListView listContent = (ListView) findViewById(R.id.contentlist);
mySQLiteAdapter = new SQLiteAdapter(this);
mySQLiteAdapter.openToRead();
Cursor cursor = mySQLiteAdapter.queueAll();
startManagingCursor(cursor);
String[] from = new String[] { SQLiteAdapter.KEY_CONTENT };
int[] to = new int[] { R.id.text };
SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this, R.layout.listrow, cursor, from, to);
listContent.setAdapter(cursorAdapter);
mySQLiteAdapter.close();
//Onclick ListView setlistener
listContent.setTextFilterEnabled(true);
listContent.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent summaryIntent = new Intent(DocumentListActivity.this, ViewDocumentActivity.class);
// summaryIntent.putExtra("SummTopic", value);
}
});
EDITED:
This part is on the next activity.
Intent i = getIntent();
extraTopic = i.getStringExtra("SummTopic");
mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
Cursor allrows = mydb.rawQuery("SELECT * FROM "+ TABLE + " WHERE topic = \" " + extraTopic + " \" " , null);
Integer cindex = allrows.getColumnIndex("topic");
Integer cindex1 = allrows.getColumnIndex("text1");
Integer cindex2 = allrows.getColumnIndex("text2");
I got an error while retrieving from database:
android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 0
Please help.
Thank you.
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent summaryIntent = new Intent(DocumentListActivity.this, ViewDocumentActivity.class);
Cursor c = (Cursor)parent.getItemAtPosition(position);
summaryIntent.putExtra("SummTopic", c.getString(c.getColumnIndex(SQLiteAdapter.KEY_CONTENT)));
startActivity(summaryIntent);
}
or you can pass id (summaryIntent.putExtra("SummTopicId", id);) of this row and "ask db" in next Activity for Topic with this id
EDIT:
protected void onCreate(Bundle savedInstanceState){
Intent i = getIntent();
String extraTopic = i.getStringExtra("SummTopic");
//or long extraTopic = i.getLongExtra("SummTopic"); if you put id there (which is better)
mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
String[] args = new String[] { extraTopic };
//or String[] args = new String[] { Long.toString(extraTopic) }; with id version
Cursor singleRow = mydb.rawQuery("SELECT * FROM "+ TABLE + " WHERE topic=?" , args);
//args is better then escaping special chars in query
//and it should be single row so we've changed var name :)
if(singleRow.moveToFirst()){ //we should do moveToFirst before we can use Cursor
Integer cindex = allrows.getColumnIndex("topic");
Integer cindex1 = allrows.getColumnIndex("text1");
Integer cindex2 = allrows.getColumnIndex("text2");
//setup views and stuff ....
}else{
Toast.makeText(this, "Oops we did not find topic, detail activity was closed", Toast.LENGTH_SHORT).show();
finish();
}
}
After you have used setContentView(...) you need to reference your String and get the text such as...
EditText et = (EditText) findViewById(R.id.my_edit_text);
String theText = et.getText().toString();
To pass it to another Activity you use an Intent. Example...
Intent i = new Intent(this, MyNewActivity.class);
i.putExtra("text_label", theText);
startActivity(i);
In the new Activity (in onCreate()), you get the Intent and retrieve the String...
public class MyNewActivity extends Activity {
String uriString;
#Override
protected void onCreate(...) {
...
Intent i = getIntent();
uriString = i.getStringExtra("text_label");
}
}
EDITED :
to get String From Listview you can apply below code and get ITEM String and Pass it to Next Activity:
listContent.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String ITEM=listContent.getItemAtPosition(position);
//Intent summaryIntent = new Intent(DocumentListActivity.this, // ViewDocumentActivity.class);
// summaryIntent.putExtra("SummTopic", value);
}
});
You can use Intent for this.
Intent intent= new Intent(context,classname.class);
intent.putExtra("name",string);
You can get it in the target class name using intent.getextra().
I guess you are using an adapter to fill your list with some data. So you need to override getItem(int position) method in your adapter:
#Override
public Object getItem(int position) {
//Note that return type should be the same you you use to initilise items oof the adapter. E.g. String or some custom Topic class
Object someObject = mObjects[position];
return someObject;
}
Then you need to set an item click listener to you list
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Object someObject = adapterView.getItemAtPosition(i);
Intent i = new Intent(this, MyNewActivity.class);
i.putExtra("text_label", someObject.toString());
startActivity(i);
}
});
I created a SQLiteDatabase where I can see the items with the 'View' Button and clicking on it, I get the whole database into a ListView. In this ListView I would like the items to be clickable and if I click on them, I want to add a new entry to it with the same name, but another id. My code so far:
ListView lv;
ArrayList<String> todoItems = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, todoItems));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
hornot info = new hornot(this);
info.open();
Cursor c = info.getAllTitles();
if (c.moveToFirst())
{
do{
todoItems.add(c.getString(0) + " " + c.getString(1) + " " + c.getString(2));
}while (c.moveToNext());
}
if (todoItems.size() > 0)
{
lv.setAdapter(new ArrayAdapter<String>(sqview.this,android.R.layout.simple_list_item_1, todoItems));
}
lv.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//-/////////////////////////
}
});
info.close();
}
As you see, I put the database items into an array, then I put them into a ListView. With an upgrade button I can add items, so I think I need to do something same here.
In the dbhelper the createEntry function:
public long createEntry(String name, String hotness) {
ContentValues cv = new ContentValues();
cv.put(KEY_NAME, name);
cv.put(KEY_HOTNESS, hotness);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
In the main.java I convert the EditTexts to Strings then put the values into the database:
String name = sqlName.getText().toString();
String hotness = sqlHotness.getText().toString();
hornot entry = new hornot(dbhelp.this);
entry.open();
entry.createEntry(name, hotness);
entry.close();
So what should I write for the onItemClick function?
In the onItemClick() method you have the position parameter that indicates the position(in the adapter) of the list row that was clicked. You could then use getItemAtPosition on the ListView to get the data from the row:
lv.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String rowData = (String) lv.getItemAtPosition(position); //you'll need to make the lv as final
String[] data = rowData.split(" "); //split the result using the spaces (so you could obtain the name, hotness and the other string you use)
entry.createEntry(data[0], data[1]);
}
I don't know your database structure so I can't recomend you something about unique id.
I'm trying to get the database id of a ListView member so that I can pass it to a new activity but the .getItemId(position) method of SimpleCursorAdapter is returning null, instead of the _id from the database. It was my understanding that this should return the _id field grabbed by the cursor, but it's not working out for me. Would love some suggestions
DatabaseHelper helper = new DatabaseHelper(this);
database = helper.getWritableDatabase();
Cursor data = database.query("myDb", fields, null, null, null, null, null);
dataSource = new SimpleCursorAdapter(this, R.layout.row, data, fields, new int[] {R.id.idText, R.id.castName, R.id.castDescription});
data.moveToFirst();
final ListView view = getListView();
view.setHeaderDividersEnabled(true);
view.addHeaderView(getLayoutInflater().inflate(R.layout.row, null));
setListAdapter(dataSource);
database.close();
view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
// Prepare intent
Intent newActivity = new Intent(getApplicationContext(), ItemIdTester.class);
newActivity.putExtra("itemId",dataSource.getItemId(position));
// start activity
startActivity(newActivity);
}
});
The adapter was returning null because of the headers added by
view.setHeaderDividersEnabled(true);
view.addHeaderView(getLayoutInflater().inflate(R.layout.row, null));
I also started getting my data directly from the cursor. Here is the full onItemClickListener that fixed the issue
view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
Cursor cursor = (Cursor) dataSource.getItem(position-1);
Long itemId = cursor.getLong(0);
// Prepare intent
Intent newActivity = new Intent(getApplicationContext(), CastrRecorder.class);
newActivity.putExtra("itemId",itemId.toString());
// start activity
startActivity(newActivity);
}
});