ListView.setAdapter - java.lang.NullPointerException

时间:2013-08-14 08:46:02

标签: java android arraylist baseadapter

有人可以解释一下,为什么我在尝试setAdapter时会遇到java.lang.NullPointerException?

当我尝试设置适配器时,我的arraylist已经填满了。我做错了什么?

THX!

activity_view_list.xml

<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical">
    <ListView
            android:id="@+id/lvView"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="1">
    </ListView>
</LinearLayout>

item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
    <ImageView
            android:id="@+id/ivImage"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_launcher">
    </ImageView>
    <LinearLayout
            android:id="@+id/linearLayout1"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_marginLeft="5dp"
            android:layout_weight="1"
            android:orientation="vertical">
        <TextView
                android:id="@+id/tvDescr"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="5dp"
                android:text=""
                android:textSize="20sp">
        </TextView>
    </LinearLayout>

</LinearLayout>

我的产品类

package com.shvedchenko.skleroshop;

/**
 * Created by dima on 14.08.13.
 */

public class Product {

    String name;
    int image;


    Product(String _describe, int _image) {
        name = _describe;
        image = _image;
    }

}

和我的BoxAdapter

package com.shvedchenko.skleroshop;

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

import java.util.ArrayList;

/**
 * Created by dima on 14.08.13.
 */
public class BoxAdapter extends BaseAdapter {
    Context ctx;
    LayoutInflater lInflater;
    ArrayList<Product> objects;

    BoxAdapter(Context context, ArrayList<Product> products) {
        ctx = context;
        objects = products;
        lInflater = (LayoutInflater) ctx
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    // кол-во элементов
    @Override
    public int getCount() {
        return objects.size();
    }

    // элемент по позиции
    @Override
    public Object getItem(int position) {
        return objects.get(position);
    }

    // id по позиции
    @Override
    public long getItemId(int position) {
        return position;
    }

    // пункт списка
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // используем созданные, но не используемые view
        View view = convertView;
        if (view == null) {
            view = lInflater.inflate(R.layout.item, parent, false);
        }

        Product p = getProduct(position);

        // заполняем View в пункте списка данными из товаров: наименование, цена
        // и картинка
        ((TextView) view.findViewById(R.id.tvDescr)).setText(p.name);
        ((ImageView) view.findViewById(R.id.ivImage)).setImageResource(p.image);
        return view;
    }

    // товар по позиции
    Product getProduct(int position) {
        return ((Product) getItem(position));
    }
}

错误

08-14 08:38:29.684      511-511/com.shvedchenko.skleroshop W/dalvikvm: threadid=3: thread exiting with uncaught exception (group=0x4001b188)
08-14 08:38:29.684      511-511/com.shvedchenko.skleroshop E/AndroidRuntime: Uncaught handler: thread main exiting due to uncaught exception
08-14 08:38:29.694      511-511/com.shvedchenko.skleroshop E/AndroidRuntime: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.shvedchenko.skleroshop/com.shvedchenko.skleroshop.ViewList}: java.lang.NullPointerException
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2496)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
        at android.app.ActivityThread.access$2200(ActivityThread.java:119)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:123)
        at android.app.ActivityThread.main(ActivityThread.java:4363)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:521)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
        at dalvik.system.NativeStart.main(Native Method)
        Caused by: java.lang.NullPointerException
        at com.shvedchenko.skleroshop.ViewList.onCreate(ViewList.java:37)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2459)

ViewList.java

package com.shvedchenko.skleroshop;

import android.app.ListActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.widget.ListView;

import java.util.ArrayList;


public class ViewList extends ListActivity {

    ArrayList<Product> products = new ArrayList<Product>();
    BoxAdapter boxAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        /*setContentView(R.layout.activity_view_list);*/
        // создаем адаптер
        fillData();
        boxAdapter = new BoxAdapter(this, products);

        // настраиваем список
        ListView lvMain = (ListView) findViewById(R.id.lvView);
        lvMain.setAdapter(boxAdapter);

    }


    // генерируем данные для адаптера
    void fillData() {
        for (int i = 1; i <= 20; i++) {
            products.add(new Product("Product " + i, R.drawable.ic_launcher));
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {

            /*startActivity(intent);
            ViewList.this.finish();
            return false;*/
        }

        return super.onKeyDown(keyCode, event);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.list, menu);
        return true;
    }

}
在setContentView

之后

ERORS

08-14 09:07:53.916        52-56/system_process I/ActivityManager: Starting activity: Intent { cmp=com.shvedchenko.skleroshop/.ViewList (has extras) }
08-14 09:07:53.956      230-230/com.shvedchenko.skleroshop D/AndroidRuntime: Shutting down VM
08-14 09:07:53.956      230-230/com.shvedchenko.skleroshop W/dalvikvm: threadid=3: thread exiting with uncaught exception (group=0x4001b188)
08-14 09:07:53.956      230-230/com.shvedchenko.skleroshop E/AndroidRuntime: Uncaught handler: thread main exiting due to uncaught exception
08-14 09:07:53.966      230-230/com.shvedchenko.skleroshop E/AndroidRuntime: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.shvedchenko.skleroshop/com.shvedchenko.skleroshop.ViewList}: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2496)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
        at android.app.ActivityThread.access$2200(ActivityThread.java:119)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:123)
        at android.app.ActivityThread.main(ActivityThread.java:4363)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:521)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
        at dalvik.system.NativeStart.main(Native Method)
        Caused by: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
        at android.app.ListActivity.onContentChanged(ListActivity.java:236)
        at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:201)
        at android.app.Activity.setContentView(Activity.java:1622)
        at com.shvedchenko.skleroshop.ViewList.onCreate(ViewList.java:21)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2459)

4 个答案:

答案 0 :(得分:7)

我想你只是忘了夸大你的布局。

setContentView(R.layout.activity_view_list);

这行不应该被评论为每次调用findViewById都不会有效,因为它没有任何View膨胀。

答案 1 :(得分:1)

在任意setContentView()来电之前致电findViewById()。否则,View返回的findViewById()将为null,并且尝试在null上调用方法会导致NullPointerException

修好后你会看到

java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'

这是因为您使用的ListActivity希望托管ListView android:id="@android:id/list。要解决此问题,请更改布局资源中的id,或者只更改活动以扩展Activity而不是ListActivity

答案 2 :(得分:1)

如果您的活动扩展了ListActivty,则listView的id必须为“@android:id / list”。 您可以更改您的活动以扩展正常活动而不是ListActivity,或者查看ListActivity文档https://developer.android.com/reference/android/app/ListActivity.html

答案 3 :(得分:0)

08-14 08:38:29.694      511-511/com.shvedchenko.skleroshop E/AndroidRuntime: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.shvedchenko.skleroshop/com.shvedchenko.skleroshop.ViewList}: java.lang.NullPointerException

此堆栈跟踪可能意味着Activity的{​​{1}}函数发生错误。

您应该查看代码的这一部分,或发布它;)