从SQLite检索数据并在listview中显示时出现空指针异常

时间:2013-09-09 10:04:26

标签: java android android-sqlite

我正在尝试在列表视图中显示数据库的内容。在运行代码时,我得到NullPointerException,我的应用程序崩溃了。请参阅以下代码:

helper.java:

public String[] personslist() {
        // TODO Auto-generated method stub
        SQLiteDatabase myDB;
        int i=0;
         String[] values = {};
        try {
                  myDB=this.openDataBase();                   
              Cursor c=myDataBase.rawQuery("select PersonName from Persons;",null);
               if (c != null ) {
                     if  (c.moveToFirst()) {
                     do {

                         // put your code to get data from cursor                      



                        for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
                               values[i] = c.getString(c.getColumnIndex("PersonName"));
                               i++;
                            }
                        }while (c.moveToNext());
                     }
                  }
                  if(c != null)
                  {
                     myDB.close();
                     c.close();
                  }                    
                  }catch(SQLException sqle){

                  throw sqle;
                  }
         return values;
         }

方法openDatabase():

 public SQLiteDatabase openDataBase() throws SQLException{

    String myPath = DB_PATH + DB_NAME;

    return myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);

    }

这是我用于在listview中显示项目的代码。

 public class newlist extends ListActivity {
    final adapter info = new adapter(this);
    String[] y = info.plist();
 /*   private static final String[] GENRES = new String[] {
        "Action", "Adventure", "Animation", "Children", "Comedy", "Documentary", "Drama",
        "Foreign", "History", "Independent", "Romance", "Sci-Fi", "Television", "Thriller"
    };*/

    private ListView listView = null;
    private MyArrayAdapter myArrayAdapter = null;
    private boolean editMode = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        this.listView = getListView();
        this.myArrayAdapter = new MyArrayAdapter(this, y);
        this.setListAdapter(this.myArrayAdapter);
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        menu.clear();

        MenuInflater inflater = this.getMenuInflater();

        if(!this.editMode) {
            inflater.inflate(R.menu.menu, menu);
        } else {
            inflater.inflate(R.menu.edit, menu);
        }

        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(item.getItemId() == R.id.edit_menu_item) {
            Toast.makeText(this, "entering edit mode", Toast.LENGTH_SHORT).show();

            this.editMode = true;
            this.listView.setItemsCanFocus(false);
            this.listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

            this.myArrayAdapter.setEditMode(editMode);
        } else if(item.getItemId() == R.id.commit_menu_item 
                || item.getItemId() == R.id.cancel_menu_item) {
            if(item.getItemId() == R.id.commit_menu_item) {
                Toast.makeText(this, "committing changes", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "leaving edit mode", Toast.LENGTH_SHORT).show();
            }

            this.editMode = false;
            this.listView.setItemsCanFocus(true);
            this.listView.setChoiceMode(ListView.CHOICE_MODE_NONE);
            this.listView.clearChoices();

            this.myArrayAdapter.setEditMode(editMode);
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        if(!this.editMode) {
            Toast.makeText(this, "list item selected at position " + position, Toast.LENGTH_SHORT).show();
        } else {
            String str = "";
            SparseBooleanArray wtfit = l.getCheckedItemPositions();
            for(int i = 0; i < y.length; i++) {
                if(wtfit.get(i)) {
                    str += i + ", ";
                }
            }

            Toast.makeText(this, "Selected item positions: " + str, Toast.LENGTH_SHORT).show();
        }

        super.onListItemClick(l, v, position, id);
    }

    class MyArrayAdapter extends ArrayAdapter<String> {
        private Context context;
        private String[] entires;

        private boolean editMode = false;

        public MyArrayAdapter(Context context, String[] entries) {
            super(context, R.layout.list_item, entries);

            this.context = context;
            this.entires = entries;
        }

        @Override
        public View getView(final int position, View view, ViewGroup parent) {
            final ListView listView = (ListView) parent;
            final ViewHolder viewHolder;

            if(view == null) {
                LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

                view = layoutInflater.inflate(R.layout.list_item, null, true);

                viewHolder = new ViewHolder();
                viewHolder.text1 = (TextView) view.findViewById(R.id.textView1);
                viewHolder.text2 = (TextView) view.findViewById(R.id.textView2);
                viewHolder.checkbox1 = (CheckBox) view.findViewById(R.id.checkBox1);

                view.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) view.getTag();
            }

            viewHolder.text1.setText(this.entires[position] + "_1");
            viewHolder.text2.setText(this.entires[position] + "_2");
            viewHolder.checkbox1.setChecked(listView.isItemChecked(position));

            if(this.editMode) {
                viewHolder.checkbox1.setVisibility(View.VISIBLE);
            } else {
                viewHolder.checkbox1.setVisibility(View.GONE);
            }

            return view;
        }

        public void setEditMode(boolean editMode) {
            this.editMode = editMode;
            this.notifyDataSetChanged();
        }

        class ViewHolder {
            TextView text1;
            TextView text2;
            CheckBox checkbox1;
        }
    }
}

logcat是,

09-09 05:57:05.687: E/AndroidRuntime(1188): FATAL EXCEPTION: main
09-09 05:57:05.687: E/AndroidRuntime(1188): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.fromstart/com.example.fromstart.newlist}: java.lang.NullPointerException
09-09 05:57:05.687: E/AndroidRuntime(1188):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2137)
09-09 05:57:05.687: E/AndroidRuntime(1188):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
09-09 05:57:05.687: E/AndroidRuntime(1188):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
09-09 05:57:05.687: E/AndroidRuntime(1188):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
09-09 05:57:05.687: E/AndroidRuntime(1188):     at android.os.Handler.dispatchMessage(Handler.java:99)
09-09 05:57:05.687: E/AndroidRuntime(1188):     at android.os.Looper.loop(Looper.java:137)
09-09 05:57:05.687: E/AndroidRuntime(1188):     at android.app.ActivityThread.main(ActivityThread.java:5103)
09-09 05:57:05.687: E/AndroidRuntime(1188):     at java.lang.reflect.Method.invokeNative(Native Method)
09-09 05:57:05.687: E/AndroidRuntime(1188):     at java.lang.reflect.Method.invoke(Method.java:525)
09-09 05:57:05.687: E/AndroidRuntime(1188):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
09-09 05:57:05.687: E/AndroidRuntime(1188):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
09-09 05:57:05.687: E/AndroidRuntime(1188):     at dalvik.system.NativeStart.main(Native Method)
09-09 05:57:05.687: E/AndroidRuntime(1188): Caused by: java.lang.NullPointerException
09-09 05:57:05.687: E/AndroidRuntime(1188):     at com.example.fromstart.adapter.plist(adapter.java:131)
09-09 05:57:05.687: E/AndroidRuntime(1188):     at com.example.fromstart.newlist.<init>(newlist.java:26)
09-09 05:57:05.687: E/AndroidRuntime(1188):     at java.lang.Class.newInstanceImpl(Native Method)
09-09 05:57:05.687: E/AndroidRuntime(1188):     at java.lang.Class.newInstance(Class.java:1130)
09-09 05:57:05.687: E/AndroidRuntime(1188):     at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
09-09 05:57:05.687: E/AndroidRuntime(1188):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2128)
09-09 05:57:05.687: E/AndroidRuntime(1188):     ... 11 more

2 个答案:

答案 0 :(得分:2)

有两件事。首先是你的数组初始化。这条线

String[] values = {};

创建一个没有分配内存的空数组。您需要初始化一个大小的数组,以容纳您要存储在数组中的所有元素。 例如在查询之后

String[] values = new String[c.getCount()];

然后,您似乎经常调用c.moveToNext()。一旦进入你的for循环,然后进入周围的do-while。

只需做一些像

这样的事情
while (c.moveToNext()) {
     values[i] = c.getString(c.getColumnIndex("PersonName"));
     i++;
}

答案 1 :(得分:0)

public class newlist extends ListActivity {
    final adapter info = new adapter(this);
    String[] y = info.plist();

看起来问题就在这里。在Activity对象初始化时,您尝试将Context用作newlist。在onCreate()之前你不能这样做。将您的adapter初始化和plist()电话移动到onCreate()以解决问题。