-3

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

助手.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);

    }

这是我用来在列表视图中显示项目的代码。

 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
4

2 回答 2

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++;
}
于 2013-09-09T10:19:33.520 回答
0
public class newlist extends ListActivity {
    final adapter info = new adapter(this);
    String[] y = info.plist();

看起来问题就在这里。您正在尝试在初始化对象时使用Activityas a 。直到. 移动你的初始化和调用,不管是什么,来修复它。ContextnewlistonCreate()adapterplist()onCreate()

于 2013-09-09T10:19:50.533 回答