Note that there are some explanatory texts on larger screens.

plurals
  1. POAccessing SQLite database from another class
    primarykey
    data
    text
    <p>I've created a sample SQLite database in Android that reads entries into a ListView. I'm going to add code so that when clicked, each ListView item starts a new activity to display more information. How can I run queries on this database from within another activity? Thanks</p> <pre><code>public class Database extends ListActivity { private final String SAMPLE_DB_NAME = "myFriendsDb"; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ArrayList&lt;String&gt; results = new ArrayList&lt;String&gt;(); SQLiteDatabase db = null; try { db = this.openOrCreateDatabase(SAMPLE_DB_NAME, MODE_PRIVATE, null); db.execSQL("CREATE TABLE IF NOT EXISTS people" + " (LastName VARCHAR, FirstName VARCHAR," + " Country VARCHAR, Age INT(3));"); db.execSQL("INSERT INTO people" + " Values ('Jones','Bob','UK',30);"); db.execSQL("INSERT INTO people" + " Values ('Smith','John','UK',40);"); db.execSQL("INSERT INTO people" + " Values ('Thompson','James','UK',50);"); Cursor c = db.rawQuery("SELECT FirstName, LastName FROM people", null); if (c != null ) { if (c.moveToFirst()) { do { String firstName = c.getString(c.getColumnIndex("FirstName")); String lastName = c.getString(c.getColumnIndex("LastName")); results.add("" + firstName + " " + lastName); }while (c.moveToNext()); } } this.setListAdapter(new ArrayAdapter&lt;String&gt;(this, android.R.layout.simple_list_item_1,results)); } catch (SQLiteException se ) { Log.e(getClass().getSimpleName(), "Could not create or Open the database"); } finally { if (db != null) db.execSQL("DELETE FROM people"); db.close(); } </code></pre> <p>}</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload