-2

setAdapter を試しているときに java.lang.NullPointerException が発生するのはなぜですか?

アダプターを設定しようとすると、配列リストが既にいっぱいになりました。私は何を間違えていますか?

どうも!

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 後のエラー

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

4 に答える 4

1

アクティビティが ListActivty を拡張する場合、 listView の ID は「@android:id/list」である必要があります。ListActivity の代わりに通常のアクティビティを拡張するようにアクティビティを変更するか、ListActivity ドキュメントhttps://developer.android.com/reference/android/app/ListActivity.htmlを参照してください。

于 2013-08-14T09:14:25.603 に答える
1

Call setContentView() before any of the findViewById() calls. Otherwise the View returned by findViewById() will be null and attempting to invoke a method on null causes NullPointerException.

After fixing that you'll see

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

This is because you're using ListActivity which expects to host a ListView with android:id="@android:id/list. To fix that, either change the id in your layout resources, or just change the activity to extend Activity instead of ListActivity.

于 2013-08-14T09:03:17.710 に答える
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このスタック トレースは、おそらくの関数でエラーが発生したことを意味しますonCreate

コードのこの部分を調べるか、投稿する必要があります;)

于 2013-08-14T08:57:59.060 に答える