简体   繁体   English

Android:从列表视图中删除SQLite项目。 空指针异常

[英]Android: delete SQLite item from listview. NullPointerException

I'm pretty new to android (and programming) so I hope this question isn't too stupid. 我是android(和编程)的新手,所以我希望这个问题不会太愚蠢。 I've tried to answer my question through tutorials and by searching through stackoverflow without success. 我试图通过教程和通过stackoverflow搜索来回答我的问题,但是没有成功。

I'm trying to populate a list with an SQLite database: when I click an item on the list, I want it to delete from the listview and from the database, too. 我正在尝试使用SQLite数据库填充列表:当我单击列表中的一项时,我希望它也从列表视图和数据库中删除。 Through debugging, I think the problem is with the my ArrayAdapter methods, since even basic methods here like "getCount()" don't seem to produce outputs. 通过调试,我认为问题出在我的ArrayAdapter方法上,因为即使像“ getCount()”这样的基本方法似乎也无法产生输出。

For my SQLite DatabaseHandler class, here is the method for getting all the items in the database and for deleting an item: 对于我的SQLite DatabaseHandler类,以下是获取数据库中所有项目并删除项目的方法:

            // Getting All breadcrumbs
    public List<Breadcrumb> getAllBreadcrumbs() {
     List<Breadcrumb> breadcrumbList = new ArrayList<Breadcrumb>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_BREADCRUMBS;

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            Breadcrumb breadcrumb = new Breadcrumb();
            breadcrumb.setId(Integer.parseInt(cursor.getString(0)));
            breadcrumb.setBreadcrumbLatitude(cursor.getInt(1));
            breadcrumb.setBreadcrumbLongitude(cursor.getInt(2));
            // Adding location to list
            breadcrumbList.add(breadcrumb);
        } while (cursor.moveToNext());
    }

    // Deleting single breadcrumb
      public void deleteBreadcrumb(Breadcrumb breadcrumb) {
        SQLiteDatabase db = this.getWritableDatabase();
        int id = breadcrumb.getId();
        System.out.println("Comment deleted with id: " + id);
        db.delete(TABLE_BREADCRUMBS, KEY_ID
                + " = " + id, null);
        db.close();
          }

The XML layout for the troublesome activity: 麻烦的活动的XML布局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".CollectedBreadcrumbsActivity" >

<ListView
    android:id="@+id/list"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >
</ListView>

</LinearLayout>

And here is the activity: 这是活动:

public class CollectedBreadcrumbsActivity extends Activity implements OnItemClickListener {

private ListView listview;
private DatabaseHandler db;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_collected_breadcrumbs);

    DatabaseHandler db = new DatabaseHandler(this);
    List<Breadcrumb> breadcrumbs = db.getAllBreadcrumbs();

    listview = (ListView) findViewById(R.id.list);
    ArrayAdapter<Breadcrumb> adapter = new ArrayAdapter<Breadcrumb>(this,
            android.R.layout.simple_list_item_1, breadcrumbs);
        listview.setAdapter(adapter);
    listview.setOnItemClickListener(this);
}

public void onItemClick(AdapterView<?> l, View v, int position, long id) {
    Log.d("HelloListView", "You clicked Item: " + id + " at position:" + position);
    Log.d("HelloListView", "Number of items in adapter:" + listview.getAdapter().getCount());
    @SuppressWarnings("unchecked")
    ArrayAdapter<Breadcrumb> adapter = (ArrayAdapter<Breadcrumb>) listview.getAdapter();
    if (listview.getAdapter().getCount() > 0) {
        Breadcrumb breadcrumb = (Breadcrumb) listview.getAdapter().getItem(position);
        db.deleteBreadcrumb(breadcrumb);
        adapter.remove(breadcrumb);
        }
    adapter.notifyDataSetChanged();
    }
}

The listview shows up alright, but when I click an item on the list, the app crashes with the following log: 列表视图显示正常,但是当我单击列表上的项目时,应用程序崩溃并显示以下日志:

05-07 19:08:40.671: D/HelloListView(29562): You clicked Item: 5 at position:5
05-07 19:08:40.671: W/dalvikvm(29562): threadid=1: thread exiting with uncaught exception (group=0x40e4c438)
05-07 19:08:40.671: E/AndroidRuntime(29562): FATAL EXCEPTION: main
05-07 19:08:40.671: E/AndroidRuntime(29562): java.lang.NullPointerException
05-07 19:08:40.671: E/AndroidRuntime(29562):    at com.detimil.breadcrumbs1.CollectedBreadcrumbsActivity.onItemClick(CollectedBreadcrumbsActivity.java:42)
05-07 19:08:40.671: E/AndroidRuntime(29562):    at android.widget.AdapterView.performItemClick(AdapterView.java:298)
05-07 19:08:40.671: E/AndroidRuntime(29562):    at android.widget.AbsListView.performItemClick(AbsListView.java:1268)
05-07 19:08:40.671: E/AndroidRuntime(29562):    at android.widget.AbsListView$PerformClick.run(AbsListView.java:3059)
05-07 19:08:40.671: E/AndroidRuntime(29562):    at android.widget.AbsListView$1.run(AbsListView.java:3950)
05-07 19:08:40.671: E/AndroidRuntime(29562):    at android.os.Handler.handleCallback(Handler.java:615)
05-07 19:08:40.671: E/AndroidRuntime(29562):    at android.os.Handler.dispatchMessage(Handler.java:92)
05-07 19:08:40.671: E/AndroidRuntime(29562):    at android.os.Looper.loop(Looper.java:137)
05-07 19:08:40.671: E/AndroidRuntime(29562):    at android.app.ActivityThread.main(ActivityThread.java:4950)
05-07 19:08:40.671: E/AndroidRuntime(29562):    at java.lang.reflect.Method.invokeNative(Native Method)
05-07 19:08:40.671: E/AndroidRuntime(29562):    at java.lang.reflect.Method.invoke(Method.java:511)
05-07 19:08:40.671: E/AndroidRuntime(29562):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1004)
05-07 19:08:40.671: E/AndroidRuntime(29562):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:771)
05-07 19:08:40.671: E/AndroidRuntime(29562):    at dalvik.system.NativeStart.main(Native Method)

Again, I think the problem must be with my ArrayAdapter because even this log Log.d("HelloListView", "Number of items in adapter:" + listview.getAdapter().getCount()); 再次,我认为问题一定出在我的ArrayAdapter上,因为即使这个日志Log.d("HelloListView", "Number of items in adapter:" + listview.getAdapter().getCount()); doesn't produce anything before the app crashes. 在应用崩溃之前不会产生任何东西。

If anyone has any thoughts on this I would really appreciate the help. 如果有人对此有任何想法,我将非常感谢您的帮助。 Again, sorry if this is a silly question. 再次,抱歉,如果这是一个愚蠢的问题。

Thank you very much. 非常感谢你。

Your db is null , 您的dbnull

Because 因为

  DatabaseHandler db = new DatabaseHandler(this);

it will create a local instance but doesn't instantiate db field so make it like this 它将创建一个本地实例,但不实例化db字段,因此使其如下所示

db = new DatabaseHandler(this);

Your db should be inititated globally not locally. 您的数据库应该在全局而不是本地启动。

I would like to add that overall it's not a good idea to use ArrayAdapter to load from DB. 我想补充一点,总体而言,使用ArrayAdapter从数据库加载不是一个好主意。 You should use CursorAdapter and CursorLoader to manage database. 您应该使用CursorAdapter和CursorLoader来管理数据库。

Here's a good tutorial on custom CursorAdapter: link 这是有关自定义CursorAdapter的很好的教程: 链接

Another one for CursorLoaders: link CursorLoaders的另一个: 链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM