1

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

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<String> results = new ArrayList<String>();
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<String>(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();
}

}

1
  • vogella.com/articles/AndroidSQLite/… is a nice tutorial on all sorts of SQLite related things. You should especially look at SQLiteOpenHelper that is used to open a database and the DataSource class that is used to access the data.
    – zapl
    Apr 28, 2012 at 22:55

1 Answer 1

0

The best way to share objects (database in your case) between activities while your application is running is by creating a class which extends Application

This class gets created before any activity is created and it will run until you app is destroyed. The way to access you application class from your activities is by doing

YourApplication app = (YourApplication) getAppliation();

Remember to add the name of you application on you manifest just like you would for your activies.

UPDATE

What I would do is first create a class to handle your database

public class DataBaseData {

private Context context;
private DbHelper dbHelper;

public DataBaseData(Context context){
    this.context = context;
    dbHelper = new DbHelper();
}

public void close(){
    dbHelper.close();
}

public void insert(){
    you insert method here
}


public void delete(int id){
}

public Cursor query(){
}

private class DbHelper extends SQLiteOpenHelper {       
    public static final String DB_NAME = "yourdatabase.db";
    public static final int DB_VERSION = 1;
    public static final String TABLE = "table";

    public DbHelper() {
        super(context, DB_NAME, null, DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
         create tables here
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("drop table if exists " + TABLE);
        Log.d(TAG, "onUpdate dropped table " + TABLE);
        this.onCreate(db);
    }
}

}

Then in your application class do something like this

private DataBaseData dataBaseData = null;

@Override
public void onCreate() {
    super.onCreate();

    Log.d(TAG, "onCreate started");

    setDataBaseData(new DataBaseData(this));


}

public DataBaseData getDataBaseData() {
    return dataBaseData;
}

public void setDataBaseData(DataBaseData dataBaseData) {
    this.dataBaseData = dataBaseData;
}

Now you will be able to access you database from anywhere once you get a handle to the application.

3
  • If I try that it says Database (my application name) cannot be resolved to a variable. Apr 28, 2012 at 23:44
  • If I create my database using that class it messes up the line this.setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,results)); what can I use instead? Apr 29, 2012 at 0:31
  • I should not make a difference. You are just moving your db querys/inserts to another class but still been able to access them through the application class. Once you get a handle to the application by: YourAppliation app = (YourApplication) getApplication; is only a matter of doing something like: DatabaseData db = app.getDatabaseData(); and then is simple as: db.insert(); etc. You will need to rearrenge things a bit but it will much better at end. If you like have a look at how I've done it on this app --> github.com/heepie/sBrowser
    – codeskraps
    Apr 29, 2012 at 1:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.