AsyncTask总是返回NPE

时间:2018-06-20 13:24:01

标签: android nullpointerexception

我是Android的新手程序员,我很困在这里,实现了这一点,想用此块在EditText中打印出网址内容。

private class MyTask extends AsyncTask<String, Void, String> {
    Activity activity;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... strings) {
        String url = strings[0];

        try {
            StringBuilder sb = new StringBuilder();
            URL link = new URL(url);
            BufferedReader in;
            in = new BufferedReader(new InputStreamReader(link.openStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null)
                sb.append(inputLine);
            in.close();
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
@Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        EditText editText = activity.findViewById(R.id.edittext);
        editText.setText(s);
    }

主要活动(onCreate):如下

        new MainActivity.MyTask().execute("http://yahoo.com");

这是我看中的错误:/

  

06-20 19:09:08.466 31168-31175 /?电子/艺术:无法将回复发送到调试器:       断管       06-20 19:09:09.563 31168-31168 / com.curiosityworks.www.weatherlite       E / AndroidRuntime:致命异常:main
      流程:com.curiosityworks.www.weatherlite,PID:31168
      java.lang.NullPointerException:尝试调用虚拟方法        空对象引用上的'android.view.View android.app.Activity.findViewById(int)'                                                                                           在com.curiosityworks.www.weatherlite.MainActivity $ MyTask.onPostExecute(MainActivity.java:102)                                                                                           在com.curiosityworks.www.weatherlite.MainActivity $ MyTask.onPostExecute(MainActivity.java:70)                                                                                           在android.os.AsyncTask.finish(AsyncTask.java:667)                                                                                           在android.os.AsyncTask.-wrap1(AsyncTask.java)                                                                                           在android.os.AsyncTask $ InternalHandler.handleMessage(AsyncTask.java:684)                                                                                           在android.os.Handler.dispatchMessage(Handler.java:102)                                                                                           在android.os.Looper.loop(Looper.java:163)                                                                                           在android.app.ActivityThread.main(ActivityThread.java:6377)                                                                                           在java.lang.reflect.Method.invoke(本机方法)                                                                                           在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:904)                                                                                           在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)

请指导我,我正在浪费很多宝贵的时间来弄清楚,这将是很大的帮助。

2 个答案:

答案 0 :(得分:0)

您有一个字段

Activity activity;

这是空的,因为您从未分配它。

您尝试在onPostExecute中访问它,这将导致一个空指针。换句话说,该活动在onPostExecute中不存在。

我不知道您其余的代码是什么样子,所以我不能给您新代码,但是我建议您阅读AsyncTasks的工作方式(或者甚至更好,请使用RxJava,无论如何这是一个示例http://www.vogella.com/tutorials/AndroidBackgroundProcessing/article.html

答案 1 :(得分:-1)

公共类MainActivity扩展了活动{

public class DownloadTask extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... urls) {

        String result = "";
        URL url;
        HttpURLConnection urlConnection = null;

        try {

            url = new URL(urls[0]);

            urlConnection = (HttpURLConnection)url.openConnection();

            InputStream in = urlConnection.getInputStream();

            InputStreamReader reader = new InputStreamReader(in);

            int data = reader.read();

            while (data != -1) {

                char current = (char) data;

                result += current;

                data = reader.read();

            }

            return result;

        }
        catch(Exception e) {

            e.printStackTrace();

            return "Failed";

        }


    }

}

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

    DownloadTask task = new DownloadTask();
    String result = null;

    try {

        result = task.execute("//website").get();
        editText.setText(result);


    } catch (InterruptedException e) {

        e.printStackTrace();

    } catch (ExecutionException e) {

        e.printStackTrace();

    }

    Log.i("Contents Of URL", result);

}