Newaj Kabir Newaj Kabir - 1 month ago 9
Android Question

How to pass text from listView item to a new activity

I am using SimpleCursorAdapter to fetch data from SQLite database to a listView. Now I am trying to open an activity which will contain the text from the listView. I have written the code, but wherever I click, it is showing only the first item's text. Code is given below:

listView.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub

textView = (TextView) findViewById(R.id.tvListItem);

String text = textView.getText().toString();

Intent intent = new Intent(getApplicationContext(), SingleActivity.class);
intent.putExtra("com.example.practise.write", text );
startActivity(intent);

}

});


Code in SingleACtivity class :

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single);

textTextView = (TextView) findViewById(R.id.tvWrite);

Intent intent = getIntent();
String write = intent.getStringExtra("com.example.practise.write");

textTextView.setText(write);
}

Answer

You need to get the textview of selected item then you will get the correct value If list item is just the TextView you can cast it to TextView like this

TextVie view = (TextView) view; 

or if your textview is a sub view of your list item view then do this.

TextView textView = (TextView) view.findViewById(R.id.tvListItem);