使用AppCompatAcitvity时无法获取上下文

时间:2015-06-16 11:48:39

标签: java android

我试图通过以下方式将Context传递给我的ListViewAdapter课程。

    private ContactAdapter adapter = new ContactAdapter(this);

但我在ContactAdapter课程中收到空指针,找不到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)

使用上下文在Adapter内的方法:

    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;
}

当适配器初始化时:

在构造函数下面

public class ContactAdapter extends BaseAdapter {
    Context ctx;

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

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

1 个答案:

答案 0 :(得分:3)

请勿在初始化程序中使用Activity,因为活动尚未准备就绪。变化:

private ContactAdapter adapter = new ContactAdapter(this);

为:

private ContactAdapter adapter;

并添加:

adapter = new ContactAdapter(this);

onCreate()之后的super.onCreate()方法。

<强>更新

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

ctx此处为null,因为您尚未为其指定值。将readTextFileAsList()调用移动到构造函数中。