首页 > 解决方案 > NullPointerException:尝试调用虚拟方法 'void android.widget.ListView.setAdapter 无法修复

问题描述

我自定义 ListView Layouts(my_list_item,xml) 来显示我的数据。它不起作用。在我展示 acyivity_main.xml 之前,仍然可以工作。我已经为列表视图创建了一个适配器。

我是安卓工作室的新人。也许是简单的问题。试了很久还是不能修。谢谢

错误

2020-03-21 00:13:18.227 20079-20079/au.edu.utas.sqlite E/AndroidRuntime: FATAL EXCEPTION: main
    Process: au.edu.utas.sqlite, PID: 20079
    java.lang.RuntimeException: Unable to start activity ComponentInfo{au.edu.utas.sqlite/au.edu.utas.sqlite.MainActivity}: 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:2665)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
        at android.app.ActivityThread.-wrap12(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6119)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
        at au.edu.utas.sqlite.MainActivity.onCreate(MainActivity.java:57)
        at android.app.Activity.performCreate(Activity.java:6679)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726) 
        at android.app.ActivityThread.-wrap12(ActivityThread.java) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477) 
        at android.os.Handler.dispatchMessage(Handler.java:102) 
        at android.os.Looper.loop(Looper.java:154) 
        at android.app.ActivityThread.main(ActivityThread.java:6119) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 

MainActivity.java

public class MainActivity extends AppCompatActivity
{
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_list_item);




        //Open the database, so that we can read and write
        Database databaseConnection = new Database(this);
        final SQLiteDatabase db = databaseConnection.open();


        Property property1 = new Property();
        property1.setAddress("742 Evergreen Terrace");
        property1.setBedrooms(4); property1.setPrice(250000);

        Property property2 = new Property();
        property2.setAddress("4352 Wisteria Lane"); property2.setBedrooms(5);
        property2.setPrice(500000);

        PropertyTable.insert(db, property1);
        PropertyTable.insert(db, property2);

        final ArrayList<Property> properties = PropertyTable.selectAll(db);


//        for(Property element: properties){
//            System.out.println(element);
//        }
//
//        Log.d("TAG", "The debugging message.");


        //List parts!

        ListView myList = findViewById(R.id.myList);

        final PropertyAdapter propertyListAdapter = new PropertyAdapter(getApplicationContext(),  R.layout.my_list_item  , properties);
        myList.setAdapter(propertyListAdapter);



        myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

            }
        });


    }
}

属性.java

public class Property {

    private int mPropertyID;
    private String mAddress;
    private int mPrice, mBedrooms;


    public int getPropertyID() { return mPropertyID; }
    public void setPropertyID(int s) { this.mPropertyID = s; }

    public String getAddress() { return mAddress; }
    public void setAddress(String add) { this.mAddress = add; }

    public int getPrice() {return mPrice; }
    public void setPrice(int pri) {this.mPrice = pri; }

    public int getBedrooms() { return mBedrooms; }
    public void setBedrooms(int bed) { this.mBedrooms = bed; }


}

属性表.java

public class PropertyTable<c> {
    public static final String TABLE_NAME = "property";
    public static final String KEY_PROPERTY_ID = "property_id";
    public static final String KEY_ADDRESS = "address";
    public static final String KEY_PRICE = "price";
    public static final String KEY_BEDROOMS = "bedrooms";


    public static final String CREATE_STATEMENT = "CREATE TABLE " + TABLE_NAME
            + " (" + KEY_PROPERTY_ID + " integer primary key autoincrement, "
            + KEY_ADDRESS + " string not null, "
            + KEY_PRICE + " int not null, "
            + KEY_BEDROOMS + " string not null " +");";


    public static Property createFromCursor(Cursor c) {
        if (c == null || c.isAfterLast() || c.isBeforeFirst()) {
            return null; }
        else {
            Property p = new Property();
            p.setPropertyID(c.getInt(c.getColumnIndex(KEY_PROPERTY_ID)));
            p.setAddress(c.getString(c.getColumnIndex(KEY_ADDRESS)));
            p.setPrice(c.getInt(c.getColumnIndex(KEY_PRICE)));
            p.setBedrooms(c.getInt(c.getColumnIndex(KEY_BEDROOMS)));
            return p;
        } }


    public static void insert(SQLiteDatabase db, Property p) {
        ContentValues values = new ContentValues();
        values.put(KEY_ADDRESS, p.getAddress());
        values.put(KEY_PRICE, p.getPrice());
        values.put(KEY_BEDROOMS, p.getBedrooms());
        db.insert(TABLE_NAME, null, values); }







    public static ArrayList<Property> selectAll(SQLiteDatabase db) {
        ArrayList<Property> results = new ArrayList<Property>();

        Cursor c = db.query(TABLE_NAME, null, null, null, null, null, null);
        if (c != null) {
            c.moveToFirst();
            while (!c.isAfterLast()) {
                Property p = createFromCursor(c);
                results.add(p);
                c.moveToNext();
            }
        }


        return results;
    }

属性适配器.java

public class PropertyAdapter extends ArrayAdapter<Property> {

    private int mLayoutResourceID;
    public PropertyAdapter(Context context, int resource, List<Property> objects)
    {
        super(context, resource, objects);
        this.mLayoutResourceID = resource;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {


        LayoutInflater layoutInflater = (LayoutInflater) getContext().getSystemService(Service.LAYOUT_INFLATER_SERVICE) ;
        View row = layoutInflater.inflate(mLayoutResourceID, parent, false);
        Property p = this.getItem(position);

//        TextView textView = row.findViewById(android.R.id.text1);
//       textView.setText(p.getPropertyID()+": "+p.getAddress());

        TextView lblAddress = row.findViewById(R.id.lblAddress);
        lblAddress.setText(p.getAddress());

        TextView lblBedrooms = row.findViewById(R.id.lblBedrooms);
        lblBedrooms.setText(""+p.getBedrooms());

        TextView lblPrice = row.findViewById(R.id.lblPrice);
        lblPrice.setText("$"+p.getPrice());

        return row;
    }
}

my_list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/lblAddress"
            android:layout_width="80dp"
            android:layout_height="40dp"
            android:text="lbTitle" />


        <TextView
            android:id="@+id/lblPrice"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:gravity="right"
            android:text="lbPrice" />

    </LinearLayout>

    <TextView
        android:id="@+id/lblBedrooms"
        android:layout_width="250dp"
        android:layout_height="40dp"
        android:gravity="right"
        android:text="lbBedrooms" />


</LinearLayout>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    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="au.edu.utas.sqlite.MainActivity">

    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/myList" />

</androidx.constraintlayout.widget.ConstraintLayout>

标签: javaandroid

解决方案


setContentView(R.layout.my_list_item);错了。

将其更改为:

setContentView(R.layout.activity_main);

谢谢你。


推荐阅读