I have a list that is populated by an sqlite database. What I am trying to do is pass the value of the clicked row – which is a string (NOT the row ID) – into a new activity. For example, if I have this list…
Apples
Bananas
Carrots
…
Etc.
…and I click on ‘Bananas’, I would like ‘Bananas’ to be passed to the new activity. I can get this to work, but ONLY for the first item in the list. All other list items also return the same value (namely ‘Apples’). Here is the code I am using…
private AdapterView.OnItemClickListener onListClick=new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent,
View view, int position,
long id)
Intent i=new Intent(MyApp.this, MyActivity.class);
TextView nameValue = (TextView)findViewById(R.id.ingredientText);
String content = nameValue.getText().toString();
i.putExtra(ID_EXTRA, String.valueOf(content));
startActivity(i);
}
};
Again, this code returns the value of ‘Apples’ regardless of which row is clicked. Perhaps I have taken the wrong approach on this as I am still new to working with databases in Android. Could someone please advise why the above code is wrong and how I might be able to correct it? Thanks in advance for any help.
The other answers are correct. But if you prefer to get the value directly from the view, you need to call findViewById on the View passed into onItemClick:
In your original code it looks like your calling it on your activity’s whole view tree, which is why you keep getting the same result.