mercredi 20 mai 2015

How to retrieve data from a particular db table in a new activity as a result of selecting a list item from a db table in the previous activity

I need some help here, I am retrieving a list of items (categories) from a database table in the main activity and that’s all working well. The issue is that the user is supposed to click on one of the items which will cause another table in the db to be queried but in another activity (workbook.java). So how do I carry the IDs of the categories clicked to the next activity and also know exactly which item was clicked so that the right table is queried?

Code that retrieves the categories from one db table and presents them in a list view and also the method to handle clicks on the list items: MainActivity.java

@SuppressLint("NewApi")
public void displayCategories(){
    cursor = dbhelper.getCategories();
    String[] FROM = { FeedReaderDbHelper.KEY_CATEGORY_NAME};
    int[] TO = {R.id.textView1};
    adapter = new SimpleCursorAdapter(this, R.layout.row_item, cursor, FROM, TO, 0);
    categories = (ListView) findViewById(android.R.id.list); 
    categories.setAdapter(adapter);
    categories.setOnItemClickListener(new ListClickHandler());
}

public class ListClickHandler implements OnItemClickListener{
@Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long arg3) {
    // TODO Auto-generated method stub
    TextView category_text = (TextView) view.findViewById(R.id.textView1);
    String category = category_text.getText().toString();
    Intent intent = new Intent(MainActivity.this, WorkBook.class);
    intent.putExtra("selected-item", category);
    intent.putExtra("item-ID", position);
    startActivity(intent);
}
}

The code below is in WorkBook.java which is supposed to query another table basing on the category selected in the previous activity (MainActivity.java):

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.work_book);
    text = (TextView) findViewById(R.id.text);

    //get the intent from which this activity is called
    Intent intent = getIntent();
    //fetch value from key-value pair and make it visible on textView
    String category = intent.getStringExtra("selected-item");
            text.setText("You are here: "+category);

}

So how do I track which category a user selects in MainActivity.java in order to query the respective table in WorkBook.java.

Thanks for the help

Aucun commentaire:

Enregistrer un commentaire