Android 将记录添加到数据库中,这是程序中的一个错误

Android 将记录添加到数据库中,这是程序中的一个错误,android,Android,将记录添加到数据库中,这是程序中的一个错误 日志 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 andro

将记录添加到数据库中,这是程序中的一个错误

日志

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) });"`

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

dbHelper.dbSqlite
正如你在问题中提到的,参考这一行。可能是您的dbSqlite未初始化,请

if(dbHelper.dbSqlite==null)
    // init first then used
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;
}
}

您是否检查了表是否已创建

db.execSQL(“创建表mytable(” +\u id整数主键自动递增 +“数据id文本,” +“名称文本,” +任务文本 +“状态整数” + ");");


在创建表时不使用空格。。在
DBhelper
类中使用此
dbSqlite
从未初始化过
。请避免出现
NPE

将此方法添加到DBhelper类

 private void open() throws SQLException {
      dbSqlite = this.getWritableDatabase();
   }
并在构造函数中调用它

public DBHelper(Context context) {
    super(context, "myDB", null, 1);
    open();
}
但上面所说的并不是处理db的最佳方法,但它可以帮助您继续前进

 public void close() {
      this.close();
   }
public void open() throws SQLException {
      dbSqlite = this.getWritableDatabase();
   }
最好的方法是向DBHelper类添加open()和close()方法,以便在正确的条件下管理连接

关闭方法

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

 public void close() {
      this.close();
   }
public void open() throws SQLException {
      dbSqlite = this.getWritableDatabase();
   }
在onclick()中的MySqlCursorAdapter类中


在更新之前检查-id的值是否得到任何值?据我所知,程序在一个循环中运行04-02 09:58:31.078:D/States(5690):onClick 04-02 09:58:31.078:D/States(5690):Integer _id=4 04-02 09:58:35.640:D/dalvikvm(5690):threadid=1:在撤消后仍然挂起(sc=1 dc=1)04-02 09:58:36.140:D/dalvikvm(5690):threadid=1:撤消后仍挂起(sc=1 dc=1)请提交DBhelper以获取更多帮助您的
this.DBhelper.DbQlite
为空..我的建议是在DBhelper中创建sqllite帮助程序的私有实例,并在DBhelper中而不是DBhelper中编写更新方法。在更新中使用新字符串[]{Long.toString(_id)}