Implementing search bar and getting 'java.lang.Object[] java.util.Collection.toArray()' on a null object reference error

huangapple go评论101阅读模式
英文:

Implementing search bar and getting 'java.lang.Object[] java.util.Collection.toArray()' on a null object reference error

问题

以下是翻译好的部分:

我是 Android Studio 的新手,我一直在尝试在我的应用程序中实现一个搜索栏,但遇到了一个构建错误。它安装得很好,但当我尝试在手机上打开应用程序时,显示“应用程序已停止”。

Logcat(错误):

E/AndroidRuntime: 致命异常: 主线程
Process: com.example.sliteproj, PID: 1445
java.lang.RuntimeException: 无法启动活动 ComponentInfo{com.example.sliteproj/com.example.sliteproj.MainActivity}: java.lang.NullPointerException: 尝试调用接口方法 'java.lang.Object[] java.util.Collection.toArray()' 时空对象引用
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2957)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032)
    at android.app.ActivityThread.-wrap11(Unknown Source:0)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696)
    at android.os.Handler.dispatchMessage(Handler.java:105)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6944)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
 原因: java.lang.NullPointerException: 尝试调用接口方法 'java.lang.Object[] java.util.Collection.toArray()' 时空对象引用
    at java.util.ArrayList.<init>(ArrayList.java:191)
    at com.example.sliteproj.Adapter.<init>(Adapter.java:34)
    at com.example.sliteproj.MainActivity.showRecord(MainActivity.java:57)
    at com.example.sliteproj.MainActivity.onCreate(MainActivity.java:41)
    at android.app.Activity.performCreate(Activity.java:7183)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1220)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2910)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032) 
    at android.app.ActivityThread.-wrap11(Unknown Source:0) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696) 
    at android.os.Handler.dispatchMessage(Handler.java:105) 
    at android.os.Looper.loop(Looper.java:164) 
    at android.app.ActivityThread.main(ActivityThread.java:6944) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374) 

我理解这是一个经常被问到的问题,我已经查看了其他答案和解决方案。我已经尝试初始化列表,但仍然无法修复这个错误。我认为我在确切需要初始化的地方遇到了困难。

我的代码(Adapter.java):

public class Adapter extends RecyclerView.Adapter<Adapter.Holder> implements 
Filterable {
private Context context;
private ArrayList<Model> arrayList;
private ArrayList<Model> exampleArrayList;

DatabaseHelper databaseHelper;

public Adapter(Context context, ArrayList<Model> arrayList) {
    this.context = context;
    this.arrayList = arrayList;
    exampleArrayList = new ArrayList<>(exampleArrayList);

    databaseHelper = new DatabaseHelper(context);
}

@Override
public Filter getFilter() {
    return exampleFilter;
}

private Filter exampleFilter = new Filter() {
    @Override
    protected FilterResults performFiltering(CharSequence constraint) {
        List<Model> filteredList = new ArrayList<>();

        if (constraint == null || constraint.length() == 0) {
            filteredList.addAll(exampleArrayList);
        } else {
            String filterPattern = constraint.toString().toLowerCase().trim();

            for (Model item: exampleArrayList) {
                if (item.getName().toLowerCase().contains(filterPattern)) {
                    filteredList.add(item);
                }
            }
        }

        FilterResults results = new FilterResults();
        results.values = filteredList;

        return results;
    }

    @Override
    protected void publishResults(CharSequence constraint, FilterResults results) {
        arrayList.clear();
        arrayList.addAll((List) results.values);
        notifyDataSetChanged();
    }
};
}
英文:

I am new to android studio and I have been trying to implement a search bar onto my app and I've come across a building error. It install's fine but when I try to open the app on my phone shows "application has stopped".

Logcat (Errors):

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.sliteproj, PID: 1445
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.sliteproj/com.example.sliteproj.MainActivity}: java.lang.NullPointerException: Attempt to invoke interface method &#39;java.lang.Object[] java.util.Collection.toArray()&#39; on a null object reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2957)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032)
    at android.app.ActivityThread.-wrap11(Unknown Source:0)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696)
    at android.os.Handler.dispatchMessage(Handler.java:105)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6944)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
 Caused by: java.lang.NullPointerException: Attempt to invoke interface method &#39;java.lang.Object[] java.util.Collection.toArray()&#39; on a null object reference
    at java.util.ArrayList.&lt;init&gt;(ArrayList.java:191)
    at com.example.sliteproj.Adapter.&lt;init&gt;(Adapter.java:34)
    at com.example.sliteproj.MainActivity.showRecord(MainActivity.java:57)
    at com.example.sliteproj.MainActivity.onCreate(MainActivity.java:41)
    at android.app.Activity.performCreate(Activity.java:7183)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1220)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2910)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032)&#160;
    at android.app.ActivityThread.-wrap11(Unknown Source:0)&#160;
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696)&#160;
    at android.os.Handler.dispatchMessage(Handler.java:105)&#160;
    at android.os.Looper.loop(Looper.java:164)&#160;
    at android.app.ActivityThread.main(ActivityThread.java:6944)&#160;
    at java.lang.reflect.Method.invoke(Native Method)&#160;
    at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)&#160;
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)&#160;

I understand that this is a frequently asked question, and have looked through the other answers and solutions. I have tried initializing the List but still, am unable to fix the error.I think I am having trouble understanding where the initialization is exactly needed.

My code (Adapter.java):

public class Adapter extends RecyclerView.Adapter&lt;Adapter.Holder&gt; implements 
Filterable {
private Context context;
private ArrayList&lt;Model&gt; arrayList;
private ArrayList&lt;Model&gt; exampleArrayList;

DatabaseHelper databaseHelper;

public Adapter(Context context, ArrayList&lt;Model&gt; arrayList) {
    this.context = context;
    this.arrayList = arrayList;
    exampleArrayList = new ArrayList&lt;&gt;(exampleArrayList);

    databaseHelper = new DatabaseHelper(context);
}

@Override
public Filter getFilter() {
    return exampleFilter;
}

private Filter exampleFilter = new Filter() {
    @Override
    protected FilterResults performFiltering(CharSequence constraint) {
        List&lt;Model&gt; filteredList = new ArrayList&lt;&gt;();

        if (constraint == null || constraint.length() == 0) {
            filteredList.addAll(exampleArrayList);
        } else {
            String filterPattern = constraint.toString().toLowerCase().trim();

            for (Model item: exampleArrayList) {
                if (item.getName().toLowerCase().contains(filterPattern)) {
                    filteredList.add(item);
                }
            }
        }

        FilterResults results = new FilterResults();
        results.values = filteredList;

        return results;
    }

    @Override
    protected void publishResults(CharSequence constraint, FilterResults results) {
        arrayList.clear();
        arrayList.addAll((List) results.values);
        notifyDataSetChanged();
    }
};
}

答案1

得分: 1

以下是翻译好的部分:

Caused by: java.lang.NullPointerException: Attempt to invoke interface method &#39;java.lang.Object[] java.util.Collection.toArray()&#39; on a null object reference

第一行声明了一个名为exampleArrayList的变量,但实际上它还没有包含原始值。相反,它包含一个指针(因为类型是ArrayList&lt;Model&gt;,这是一个引用类型)。由于您尚未指定要指向什么,Java将其设置为null,这意味着“我指向的是空”。

public Adapter(Context context, ArrayList&lt;Model&gt; arrayList) {
    this.context = context;
    this.arrayList = arrayList;
    // 此行将数组列表从null对象分配给了它,因此导致了NullPointerException
    exampleArrayList = new ArrayList&lt;&gt;(exampleArrayList);

    databaseHelper = new DatabaseHelper(context);
}

Solution

exampleArrayList = new ArrayList&lt;&gt;(exampleArrayList); 替换为 exampleArrayList = new ArrayList&lt;&gt;() 或者如果你想要分配来自构造函数的数组,那么使用 exampleArrayList = new ArrayList&lt;&gt;(arrayList);exampleArrayList = arrayList

Edit 2

private void showRecord() {

    adapter = new Adapter(MainActivity.this,
            databaseHelper.getAllData(Constants.C_TAG + &quot; DESC&quot;));

    mRecyclerView.setAdapter(adapter);
}

第二个异常是因为您在全局声明了adapter对象,但是在showRecord方法中局部地创建了adapter对象,因此全局adapter对象为空,您正在访问全局对象,所以会出现异常。

英文:

Caused by: java.lang.NullPointerException: Attempt to invoke interface method &#39;java.lang.Object[] java.util.Collection.toArray()&#39; on a null object reference

The first line declares a variable named exampleArrayList, but it does not actually contain a primitive value yet. Instead, it contains a pointer (because the type is ArrayList&lt;Model&gt; which is a reference type). Since you have not yet said what to point to, Java sets it to null, which means "I am pointing to nothing".

public Adapter(Context context, ArrayList&lt;Model&gt; arrayList) {
    this.context = context;
    this.arrayList = arrayList;
    //this line you are assing array list from null object thats why you are getting **NullPointerException**
    exampleArrayList = new ArrayList&lt;&gt;(exampleArrayList);

    databaseHelper = new DatabaseHelper(context);
}

Solution

replace exampleArrayList = new ArrayList&lt;&gt;(exampleArrayList); with exampleArrayList = new ArrayList&lt;&gt;() or if you want to assign array which is comming from constructor then exampleArrayList = new ArrayList&lt;&gt;(arrayList); or exampleArrayList = arrayList

Edit 2

private void showRecord() {

    adapter = new Adapter(MainActivity.this,
            databaseHelper.getAllData(Constants.C_TAG + &quot; DESC&quot;));

    mRecyclerView.setAdapter(adapter);
}

Second exception bcz of you are declared adapter object globally but you are creating adapter object in showRecord method locally thats why globall adapter object is null and you are accessing global object and you are getting exception

答案2

得分: 0

我在实时数据库中遇到了相同的问题,因为某些字段为空。当我清除了那些具有空值的字段时,错误得以解决。
有时候错误并不一定出现在代码中,可能与你的数据有关。

附言:这是其中一个解决方案。(适用于我的情况)

英文:

I faced the same problem because some fields were null in my real-time database. As soon as I cleared the fields with null values, the error got solved.
Sometimes errors may not be in the code. It can be related to your data.

P.S - This is one of the solutions. (For my case)

huangapple
  • 本文由 发表于 2020年4月8日 16:13:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/61096204.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定