2 u010811339 u010811339 于 2016.04.23 16:57 提问

求大神指导Android中重写SimpleAdapter类引getCount空指针异常,万分感谢

重写的BaseAdapter:

public class MyAdapter extends BaseAdapter {
    List<UserInfo> userInfos=new ArrayList<UserInfo>();
    Context context;

    public MyAdapter(Context c,List<UserInfo> userInfos) {
        // TODO Auto-generated constructor stub
        this.context=c;
        this.userInfos=userInfos;
    }

    public void setcotext(List<UserInfo> userInfos){
        this.userInfos=userInfos;
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return userInfos.size();
    }

    @Override
    public Object getItem(int arg0) {
        // TODO Auto-generated method stub
        return userInfos.get(arg0);
    }

    @Override
    public long getItemId(int arg0) {
        // TODO Auto-generated method stub
        return userInfos.get(arg0).getId();
    }

    @Override
    public View getView(int arg0, View arg1, ViewGroup arg2) {
        // TODO Auto-generated method stub
        if(arg1==null){
            arg1=LayoutInflater.from(context).inflate(R.layout.book_item, null);
        }
        TextView _context=(TextView) arg1.findViewById(R.id.content);
        TextView _datetime=(TextView) arg1.findViewById(R.id.datetime);

        UserInfo u=userInfos.get(arg0);

        _context.setText(u.getContent());
        _datetime.setText(u.getDatetime());
        return arg1;
    }

}

Activity的:

 public class MainActivity extends Activity implements OnClickListener{
    Button add;
    Button re;
    SQLiteDatabase db;
    ListView listView;
    MyAdapter adapter;
    List<UserInfo> liUse;
    protected void onRestart() {
        // TODO Auto-generated method stub
        super.onRestart();
        shuaxin();
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        DbInit();
        add=(Button) findViewById(R.id.add);
        listView=(ListView) findViewById(R.id.lv);
        registerForContextMenu(listView);
        adapter=new MyAdapter(this , liUse);
        listView.setAdapter(adapter);
    }

    public List<UserInfo> selectAll(){
        List<UserInfo> ls=new ArrayList<UserInfo>();

        Cursor cur=db.rawQuery(" select * from user ", null);
        while (cur.moveToNext()) {
            UserInfo u = new UserInfo();
            u.setId(cur.getInt(cur.getColumnIndex("_id")));
            u.setContent(cur.getString(cur.getColumnIndex("content")));
            u.setDatetime(cur.getString(cur.getColumnIndex("datetime")));
            ls.add(u);
        }

        return liUse;

    }

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


    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub
        switch (arg0.getId()) {
        case R.id.refresh:
            shuaxin();
            break;

        case R.id.add:
            Intent intent=new Intent(this,AddConActivity.class);
            startActivity(intent);
            break;

        default:
            break;
        }

    }
    public void DbInit(){
        DBHelper dbHelper=new DBHelper(this, "Cotext.db", null, 1);
        db=dbHelper.getWritableDatabase();

    }
    class DBHelper extends SQLiteOpenHelper{

        public DBHelper(Context context, String name, CursorFactory factory,
                int version) {
            super(context, name, factory, version);
            // TODO Auto-generated constructor stub
        }

        @Override
        public void onCreate(SQLiteDatabase arg0) {
            // TODO Auto-generated method stub
            SimpleDateFormat    formatter    =   new    SimpleDateFormat    ("yyyy年MM月dd日    HH:mm:ss     ");       
            Date    curDate    =   new    Date(System.currentTimeMillis());//获取当前时间       
            String    str    =    formatter.format(curDate);       
            arg0.execSQL("create table user ( _id integer primary key  autoincrement , datetime text not null , content varchar(100))");
            ContentValues cv=new ContentValues();
            cv.put("datetime", str);
            cv.put("content", "测试");
            arg0.insert("user", "datetime", cv);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            // TODO Auto-generated method stub

        }

    }
    private void shuaxin() {
        liUse=selectAll();
        adapter.setcotext(liUse);
        adapter.notifyDataSetInvalidated();
    }
}

get 和 set :

 public class UserInfo implements Serializable{
    private int id;
    private String datetime;
    private String content;

    public UserInfo() {
        // TODO Auto-generated constructor stub
    }

    public UserInfo(int id,String datetime,String content) {
        // TODO Auto-generated constructor stub
        this.setId(id);
        this.setContent(content);
        this.setDatetime(datetime);

    }

    public UserInfo(String datetime,String content) {
        // TODO Auto-generated constructor stub
        this.setContent(content);
        this.setDatetime(datetime);
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getDatetime() {
        return datetime;
    }

    public void setDatetime(String datetime) {
        this.datetime = datetime;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }


}

异常

04-23 16:48:45.585: E/AndroidRuntime(1823): FATAL EXCEPTION: main
04-23 16:48:45.585: E/AndroidRuntime(1823): Process: com.example.notepad, PID: 1823
04-23 16:48:45.585: E/AndroidRuntime(1823): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.notepad/com.example.notepad.MainActivity}: java.lang.NullPointerException
04-23 16:48:45.585: E/AndroidRuntime(1823): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2219)
04-23 16:48:45.585: E/AndroidRuntime(1823): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2269)
04-23 16:48:45.585: E/AndroidRuntime(1823): at android.app.ActivityThread.access$800(ActivityThread.java:135)
04-23 16:48:45.585: E/AndroidRuntime(1823): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
04-23 16:48:45.585: E/AndroidRuntime(1823): at android.os.Handler.dispatchMessage(Handler.java:102)
04-23 16:48:45.585: E/AndroidRuntime(1823): at android.os.Looper.loop(Looper.java:136)
04-23 16:48:45.585: E/AndroidRuntime(1823): at android.app.ActivityThread.main(ActivityThread.java:5045)
04-23 16:48:45.585: E/AndroidRuntime(1823): at java.lang.reflect.Method.invokeNative(Native Method)
04-23 16:48:45.585: E/AndroidRuntime(1823): at java.lang.reflect.Method.invoke(Method.java:515)
04-23 16:48:45.585: E/AndroidRuntime(1823): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-23 16:48:45.585: E/AndroidRuntime(1823): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-23 16:48:45.585: E/AndroidRuntime(1823): at dalvik.system.NativeStart.main(Native Method)
04-23 16:48:45.585: E/AndroidRuntime(1823): Caused by: java.lang.NullPointerException
04-23 16:48:45.585: E/AndroidRuntime(1823): at com.example.notepad.MyAdapter.getCount(MyAdapter.java:29)
04-23 16:48:45.585: E/AndroidRuntime(1823): at android.widget.ListView.setAdapter(ListView.java:480)
04-23 16:48:45.585: E/AndroidRuntime(1823): at com.example.notepad.MainActivity.onCreate(MainActivity.java:44)
04-23 16:48:45.585: E/AndroidRuntime(1823): at android.app.Activity.performCreate(Activity.java:5231)
04-23 16:48:45.585: E/AndroidRuntime(1823): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
04-23 16:48:45.585: E/AndroidRuntime(1823): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2163)
04-23 16:48:45.585: E/AndroidRuntime(1823): ... 11 more


4个回答

q610098308
q610098308   2016.04.23 17:29
已采纳

04-23 16:48:45.585: E/AndroidRuntime(1823): at android.widget.ListView.setAdapter(ListView.java:480)
List liUse; liUse没有初始化,是空指针吧,所以后面 adapter 中getCount 是崩溃了。
开始直接初始化就不会崩溃了,
List liUse = new ArrayList<>();

u010811339
u010811339 谢谢,谢谢,谢谢
一年多之前 回复
u010811339
u010811339 是在Activity中初始化还是在Activity中初始化?
一年多之前 回复
q610098308
q610098308   2016.04.23 17:48

声名时,直接初始化就可以,当然是在MainActivity 中;

u010811339
u010811339 谢谢,谢谢,谢谢
一年多之前 回复
q610098308
q610098308   2016.04.23 17:58

public class MainActivity extends Activity implements OnClickListener{
Button add;
Button re;
SQLiteDatabase db;
ListView listView;
MyAdapter adapter;
List liUse;

    最后一句改成 
     List<UserInfo> liUse = new ArrayList<UserInfo>(); 就可以了。 
u010811339
u010811339 是的是的,谢谢,谢谢,谢谢
一年多之前 回复
baidu_23086307
baidu_23086307   2016.04.24 00:32

E/AndroidRuntime(1823): at android.widget.ListView.setAdapter(ListView.java:480)
List liUse; liUse没有初始化,是空指针吧,所以后面 adapter 中getCount 是崩溃了。
开始直接初始化就不会崩溃了,
List liUse = new ArrayList<>();

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!