Md. Abdullah
Md. Abdullah

Reputation: 17

When Calling Other Activity Method Showing NullPointerException

I have two activity (PrivateContactActivity.java and AddContact.java). Inside PrivateContactActivity have a method:-

PrivateContactActivity.java

public void databaseLoader() {
    privateList.clear();
    myDatabase = new MyDatabase(PrivateContactActivity.this);
    Cursor cursor = myDatabase.queryData();
    StringBuilder stringBuilder = new StringBuilder();
    if (cursor.getCount() == 0) {
        Toast.makeText(this, "No Contact Found", Toast.LENGTH_SHORT).show();
    } else {
        while (cursor.moveToNext()) {
            String name, phone, email, address;
            name = cursor.getString(1);
            phone = cursor.getString(2);
            email = cursor.getString(3);
            address = cursor.getString(4);

            PrivateContactModel privateContactModel = new PrivateContactModel(name, phone, email, address);
            privateList.add(privateContactModel);
        }
    }
}

AddContact.java

@Override
public void onBackPressed() {
    PrivateContactActivity privateContactActivity = new PrivateContactActivity();
    privateContactActivity.databaseLoader();
    super.onBackPressed();
}

and when i am calling this method from AddContact activity then showing NullPointerException. Why this problem? I face this kind of problem often. I solved this from kind of problem in another way but don't know why this problem. Please explain me.

Upvotes: 1

Views: 43

Answers (1)

David Wasser
David Wasser

Reputation: 95578

You absolutely positively cannot instantiate an Activity with the keyword new. Only Android can instantiate Android components (Activity, Service, BroadcastReceiver, Provider). The Context isn't correctly set up when you instantiate an Android component using new, which is why you get a NullPointerException.

To get around this you can declare your method databaseLoader() as static and pass a Context argument into it which can be used as necessary. When calling this method from any Activity you can pass this as the Context argument.


Also, it isn't clear why you would need to load your database in onBackPressed(), since onBackPressed() just finishes the Activity anyway and it will be destroyed. This seems strange.

Upvotes: 1

Related Questions