Home » Android » android – Select on ListView items and show users different tables of the database-Exceptionshub

android – Select on ListView items and show users different tables of the database-Exceptionshub

Posted by: admin February 26, 2020 Leave a comment


I am building a wordsearch game and I have a listview in the MainActivity which when I click on 1 item on the list, it should open the particular table (TABLE_NAME) in the database. How can i call the TABLE_NAME from the MainActivity without hardcoding the TABLE_NAME in the SQLiteAssetHelper?

Thank you very much for your help.

Code snippet from the MainActivity:

 listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                if (position == 0) {
                    Intent myIntent = new Intent(view.getContext(), GameActivity.class);
                    String tableName="heart";
                    myIntent.putExtra("TABLE_NAME", tableName);
                    startActivityForResult(myIntent, 0);

Code Snippet from the GameActivity

private void selectWords(){
    String count = Settings.getStringValue(this, getResources().getString(R.string.pref_key_num_words_to_select), "1000");

    WSDatabase wsd = new WSDatabase(this);
    Intent myIntent = getIntent();
    String tableName = myIntent.getStringExtra("TABLE_NAME");

    wordList = wsd.getRandomWords(Integer.parseInt(count));

Code from the WSDatabase

public class WSDatabase extends SQLiteAssetHelper {

private static final String DATABASE_NAME = "wordsearchfinal.db";
private static final int DATABASE_VERSION = 1;
private String TABLE_NAME = "heart"; // i would like to get this table name from the listview on the MainActivity

private Context context;
private SQLiteDatabase database;

public WSDatabase(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
    this.context = context;

public void open(){
    database = getReadableDatabase();

public String[] getRandomWords(int count){
    Cursor cursor = database.query(TABLE_NAME +" Order BY RANDOM() LIMIT " + count, new String[] { "*" }, null, null, null, null, null);
    int len = cursor.getCount();
    String[] words = new String[len];
    int i = 0;
    while (!cursor.isAfterLast()) {
        words[i++] = cursor.getString(0);
    return words;
How to&Answers: