Andy
Andy

Reputation: 10830

Is any class considered a Context in android or is there something specific that must be done?

I have this class, omitting the code to make it more readable:

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ListView;
public class TimeTrackerActivity extends Activity {

    //some code here
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    ListView listView = (ListView) findViewById(R.id.times_list);

    listView.setAdapter(timeTrackerAdapter);

    TimeTrackerOpenHelper openHelper = new TimeTrackerOpenHelper(this);
    //my error with line of code right above saying
    //the constructor of TimeTrackerOpenHelper(TimeTrackerActivity) is undefined

    }
    //more code here
}

I commented where my error is. I have looked at other example online and everyone else is sending this in to the class that extends SQLiteOpenHelper, which leads me to assume that it should be working. But its not. My code is as follows:

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class TimeTrackerOpenHelper extends SQLiteOpenHelper {

TimeTrackerOpenHelper(Context context) {
    super(context, "timetracker.db", null, 1);
}

public void onCreate(SQLiteDatabase database) {/*stuff*/}

public void onUpgrade(SQLiteDatabase datbase, int oldVersion, int newVersion) {/*stuff*/}

}

Is my assumption wrong and is there something I am missing.

Upvotes: 1

Views: 227

Answers (3)

Tony the Pony
Tony the Pony

Reputation: 41357

Since Activity derives from android.content.Context, your code should compile without an error, as long as the Context class used by TimeTrackerOpenHelper(Context context) is also an android.content.Context, and not a Context class from a different package.

EDIT

Thanks to superfell's comment, I think the problem is the visibility of TimeTrackerOpenHelper's constructor. Try making it public:

public TimeTrackerOpenHelper(Context context) {

Upvotes: 2

Gökhan Barış Aker
Gökhan Barış Aker

Reputation: 4535

Android Activity is a subclass of Context. See Activity source. And no, not every class is considered a Context in Android. You have to extend Context but i don't think you would want to perform such a thing and need to.

Upvotes: 0

Simone Casagranda
Simone Casagranda

Reputation: 1215

No the only "class" that contains a context reference are Activities and Services. If you use for example a BroadcastReceiver you receive in your listener method the context reference.

Upvotes: 0

Related Questions