1

将记录添加到数据库,程序出错

日志

04-02 09:22:08.601: W/dalvikvm(4332): threadid=1: thread exiting with uncaught  exception (group=0x40018578)
    04-02 09:22:10.023: E/AndroidRuntime(4332): FATAL EXCEPTION: main
    04-02 09:22:10.023: E/AndroidRuntime(4332): java.lang.NullPointerException
    04-02 09:22:10.023: E/AndroidRuntime(4332):     at com.example.ok1.MySqlCursorAdapter.onClick(MySqlCursorAdapter.java:87)
    04-02 09:22:10.023: E/AndroidRuntime(4332):     at android.view.View.performClick(View.java:2485)
    04-02 09:22:10.023: E/AndroidRuntime(4332):     at android.widget.CompoundButton.performClick(CompoundButton.java:99)
    04-02 09:22:10.023: E/AndroidRuntime(4332):     at android.view.View$PerformClick.run(View.java:9080)
    04-02 09:22:10.023: E/AndroidRuntime(4332):     at android.os.Handler.handleCallback(Handler.java:587)
    04-02 09:22:10.023: E/AndroidRuntime(4332):     at     android.os.Handler.dispatchMessage(Handler.java:92)
    04-02 09:22:10.023: E/AndroidRuntime(4332):     at android.os.Looper.loop(Looper.java:130)
    04-02 09:22:10.023: E/AndroidRuntime(4332):     at android.app.ActivityThread.main(ActivityThread.java:3687)
    04-02 09:22:10.023: E/AndroidRuntime(4332):     at java.lang.reflect.Method.invokeNative(Native Method)
    04-02 09:22:10.023: E/AndroidRuntime(4332):     at java.lang.reflect.Method.invoke(Method.java:507)
    04-02 09:22:10.023: E/AndroidRuntime(4332):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
    04-02 09:22:10.023: E/AndroidRuntime(4332):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
    04-02 09:22:10.023: E/AndroidRuntime(4332):     at dalvik.system.NativeStart.main(Native Method)

MySqlCursorAdapter

   package com.example.ok1;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

public class MySqlCursorAdapter extends SimpleCursorAdapter implements
        OnClickListener {
    final String Tag = "States";
    private Context context;
    private DBHelper dbHelper;
    private Cursor currentCursor;

    public MySqlCursorAdapter(Context context, int layout, Cursor c,
            String[] from, int[] to, DBHelper dbHelper) {
        super(context, layout, c, from, to);
        Log.d(Tag, "трассировка1");
        this.currentCursor = c;
        this.context = context;
        this.dbHelper = dbHelper;
        Log.d(Tag, "MySqlCursorAdapter()");
        Integer b = c.getCount();
        Log.d(Tag, "b=" + b);
    }

    public View getView(int pos, View inView, ViewGroup parent) {
        Log.d(Tag, "getView() + posss=" + pos);
        View v = inView;
        if (v == null) {
            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = inflater.inflate(R.layout.my_list_item, null);
        }

        this.currentCursor.moveToPosition(pos);

        CheckBox cBox = (CheckBox) v.findViewById(R.id.bcheck);

        cBox.setTag(Integer.parseInt(this.currentCursor
                .getString(this.currentCursor
                        .getColumnIndex(DBHelper.COLUMN_ID))));
        Log.d(Tag, "tag=" + cBox.getTag().toString());
        if (this.currentCursor.getString(this.currentCursor
                .getColumnIndex(DBHelper.COLUMN_STATUS)) != null
                && Integer.parseInt(this.currentCursor
                        .getString(this.currentCursor
                                .getColumnIndex(DBHelper.COLUMN_STATUS))) != 0) {
            cBox.setChecked(true);
        } else {
            cBox.setChecked(false);
        }
        cBox.setOnClickListener(this);

        TextView txtTitle = (TextView) v.findViewById(R.id.txtTitle);
        txtTitle.setText(this.currentCursor.getString(this.currentCursor
                .getColumnIndex(DBHelper.COLUMN_NAME)));

        return (v);
    }

    public void ClearSelections() {
        Log.d(Tag, "ClearSelections()");
        this.dbHelper.clearSelections();
        this.currentCursor.requery();
    }

    @Override
    public void onClick(View v) {
        Log.d(Tag, "onClick");
        CheckBox cBox = (CheckBox) v;
        Integer _id = (Integer) cBox.getTag();
        Log.d(Tag, "Integer _id=" + _id.toString());
        ContentValues values = new ContentValues();
        values.put(" status", cBox.isChecked() ? 1 : 0);
        try {
            this.dbHelper.dbSqlite.update("mytable", values, "_id = ?",
                    new String[] { Integer.toString(_id) });
        } catch (SQLException sqle) {
            Log.d(Tag, "неудача");
            throw sqle;
        }
    }
}

错误出现在该行

"this.dbHelper.dbSqlite.update("mytable", values, "_id = ?", new String[] {     Integer.toString(_id) });"`
4

4 回答 4

1

dbSqlite上课DBhelper从来没有。initialized请这样做以避免NPE

将此方法添加到您的 DBhelper 类

 private void open() throws SQLException {
      dbSqlite = this.getWritableDatabase();
   }

并在你的构造函数中调用它

public DBHelper(Context context) {
    super(context, "myDB", null, 1);
    open();
}

但是上面所说的并不是处理 db 的最佳方法,但它可以帮助您继续前进

最好的方法是在 DBHelper 类中添加一个 open() 和 close() 方法,以便您可以在正确的条件下管理连接

关闭方法

 public void close() {
      this.close();
   }

打开()方法

public void open() throws SQLException {
      dbSqlite = this.getWritableDatabase();
   }

在 onclick() 的 MySqlCursorAdapter 类中

 try {
        DBhelper helper = new DBhelper(this);
        helper.open();
            helper.update("mytable", values, "_id = ?",
                    new String[] { Integer.toString(_id) });
        helper.close();
        } catch (SQLException sqle) {
            Log.d(Tag, "неудача");
            throw sqle;
        }
   }
于 2013-04-02T06:49:36.907 回答
1

请检查您在 DBHelper 类中的对象,因为 dbsqlite 是否已初始化

dbHelper.dbSqlite

正如您通过引用此行在问题中提到的那样。可能是你的 dbSqlite 没有初始化好吗

if(dbHelper.dbSqlite==null)
    // init first then used
于 2013-04-02T05:57:23.297 回答
0

您是否检查过您的表是否已创建

db.execSQL("创建表mytable("+"_id整型主键自增,"+"data_id文本,"+"名称文本,"+"任务文本,"+"状态整型"+");");

你不要在表创建中放置空格..使用这个

于 2013-04-02T06:28:54.703 回答
0

DBHelper
包 com.example.ok1;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.util.Log;


public class DBHelper extends SQLiteOpenHelper {
final String Tag="States";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_DATA = "data_id";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_STATUS = "status";
public static final String TABLE_NAME = "mytable";
public SQLiteDatabase dbSqlite;
public DBHelper(Context context) {
  // конструктор суперкласса
    super(context, "myDB", null, 1);
}



@Override
public void onCreate(SQLiteDatabase db) {
  Log.d(Tag, "--- onCreate database ---");
  // создаем таблицу с полями
  db.execSQL("create table mytable ("
      + "_id integer primary key autoincrement," 
      + "data_id text,"
      + "name text,"
      + "task text,"
      + "status integer"
       + ");");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}

public void clearSelections() {
    Log.d(Tag, "clearSelections()");
    ContentValues values = new ContentValues();
    values.put(" selected", 0);
    this.dbSqlite.update(DBHelper.TABLE_NAME, values, null, null);
}

public Cursor getCursor() {
    Log.d(Tag, "getCursor() получили курсор с базы");
        String[] columns = null;
        String selection = null;
        String[] selectionArgs = null;
        String groupBy = null;
        String having = null;
        String orderBy = null;
//  SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();

//  queryBuilder.setTables(TABLE_NAME);

//  String[] asColumnsToReturn = new String[] { COLUMN_ID, COLUMN_NAME,
//          COLUMN_DATA, COLUMN_STATUS };

//  Cursor mCursor = queryBuilder.query(dbSqlite, asColumnsToReturn, null,
//          null, null, null, "title ASC");
//  Log.d(Tag, "getCursor() получили курсор с базы конец");
            final SQLiteDatabase db = this.getWritableDatabase();
            columns = new String[] { COLUMN_ID, COLUMN_NAME, COLUMN_STATUS };
//              selection = "data_id = ?";
//              selectionArgs = new String[] {id_for_listtsk_today};
            Cursor c = db.query("mytable", columns, null, null, null, null, null);
    return c;
}
}
于 2013-04-02T06:19:00.677 回答