jZhou
jZhou

Reputation: 23

Is Android onCreate method a static context?

I'm currently working on a news reader app where I store info that I retrieved from an API and loaded into an SQLite database. I initialized a db variable to a new custom class that holds the database, but when I try to access it from another activity, I am given a "non-static variable db cannot be referenced from a static context" error message.

Where I am initializing the field:

public class MainActivity extends AppCompatActivity {

    public NewsReaderDb db;
    private RecyclerView headlinesRecyclerView;
    private RecyclerView.Adapter headlinesAdapter;
    private LinearLayoutManager headlinesManager;
    List<String> headlinesList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Setting up connection to SQLite database
        db = new NewsReaderDb(this);

Where I am trying to use it:

public class ArticleActivity extends AppCompatActivity {

    WebView webView;
    Intent data;
    NewsReaderDb database;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_article);
        // Setting up webview
        webView = findViewById(R.id.webview);
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setUseWideViewPort(true);
        webView.getSettings().setBuiltInZoomControls(true);
        webView.setWebViewClient(new HelloWebViewClient());

        data = getIntent();
        // OFFENDING LINE:
        database = MainActivity.db;

The NewsReaderDb class:

public class NewsReaderDb {

    private NewsReaderDbHelper dbHelper;
    private SQLiteDatabase db;

    public NewsReaderDb(Context context) {
        // Accessing database in writable format
        dbHelper = new NewsReaderDbHelper(context);
        db = dbHelper.getWritableDatabase();
    }

It doesn't make sense to me that the onCreate method would be static, but are activities inherently static?

Upvotes: 1

Views: 206

Answers (1)

siralexsir88
siralexsir88

Reputation: 418

The context in which you attempt to access MainActivity.db is static since you use the class name. You would need a reference to an instance of the MainActivity class to access its db member. Since you're accessing it from a different activity, the MainActivity instance is likely already destroyed so you will need another means of accessing the db value.

Depending on your NewsReaderDB implementation, you could just initialize a new NewsReaderDB in the OnCreate of ArticleActivity.

Upvotes: 1

Related Questions