Search code examples
androidsqliteandroid-intentandroid-sqliteonclicklistener

ListView Generated from SQLite onClickListener() to take me to another activity based on where i clicked


I'm creating an android app. In this app, I have a ListView populated with data from SQLite. I am trying to add an onClickEventListener to each row of the ListView so that when a menu item is clicked it opens up another Activity with more information from the Database about the item clicked. I have succeeded in adding an event listener to the ListView, but I am not sure how to pass on database information depending on the list item clicked.

Here is my code:

public class MainActivity extends AppCompatActivity {

private DatabaseHelper dbh;
private ArrayList listItems = new ArrayList();

ArrayList<String[]> noteList;
private ArrayAdapter adapter;
private ListView lv;

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

    dbh = new DatabaseHelper(this);
    dbh.open();

    lv = (ListView) findViewById(R.id.noteListView);

    noteList = dbh.selectAll();
    String id = "";
    String content = "";

    for(int i = 0; i < noteList.size(); i++){
        content = noteList.get(i)[1];
        id = noteList.get(i)[0];
        listItems.add(id + ", " + content);
    }

    ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, listItems);

    lv.setAdapter(arrayAdapter);

    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view,int position, long id) {

            Intent i = new Intent(MainActivity.this, EditNote.class);

            //i.putExtra();

            startActivity(i);
        }
    });
}

}

Solution

  • In your case list has strings, so here is what you need to do:

    String yourString = listItem.get(position);
    i.putExtra("KEY", yourString);
    startActivity(i); 
    

    And at the receiving activity you can retrieve as

    intent intent = getIntent();
    String yourString = intent.getExtras().getString("KEY");
    

    EDIT: If your list is having some POJO class or simple class objects

    You can pass to second activity like this

    intent.putExtra("Your class", obj);
    

    To retrieve object in second Activity

    getIntent().getSerializableExtra("Your class");
    

    EDIT: One important thing to remember.

    If you passing a class object it must implement Serializable or Parcelable interface.
    For eg

    class Student implements Serializable{
    
    }