我2天前开始使用Java和AS。 我已根据说明完成了所有操作,但在模拟器中运行应用时,退出并显示错误
`java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.user.project1/com.example.user.project1.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference`
我尝试使用三个TextView创建ListView。这是代码:
package com.example.user.project1;
import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.app.ListActivity;
import android.widget.Toast;
import android.view.View;
import android.widget.SimpleAdapter;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
ListView lv = (ListView) findViewById(R.id.list);
super.onCreate(savedInstanceState);
setContentView(R.layout.rowlayout);
ArrayList<Contact> list = new ArrayList<Contact>();
list.add(new Contact("Surdialx", "Status","Available Works"));
list.add(new Contact("Surdial", "Status","Available Works"));
list.add(new Contact("Surdialx", "Status","Available Works"));
list.add(new Contact("Surdial", "Status","Available Works"));
list.add(new Contact("Surdial", "Status","Available Works"));
list.add(new Contact("Surdialxx", "Status","Available Works"));
SimpleAdapter adapter = new SimpleAdapter(this,list, R.layout.content_scrolling, new String[]{Contact.Serial,Contact.Status,Contact.WorkSt}, new int[]{R.id.tvSerial,R.id.tvStatus,R.id.tvWorkSt});
//据我所知,问题出现在这里,但我无法解决。
lv.setAdapter(adapter);
}
public class Contact extends HashMap<String, String> {
public static final String Serial = "Serial";
public static final String Status = "Status";
public static final String WorkSt = "WorkSt";
public Contact(String Ser, String Stat, String Work) {
super();
super.put(Serial, Ser);
super.put(Status, Stat);
super.put(WorkSt, Work);
}
}
}
答案 0 :(得分:2)
在将内容设置为活动之前,您正尝试findViewById
。在设置内容后,应初始化ListView
。
应该是这样的:
super.onCreate(savedInstanceState);
setContentView(R.layout.rowlayout);
ListView lv = (ListView) findViewById(R.id.list);