启动TextView时,在getapplicationContext()中使用Java.lang.NullPointerException

时间:2016-01-04 15:57:00

标签: android nullpointerexception

public final class ConnectAsync extends AsyncTask<Void, String, String>
{
    private MainActivity mActivity = new MainActivity();
    private TextView mTextView;

    // other codes...

    @Override
    protected void onProgressUpdate(String... params)
    {
        // exception throws in this line
        mTextView = new TextView(mActivity.getApplicationContext());
    }
}

我调用了publishProgress(myString + " five");并希望生成TextView运行时。但NullPointerException抛出。怎么了?

你能解释一下吗?

感谢。

1 个答案:

答案 0 :(得分:2)

尝试使用活动上下文代替应用程序上下文代码:

public final class ConnectAsync extends AsyncTask<Void, String, String>
{
    private Context context;
    // other codes...

    public ConnectAsync(Context context)
    {
        this.context = context;
    }

    @Override
    protected void onProgressUpdate(String... params)
    {
        // exception throws in this line
        mTextView = new TextView(context);
    }
}

我无权发表评论。*