user4095898
user4095898

Reputation:

Cannot get the Context when using AppCompatAcitvity

I'm trying to pass the Context to my ListViewAdapter class using:

    private ContactAdapter adapter = new ContactAdapter(this);

But I'm getting a null pointer in my ContactAdapter class, it cannot find the Context:

public class MainActivity extends AppCompatActivity {

Logcat:

 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
        at info.androidhive.materialnavbar.ContactAdapter.readTextFileAsList(ContactAdapter.java:67)
        at info.androidhive.materialnavbar.ContactAdapter.<init>(ContactAdapter.java:30)
        at info.androidhive.materialnavbar.MainActivity.onCreate(MainActivity.java:18)

Method inside Adapter using the context:

    public List<Contact> readTextFileAsList(Context ctx, int resId)
{
    InputStream inputStream = ctx.getResources().openRawResource(resId);

    InputStreamReader inputreader = new InputStreamReader(inputStream);
    BufferedReader bufferedreader = new BufferedReader(inputreader);
    String line;
    List<Contact> list = new ArrayList<>();

    try
    {
        while (( line = bufferedreader.readLine()) != null)
        {
            String[] a = line.split(";");
            list.add(new Contact(a[0],a[1],a[2],a[3],a[4]));
        }
    }
    catch (IOException e)
    {
        return null;
    }
    return list;
}

When the adapter get's initialized:

underneath the constructor

public class ContactAdapter extends BaseAdapter {
    Context ctx;

public ContactAdapter(Context ctx) {
    this.ctx = ctx;
}

private List<Contact> codeLearnChapterList = readTextFileAsList(ctx, R.raw.testcrawljs);

Upvotes: 0

Views: 2480

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006849

Do not use an Activity in an initializer, as the activity is not ready yet. Change:

private ContactAdapter adapter = new ContactAdapter(this);

to:

private ContactAdapter adapter;

And add:

adapter = new ContactAdapter(this);

to your onCreate() method, somewhere after super.onCreate().


UPDATE

private List<Contact> codeLearnChapterList = readTextFileAsList(ctx, R.raw.testcrawljs);

ctx is null here, because you have not assigned a value to it yet. Move the readTextFileAsList() call into the constructor.

Upvotes: 3

Related Questions