Search code examples
androidlistviewsimplecursoradapter

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

Solution

  • 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);