java.lang.NullPointerException:尝试在空对象引用上调用

java.lang.NullPointerException: Attempt to invoke virtual method #39;android.view.View .MainActivity.findViewById(int)#39; on a null object reference(java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“android.view.View .MainActivity.findViewById(int)) - IT屋-程
本文介绍了java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“android.view.View .MainActivity.findViewById(int)"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 MainActivity.java 的类,它调用了一个 AsyncTask 类.最后一个类有一个 findViewById() 在执行时返回这个错误:

I have a class called MainActivity.java that call an AsyncTask class. The last class have a findViewById() that in execution return this error:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View <mypackage>.MainActivity.findViewById(int)' on a null object reference

我不明白如何在 AsyncTask 完成工作后编辑位于 R.layout.activity_main 中的 ImageView.

I don't understand how can I edit an ImageView positioned in R.layout.activity_main after that an AsyncTask finish to work.

MainActivity.java

public class MainActivity extends Activity {

    public MainActivity() {}

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

}

Connection.java

public class Connection extends AsyncTask<String, Void, String> {
    public String result;

    //I know, this isn't correct, how can i do?
    public MainActivity MainActivity;

    @Override
    protected String doInBackground(String... arg0) {
        // TODO Auto-generated method stub
                //...

        return "a string";
    }

    protected void onPostExecute(String result) {
        super.onPostExecute(result);
                    //...

            // Where the error is generated
            ImageView image = (ImageView) MainActivity.findViewById(R.id.image);

            //...

    }
}

推荐答案

错误在于

public MainActivity MainActivity;

从未初始化,因此指向 null.要使您的代码工作,最少的步骤是在主活动中

is never initialized, thus pointing to null. To make your code work the minimum step is in MainActivity

new Connection(this).execute();

连接中

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

    public MainActivity MainActivity;

    public Connection(MainActivity activity) {
        MainActivity = activity;
    }

但是在 onCreate 中创建一个任务并传递一个 Activity 无论如何都不是最好的主意.此外,字段名称应始终以小写字母开头.

But creating a task in onCreate and passing an Activity is not the best idea anyway. Also, field names should always start with a lowercase letter.

最好的方法是将 ImageView 传递给 AsyncTask.在 Activity 启动之前不要启动任务,并且不要忘记在 Activity 停止时取消任务.

The best way is passing an ImageView to the AsyncTask. Don't start a task until the Activity is started and also, don't forget to cancel the task when the Activity is stopped.

public final class MainActivity extends Activity {

    public MainActivity() {}

    private Connection connection;
    private ImageView imageView;

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

        imageView = (ImageView) findViewById(R.id.image);
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (connection == null || connection.getStatus() != AsyncTask.Status.RUNNING) {
            connection = new Connection(imageView);
            connection.execute();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (connection != null && connection.getStatus() == AsyncTask.Status.RUNNING) {
            connection.cancel(true);
        }
    }

}

在 Connection.java 中,将 ImageView 存储为 WeakReference 以避免泄漏.

In Connection.java, store an ImageView as a WeakReference to avoid leaks.

public final class Connection extends AsyncTask<String, Void, String> {

    private final WeakReference<ImageView> imageViewRef;

    public Connection(ImageView view) {
        imageViewRef = new WeakReference<ImageView>(view);
    }

    @Override
    protected String doInBackground(String... arg0) {
        // TODO Auto-generated method stub
                //...

        return "a string";
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
                //...

        final ImageView imageView = imageViewRef.get();
        // if the Activity is still alive, the ImageView will not be null
        if (imageView != null) {
            // set an image or whatever you need
            image.setImageResource(666);
        }

    }

这篇关于java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“android.view.View .MainActivity.findViewById(int)"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

How can create a producer using Spring Cloud Kafka Stream 3.1(如何使用Spring Cloud Kafka Stream 3.1创建制片人)
Insert a position in a linked list Java(在链接列表中插入位置Java)
Did I write this constructor properly?(我是否正确地编写了这个构造函数?)
Head value set to null but tail value still gets displayed(Head值设置为空,但仍显示Tail值)
printing nodes from a singly-linked list(打印单链接列表中的节点)
Control namespace prefixes in web services?(控制Web服务中的命名空间前缀?)