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

时间:2013-04-02 05:44:12

标签: android

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

日志

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 个答案:

答案 0 :(得分:1)

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

dbHelper.dbSqlite

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

if(dbHelper.dbSqlite==null)
    // init first then used

答案 1 :(得分:1)

dbSqlite课程中的

DBhelper从未initialized。请这样做以避免NPE

将此方法添加到您的DBhelper类

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

并在构造函数中调用它

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

但它上面说的不是处理数据库的最佳方式,但它可以帮助你继续前进

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

关闭方法

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

open()方法

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;
        }
   }

答案 2 :(得分: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;
}
}

答案 3 :(得分:0)

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

  

db.execSQL(“create table mytable(”         +“_id整数主键自动增量”         +“data_id text”         +“名称文字”         +“任务文字”         +“状态整数”          +“);”);

你没有在表创建中添加空格..使用此