views:

89

answers:

2

I'm still very new to Object Oriented programming and am having problems with the class inheritance and the scope of variables from one instantiated class to another.

I'm trying to build an android application that can read multiple XML feeds and save them to the phone's SQLite database. Each feed has a different name ("news", "audio_mixes" etc.) and I want to use these names to save each feed's data into separate database tables - each one named after the feed title.

In diagrammatic terms this is what my classes look like: alt text

The Main activity displays two buttons each of which starts an activity - both of which are instances of the TitlesBrowser class. Extras are used to pass different values of the_url and the_feed_type variables.

@Override
    public void onCreate(final Bundle icicle) {
        super.onCreate(icicle);
        this.setContentView(R.layout.main);

        this.getNewsButton = (Button) findViewById(R.id.get_news_button);
        this.getNewsButton.setOnClickListener(new OnClickListener() {

            public void onClick(final View v) {
                Intent doGetNews = new Intent(Main.this, TitlesBrowser.class);
                doGetNews.putExtra("the_url", Main.this.getString(R.string.titles_url));
                doGetNews.putExtra("the_feed_type", Main.this.getString(R.string.news_type_var));
                startActivity(doGetNews);
            }
        });

        this.getMixtapesButton = (Button) findViewById(R.id.get_mixtapes_button);
        this.getMixtapesButton.setOnClickListener(new OnClickListener() {

            public void onClick(final View v) {
                Intent doGetMixtapes = new Intent(Main.this, TitlesBrowser.class);
                doGetMixtapes.putExtra("the_url", Main.this.getString(R.string.titles_url));
                doGetMixtapes.putExtra("the_feed_type", Main.this.getString(R.string.mixtapes_type_var));
                startActivity(doGetMixtapes);
            }
        });

    }

The TitlesBrowser class, in its onCreate method, gets the Extras and saves them to private local variables.

Intent i = getIntent();
private String theUrl = (String) i.getStringExtra("the_url");
private String theFeedType = (String) i.getStringExtra("the_feed_type");</pre>

This class does two things,

1/ it creates an instance of the DatabaseHelper class, and uses a public set method in that class to pass on the value of the locally help theFeedType variable. Having done that it queries the database for any existing data (the theFeedType is the name of each table)

db=new DatabaseHelper(this);
db.setTableName(theFeedType);

dbCursor=db.getReadableDatabase().rawQuery("SELECT _ID, id, title FROM "+theFeedType+" ORDER BY id",    null);

2/ then it loads new data from the feed URL by instantiating another class HTTPRequestHelper :

HTTPRequestHelper helper = new HTTPRequestHelper(responseHandler);
helper.performPost(theUrl, theFeedType);

The HTTP requests work fine, and depending on which of the two buttons is clicked, each of the two different activities display the appropriate XML (i.e. retrieve the correct data) - therefore I know that theUrl and theFeedType variables are local to each instance of the TitlesBrowser class. One calls:

http://baroquedub.co.uk/get-feed.php?feed=news

and the other one:

http://baroquedub.co.uk/get-feed.php?feed=audio_mixes

The problem is with the DatabaseHelper class:

public class DatabaseHelper extends SQLiteOpenHelper {
  private static final String DATABASE_NAME="baroquedub.db";
  private String table_name;


  public DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, 1);
  }

  @Override
  public void onCreate(SQLiteDatabase db) {
    db.execSQL("CREATE TABLE "+ table_name + "(_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
                "id INTEGER, " +
                "title TEXT, " +
                "details TEXT, " +
                "picture TEXT, " +
                "viewed BOOLEAN DEFAULT '0' NOT NULL);");
  }

  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    android.util.Log.w("Baroquedub", "Upgrading database, which will destroy all old data");
    db.execSQL("DROP TABLE IF EXISTS mixtapes");
    onCreate(db);
  }

  public void setTableName(String theName){
    this.table_name = theName;
  }
}

I would expect it to create a new table each time it is instantiated (whether "news" or "audio_mixes" was passed from its parent TitlesBrowser class.

But it only works once - if I start the application and click on "news" a table called news is created and each time I return to that activity it successfully retrieves data from that same database.

But if I then start the other activity by clicking on the other button (i.e access the other feed) I get an SQL error telling me that a database of that name doesn't exist. In other words the onCreate db.execSQL("CREATE TABLE... method doesn't appear to get called again.

It's as if multiple copies of the DatabaseHelper class aren't being created, although there are two instances of TitlesBrowser.

-- Here's a demonstration of the problem:

http://screencast.com/t/NDFkZDFmMz

This has been really tricky to explain (especially for a newbie!!!) and I hope it makes some sense. I'd be very grateful for any help, advice or guidance.

A: 

When you instanciate a SQLiteOpenHelper class you actually access a singleton in the Activity's context. The helper decides when to call the OnCreate / onUpgrade methods - specifically, if the DB doesn't exist or is stale.

Either way, the onCreate method is not called each time you create a new instance of the class - that would really make no sense. You should put the two CREATE TABLE commands in the onCreate method.

(PS I assume the error you're getting is that a table is missing and not the entire database).

adamk
Aah! I'd heard of Singletons but didn't realise that the SQLiteOpenHelper class was one. How would I know looking at the Android docs? I can't see it mentioned in the reference class definition.Also I'm not sure I quite understand why having multiple instances of the databaseHelper (each containing their own value for table_name) would not make sense - but your answer helped me find a solution - thank you!
baroquedub
A: 

A big thank you to adamk for providing the guidance necessary to solve this, in the answer he provided.

He suggested that I add two CREATE TABLE commands in the DatabaseHelper's onCreate method (on for each of my feeds). However, I needed to abstract things a little more so that I could still use multiple instantiations of the TitlesBrowser activity and so that I wouldn't have to rewrite the helper class every time a new feed came on board.

For those interested, here's the solution I came up with.

First of all, I removed the CREATE TABLE commands in the DatabaseHelper's onCreate method. I also removed the private table_name variable (and its associated set method) and I replaced this with a public method called makeTable():

public class DatabaseHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME="baroquedub.db";

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        android.util.Log.w("Baroquedub", "Upgrading database, which will destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS mixtapes");
        onCreate(db);
    }

    public void makeTable(String theTableName){
        SQLiteDatabase thisDB = DatabaseHelper.this.getWritableDatabase();
        thisDB.execSQL("CREATE TABLE IF NOT EXISTS "+ theTableName + "(_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
                "id INTEGER, " +
                "title TEXT, " +
                "details TEXT, " +
                "picture TEXT, " +
                "viewed BOOLEAN DEFAULT '0' NOT NULL);");
    }
}

In TitlesBrowser, rather than instantiating the DatabaseHelper, setting the table name and then reading in the data:

db=new DatabaseHelper(this);
db.setTableName(theFeedType);

dbCursor=db.getReadableDatabase().rawQuery("SELECT _ID, id, title FROM "+theFeedType+" ORDER BY id",    null);

Instead, I reworked all this so that it would more elegantly handle the creation and loading of the database data from each table:

  1. The database Helper is created as before,
  2. then the new databaseLoad() method tries to read from the required table
  3. and if it can't, it calls the DatabaseHelper's public makeTable() method,
  4. before finally trying to load the data again:
   @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent i = getIntent();
        theUrl = (String) i.getStringExtra("the_url");
        theFeedType = (String) i.getStringExtra("the_feed_type");

        // show saved in DB 
        db=new DatabaseHelper(this);
        databaseLoad();

    }

    private void databaseLoad(){
        try { // table exists
            dbCursor=db.getReadableDatabase()
                        .rawQuery("SELECT _ID, id, title FROM "+theFeedType+" ORDER BY id", null);

            displayContent();

        } catch (Exception e) { // table doesn't exist
            db.makeTable(theFeedType);
            databaseLoad(); // try again
        }
    }
baroquedub