ListView.setAdapter - java.lang.NullPointerException
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18227027/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ListView.setAdapter - java.lang.NullPointerException
提问by kbu
Could anybody explain me, why i have java.lang.NullPointerException when i am trying setAdapter?
谁能解释一下,为什么我在尝试 setAdapter 时会出现 java.lang.NullPointerException?
When i trying set Adapter, my arraylist already filled. What i making wrong?
当我尝试设置适配器时,我的数组列表已经填满了。我做错了什么?
Thx!
谢谢!
activity_view_list.xml
活动视图列表.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
<?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>
My class for products
我的产品类
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;
}
}
And my BoxAdapter
还有我的 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));
}
}
ERRORS
错误
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.access00(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
视图列表.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;
}
}
ERORS after setContentView
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.access00(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)
采纳答案by yugy
If your activity extends ListActivty, your listView 's id must be "@android:id/list". You can change your activty to extends the normal Activity instead of ListActivity,or see the ListActivity document https://developer.android.com/reference/android/app/ListActivity.html
如果您的活动扩展了 ListActivty,则您的 listView 的 id 必须是“@android:id/list”。您可以更改您的活动以扩展普通活动而不是 ListActivity,或查看 ListActivity 文档https://developer.android.com/reference/android/app/ListActivity.html
回答by Goo
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
This stack trace probably means that an error occurs in your Activity
's onCreate
function.
此堆栈跟踪可能意味着您Activity
的onCreate
函数中发生错误。
You should look into this part of your code, or post it ;)
您应该查看代码的这一部分,或将其发布 ;)
回答by laalto
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
.
setContentView()
在任何调用之前findViewById()
调用。否则View
返回的findViewById()
将是null
并尝试调用null
原因上的方法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
.
这是因为你使用ListActivity
它预计将举办一个ListView
有android:id="@android:id/list
。要解决此问题,请更改id
布局资源中的 ,或者只是将活动更改为扩展Activity
而不是ListActivity
.
回答by HpTerm
I think you simply forget to inflate your layout.
我认为您只是忘记夸大您的布局。
setContentView(R.layout.activity_view_list);
this line should not be commented orelse every call to findViewById will not work as it does not have any View inflated.
这行不应该被注释,否则每次调用 findViewById 都将不起作用,因为它没有任何视图膨胀。