自定义SimpleCursorAdapter、数据库查询和NullPointerException

发布于 2024-11-02 13:24:10 字数 4773 浏览 0 评论 0原文

我试图让 ListView 从数据库中填充,并用精美的删除按钮为每一行添加香料。所以我制作了列表 Activity 和自定义 SimpleCursorAdapter。

这是主要的 ListView 活动:

    public class EditEntries extends ListActivity {
    Cursor cursor;
    DBAdapter db = new DBAdapter(this);
    private static String[] FROM = { _ID, SCORE_COLUMN,
            "date(time, 'localtime')", };
    private static int[] TO = { R.id.rowid, R.id.title, R.id.time, };

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.entries_list);
        try {
            cursor = getEvents();
            showEvents(cursor);
        } finally {
            db.close();
        }
    }

    private void showEvents(Cursor cursor) {
        // Set up data binding
        SMSimpleCursorAdapter adapter = new SMSimpleCursorAdapter(this,
                R.layout.entries_list_item, cursor, FROM, TO);
        setListAdapter(adapter);

    }

    private Cursor getEvents() {
        db.open();
        cursor = db.getAllScores();
        startManagingCursor(cursor);
        return cursor;
    }

    void delRow() {        // this is method for deleting row by _id
        db.open();
        db.deleteScore(3); // here will be TAG with _id from adapter,
        db.close();        // for now I just use hardcoded _id
    }

}

这是自定义的 SimpleCursorAdapter:

    public class SMSimpleCursorAdapter extends SimpleCursorAdapter{
    
    Cursor c;
    Context context;
    Activity activity;

    public SMSimpleCursorAdapter(Context context, int layout, Cursor c,
            String[] from, int[] to) {
        super(context, layout, c, from, to);
        
        this.c = c;
        this.context=context;
        this.activity=(Activity) context;
        
    }
    EditEntries dbDel = new EditEntries(); //from previous code sample

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if(convertView == null)
            convertView = View.inflate(context, R.layout.entries_list_item, null);
        View row = convertView;
        
        c.moveToPosition(position);
        
        TextView score = (TextView) convertView.findViewById(R.id.title);
        TextView time = (TextView) convertView.findViewById(R.id.time);
        TextView id = (TextView) convertView.findViewById(R.id.rowid);
        
        id.setText(c.getString(0));
        time.setText(c.getString(2));
        score.setText(c.getString(1));
        
        String daTag = c.getString(1);
        
        ImageButton delButton = (ImageButton) convertView.findViewById(R.id.delButton);
        delButton.setFocusable(true);
        delButton.setClickable(true);
        //delButton.setTag(daTag);
        delButton.setOnClickListener(new OnClickListener() { //Click listener fro delete button
             @Override
             public void onClick(View view) {
                 dbDel.delRow(); //this is "delete row" method from previos code                    sample
             }
             });

        return(row);
    }

}

当我单击删除按钮时,所有这些东西都会给我 NullPointerException 。 我是 Android 新手,假设我错过了一些明显的东西。

日志猫:

错误/AndroidRuntime(14027):致命异常:主要

错误/AndroidRuntime(14027): java.lang.NullPointerException

错误/AndroidRuntime(14027):位于 android.content.ContextWrapper.openOrCreateDatabase(ContextWrapper.java:203)

错误/AndroidRuntime(14027):位于 android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:98)

错误/AndroidRuntime(14027):位于namespace.DBAdapter.open(DBAdapter.java:66)

错误/AndroidRuntime(14027):位于命名空间.EditEntries.delRow(EditEntries.java:50)

错误/AndroidRuntime(14027):位于命名空间.SMSimpleCursorAdapter$1.onClick(SMSimpleCursorAdapter.java:64)

错误/AndroidRuntime(14027):位于 android.view.View.performClick(View.java:2414)

错误/AndroidRuntime(14027):位于 android.view.View$PerformClick.run(View.java:8838)

错误/AndroidRuntime(14027):位于 android.os.Handler.handleCallback(Handler.java:587)

错误/AndroidRuntime(14027):位于 android.os.Handler.dispatchMessage(Handler.java:92)

错误/AndroidRuntime(14027):位于 android.os.Looper.loop(Looper.java:123)

错误/AndroidRuntime(14027):位于 android.app.ActivityThread.main(ActivityThread.java:4680)

错误/AndroidRuntime(14027):位于 java.lang.reflect.Method.invokeNative(本机方法)

错误/AndroidRuntime(14027):位于 java.lang.reflect.Method.invoke(Method.java:521)

错误/AndroidRuntime(14027):位于 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)

错误/AndroidRuntime(14027):位于 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

错误/AndroidRuntime(14027):位于 dalvik.system.NativeStart.main(本机方法)

I'm trying to make ListView populated from database, and spice each row with fancy delete button. So I made list Activity and custom SimpleCursorAdapter.

This is main ListView activity:

    public class EditEntries extends ListActivity {
    Cursor cursor;
    DBAdapter db = new DBAdapter(this);
    private static String[] FROM = { _ID, SCORE_COLUMN,
            "date(time, 'localtime')", };
    private static int[] TO = { R.id.rowid, R.id.title, R.id.time, };

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.entries_list);
        try {
            cursor = getEvents();
            showEvents(cursor);
        } finally {
            db.close();
        }
    }

    private void showEvents(Cursor cursor) {
        // Set up data binding
        SMSimpleCursorAdapter adapter = new SMSimpleCursorAdapter(this,
                R.layout.entries_list_item, cursor, FROM, TO);
        setListAdapter(adapter);

    }

    private Cursor getEvents() {
        db.open();
        cursor = db.getAllScores();
        startManagingCursor(cursor);
        return cursor;
    }

    void delRow() {        // this is method for deleting row by _id
        db.open();
        db.deleteScore(3); // here will be TAG with _id from adapter,
        db.close();        // for now I just use hardcoded _id
    }

}

And this is custom SimpleCursorAdapter:

    public class SMSimpleCursorAdapter extends SimpleCursorAdapter{
    
    Cursor c;
    Context context;
    Activity activity;

    public SMSimpleCursorAdapter(Context context, int layout, Cursor c,
            String[] from, int[] to) {
        super(context, layout, c, from, to);
        
        this.c = c;
        this.context=context;
        this.activity=(Activity) context;
        
    }
    EditEntries dbDel = new EditEntries(); //from previous code sample

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if(convertView == null)
            convertView = View.inflate(context, R.layout.entries_list_item, null);
        View row = convertView;
        
        c.moveToPosition(position);
        
        TextView score = (TextView) convertView.findViewById(R.id.title);
        TextView time = (TextView) convertView.findViewById(R.id.time);
        TextView id = (TextView) convertView.findViewById(R.id.rowid);
        
        id.setText(c.getString(0));
        time.setText(c.getString(2));
        score.setText(c.getString(1));
        
        String daTag = c.getString(1);
        
        ImageButton delButton = (ImageButton) convertView.findViewById(R.id.delButton);
        delButton.setFocusable(true);
        delButton.setClickable(true);
        //delButton.setTag(daTag);
        delButton.setOnClickListener(new OnClickListener() { //Click listener fro delete button
             @Override
             public void onClick(View view) {
                 dbDel.delRow(); //this is "delete row" method from previos code                    sample
             }
             });

        return(row);
    }

}

And all this stuff gives me NullPointerException when I click delete button.
I'm new to android, and suppose that I just missed something obvious.

LogCat:

ERROR/AndroidRuntime(14027): FATAL EXCEPTION: main

ERROR/AndroidRuntime(14027): java.lang.NullPointerException

ERROR/AndroidRuntime(14027): at android.content.ContextWrapper.openOrCreateDatabase(ContextWrapper.java:203)

ERROR/AndroidRuntime(14027): at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:98)

ERROR/AndroidRuntime(14027): at namespace.DBAdapter.open(DBAdapter.java:66)

ERROR/AndroidRuntime(14027): at namespace.EditEntries.delRow(EditEntries.java:50)

ERROR/AndroidRuntime(14027): at namespace.SMSimpleCursorAdapter$1.onClick(SMSimpleCursorAdapter.java:64)

ERROR/AndroidRuntime(14027): at android.view.View.performClick(View.java:2414)

ERROR/AndroidRuntime(14027): at android.view.View$PerformClick.run(View.java:8838)

ERROR/AndroidRuntime(14027): at android.os.Handler.handleCallback(Handler.java:587)

ERROR/AndroidRuntime(14027): at android.os.Handler.dispatchMessage(Handler.java:92)

ERROR/AndroidRuntime(14027): at android.os.Looper.loop(Looper.java:123)

ERROR/AndroidRuntime(14027): at android.app.ActivityThread.main(ActivityThread.java:4680)

ERROR/AndroidRuntime(14027): at java.lang.reflect.Method.invokeNative(Native Method)

ERROR/AndroidRuntime(14027): at java.lang.reflect.Method.invoke(Method.java:521)

ERROR/AndroidRuntime(14027): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)

ERROR/AndroidRuntime(14027): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

ERROR/AndroidRuntime(14027): at dalvik.system.NativeStart.main(Native Method)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

面如桃花 2024-11-09 13:24:10

问题出在您的 SMSimpleCursorAdapter 代码中:

EditEntries dbDel = new EditEntries(); //from previous code sample

您创建了一个新对象,但它不会是托管活动(例如,不会调用 onCreate 方法)。当您尝试第二次(从您的适配器)创建 NPE 时,NPE 可能来自您的 DBAdapter。

快速修复:

EditEntries dbDel; //from previous code sample
public SMSimpleCursorAdapter(Context context, int layout, Cursor c,
        String[] from, int[] to) {
    super(context, layout, c, from, to);

    this.c = c;
    this.context = context;
    this.activity = (Activity) context;
    this.dbDel = (EditEntries) context;
}

如果您不想只是快速修复,以下将是一个更好的解决方案:

  1. 将 delRow、getEvents 方法移至 DBAdapter 类中
  2. 修改 SMSimpleCursorAdapter 的构造函数以在 DBAdapter 类中给出(在 ListActivity 中创建) 。

The problem is in your SMSimpleCursorAdapter code:

EditEntries dbDel = new EditEntries(); //from previous code sample

You create a new object but it won't be a managed Activity (eg. the onCreate method won't be called). The NPE probably comes from your DBAdapter when you try to create it the second time (from your Adapter).

Quick fix:

EditEntries dbDel; //from previous code sample
public SMSimpleCursorAdapter(Context context, int layout, Cursor c,
        String[] from, int[] to) {
    super(context, layout, c, from, to);

    this.c = c;
    this.context = context;
    this.activity = (Activity) context;
    this.dbDel = (EditEntries) context;
}

If you don't want just a quick fix the following would be a much better solution:

  1. Move the delRow, getEvents method into your DBAdapter class
  2. Modify the constructor of your SMSimpleCursorAdapter to give in the DBAdapter class (created in your ListActivity).
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文