我的应用不断崩溃,大概是由于空对象引用错误,但我不知道为什么

时间:2018-07-15 15:57:33

标签: android listview android-activity nullpointerexception

我当前正在构建的应用程序存在一些问题。它可以正常启动,但是每次我进入keywordsearch活动时,它都会崩溃。我查看了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 ComponentInfo{com.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!

Keywordsearch.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_width="match_parent"
android:layout_height="match_parent"
tools:context=".Keywordsearch"
android:background="@drawable/achtergrond">

<ListView
    android:id="@+id/keywordlist"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</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_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:gravity="center"
    android:padding="10dp">


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        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_width="match_parent"
            android:layout_height="wrap_content" />
        <TextView
            android:id="@+id/mainDesc"
            android:text="Description"
            android:textSize="20sp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>

</RelativeLayout>

同样,如果有人能帮助我,那将是太棒了! 谢谢!

1 个答案:

答案 0 :(得分:-1)

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

keywordlist = findViewById(R.id.keywordlist);

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

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

setContentView(R.layout.activity_main);

当您可能想要这样做时:

setContentView(R.layout.activity_keywordsearch);