我的应用程序不断崩溃,大概是因为空对象引用错误,但我不知道为啥

Posted

技术标签:

【中文标题】我的应用程序不断崩溃,大概是因为空对象引用错误,但我不知道为啥【英文标题】:My app keeps crashing, presumably because of null object reference error but I can't figure out why我的应用程序不断崩溃,大概是因为空对象引用错误,但我不知道为什么 【发布时间】:2018-12-23 07:13:14 【问题描述】:

我目前正在构建的应用程序有点问题。它启动得很好,但每次我让它进入关键字搜索活动时,它都会崩溃。我查看了 logcat,第 49 行的 listview.setadapter 似乎有问题,但我不知道为什么?我在这里寻找答案,但我无法让它发挥作用。如果你们能帮忙就太好了。

错误

07-15 15:47:19.273 2204-4369/com.google.android.gms E/Herrevad: [309] RemoteReportsRefreshChimeraService.a: want to send authenticated request, but no Google account on device
07-15 15:47:19.310 1180-1618/? E/Drm: Failed to find drm plugin
07-15 15:47:19.387 2204-2769/com.google.android.gms E/Volley: [150] BasicNetwork.performRequest: Unexpected response code 307 for https://android.googleapis.com/nova/herrevad/network_quality_info
07-15 15:50:44.074 4411-4411/? E/libprocessgroup: failed to make and chown /acct/uid_10058: Read-only file system
07-15 15:50:46.582 4411-4411/com.android.dreamworker.droomapp E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.android.dreamworker.droomapp, PID: 4411
    java.lang.RuntimeException: Unable to start activity ComponentInfocom.android.dreamworker.droomapp/com.android.dreamworker.droomapp.Keywordsearch: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
        at android.app.ActivityThread.access$800(ActivityThread.java:151)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5254)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
        at com.android.dreamworker.droomapp.Keywordsearch.onCreate(Keywordsearch.java:49)
        at android.app.Activity.performCreate(Activity.java:5990)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
        at android.app.ActivityThread.access$800(ActivityThread.java:151) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
        at android.os.Handler.dispatchMessage(Handler.java:102) 
        at android.os.Looper.loop(Looper.java:135) 
        at android.app.ActivityThread.main(ActivityThread.java:5254) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at java.lang.reflect.Method.invoke(Method.java:372) 
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 
07-15 15:50:48.783 1536-1589/system_process E/InputDispatcher: channel '3e3c931 com.android.dreamworker.droomapp/com.android.dreamworker.droomapp.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed!

关键字搜索.java

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.SearchView;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import java.util.ArrayList;

public class Keywordsearch extends AppCompatActivity 

ListView keywordlist;
KeywordlistAdapter adapter;
String[] title;
String[] description;
int[] icon;
ArrayList<Model> arrayList = new ArrayList<Model>();

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

    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) 
        actionBar.setTitle("Items List");
    

    title = new String[]"Battery", "Cpu", "Display", "Memory", "Sensor";
    description = new String[]"Battery detail...", "Cpu detail...", "Display detail...", "Memory detail...", "Sensor detail...";

    keywordlist = findViewById(R.id.keywordlist);

    for (int i =0; i<title.length; i++)
        Model model = new Model(title[i], description[i]);

        arrayList.add(model);
    

    adapter = new KeywordlistAdapter(this, arrayList);

    //this is were it goes wrong according to catlog
    keywordlist.setAdapter(adapter);



@Override
public boolean onCreateOptionsMenu(Menu menu) 
    getMenuInflater().inflate(R.menu.menu, menu);

    MenuItem myActionMenuItem = menu.findItem(R.id.action_search);
    SearchView searchView = (SearchView)myActionMenuItem.getActionView();
    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() 
        @Override
        public boolean onQueryTextSubmit(String s) 
            return false;
        

        @Override
        public boolean onQueryTextChange(String s) 
            if (TextUtils.isEmpty(s))
                adapter.filter("");
                keywordlist.clearTextFilter();
            
            else 
                adapter.filter(s);
            
            return true;
        
    );
    return true;


@Override
public boolean onOptionsItemSelected(MenuItem item) 
    int id = item.getItemId();

    if (id==R.id.action_settings)

        return true;
    
    return super.onOptionsItemSelected(item);

 

activity_keywordsearch.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_
android:layout_
tools:context=".Keywordsearch"
android:background="@drawable/achtergrond">

<ListView
    android:id="@+id/keywordlist"
    android:layout_
    android:layout_>
</ListView>

</RelativeLayout>

KeywordlistAdapter.java

import android.widget.BaseAdapter;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.android.dreamworker.droomapp.com.android.dreamworker.droomapp.keywordactivity.NewActivity;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;


public class KeywordlistAdapter extends BaseAdapter 


    Context mContext;
    LayoutInflater inflater;
    List<Model> modellist;
    ArrayList<Model> arrayList;


    public KeywordlistAdapter(Context context, List<Model> modellist) 
        mContext = context;
        this.modellist = modellist;
        inflater = LayoutInflater.from(mContext);
        this.arrayList = new ArrayList<Model>();
        this.arrayList.addAll(modellist);
    

    public class ViewHolder
        TextView mTitleTv, mDescTv;
    

    @Override
    public int getCount() 
        return modellist.size();
    

    @Override
    public Object getItem(int i) 
        return modellist.get(i);
    

    @Override
    public long getItemId(int i) 
        return i;
    

    @Override
    public View getView(final int postition, View view, ViewGroup parent) 
        ViewHolder holder;
        if (view==null)
            holder = new ViewHolder();
            view = inflater.inflate(R.layout.row, parent, false);


            holder.mTitleTv = view.findViewById(R.id.mainTitle);
            holder.mDescTv = view.findViewById(R.id.mainDesc);

            view.setTag(holder);

        
        else 
            holder = (ViewHolder)view.getTag();
        

        holder.mTitleTv.setText(modellist.get(postition).getTitle());
        holder.mDescTv.setText(modellist.get(postition).getDesc());



        view.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View view) 

                if (modellist.get(postition).getTitle().equals("Battery"))

                    Intent intent = new Intent(mContext, NewActivity.class);
                    mContext.startActivity(intent);
                
                if (modellist.get(postition).getTitle().equals("Cpu"))

                    Intent intent = new Intent(mContext, NewActivity.class);
                    mContext.startActivity(intent);
                
                if (modellist.get(postition).getTitle().equals("Display"))

                    Intent intent = new Intent(mContext, NewActivity.class);
                    mContext.startActivity(intent);
                
                if (modellist.get(postition).getTitle().equals("Memory"))

                    Intent intent = new Intent(mContext, NewActivity.class);
                    mContext.startActivity(intent);
                
                if (modellist.get(postition).getTitle().equals("Sensor"))

                    Intent intent = new Intent(mContext, NewActivity.class);
                    mContext.startActivity(intent);
                
            
        );


        return view;
    


    public void filter(String charText)
        charText = charText.toLowerCase(Locale.getDefault());
        modellist.clear();
        if (charText.length()==0)
            modellist.addAll(arrayList);
        
        else 
            for (Model model : arrayList)
                if (model.getTitle().toLowerCase(Locale.getDefault())
                        .contains(charText))
                    modellist.add(model);
                
            
        
        notifyDataSetChanged();
    


您可能不需要这些,但如果您在此处使用它们

Model.java

public class Model 
    String title;
    String desc;


    //constructor
    public Model(String title, String desc) 
        this.title = title;
        this.desc = desc;

    

    //getters


    public String getTitle() 
        return this.title;
    

    public String getDesc() 
        return this.desc;
    

row.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_
    android:layout_
    android:orientation="horizontal"
    android:gravity="center"
    android:padding="10dp">


    <LinearLayout
        android:layout_
        android:layout_
        android:orientation="vertical"
        android:gravity="center"
        android:layout_marginLeft="5dp"
        android:layout_marginStart="5dp">
        <TextView
            android:id="@+id/mainTitle"
            android:text="Title"
            android:textStyle="bold"
            android:textSize="20sp"
            android:layout_
            android:layout_ />
        <TextView
            android:id="@+id/mainDesc"
            android:text="Description"
            android:textSize="20sp"
            android:layout_
            android:layout_ />
    </LinearLayout>

</RelativeLayout>

再次,如果你们中的任何人可以帮助我,那将是 太棒了! 谢谢!

【问题讨论】:

setContentView(R.layout.activity_main);。您设置了错误的布局,这反过来使 findViewById(R.id.keywordlist) 返回 null (因为您设置了另一个不包含此视图的布局)。试试setContentView(R.layout.activity_keywordsearch); 【参考方案1】:

这将返回 null,因此 keywordlistnull 导致 NPE:

keywordlist = findViewById(R.id.keywordlist);

显然R.id.keywordlist在当前布局中不存在。

原因是在Keywordsearch.onCreate() 你这样做:

setContentView(R.layout.activity_main);

当您可能想要这样做时:

setContentView(R.layout.activity_keywordsearch);

【讨论】:

以上是关于我的应用程序不断崩溃,大概是因为空对象引用错误,但我不知道为啥的主要内容,如果未能解决你的问题,请参考以下文章

由于尝试在空对象引用上调用虚拟方法“ ”,应用程序崩溃

可滑动视图空异常错误 - Android Studio [重复]

字符串空对象引用[重复]

在使用 Recycler View 时尝试在空对象引用上调用虚拟方法

YouTube 播放器崩溃(java.lang.NullPointerException,空对象引用)

尝试在空对象引用上调用虚方法 - 如何正确更改TextView的值