使用Android SQLiteDatabase insert()方法时出错

时间:2010-12-08 15:36:24

标签: android sqlite

我正在尝试在Activity中使用SQLiteDatabase中的方法插入。但我有这个错误:

  

12-08 13:28:24.497:ERROR / AndroidRuntime(20051):引起:java.lang.NullPointerException   12-08 13:28:24.497:ERROR / AndroidRuntime(20051):在android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:118)   12-08 13:28:24.497:ERROR / AndroidRuntime(20051):at com.psyhclo.RatedCalls.onCreate(RatedCalls.java:42)

错误在这一行:

  

this.db = openHelper.getWritableDatabase();

这是名为 RatedCalls.java 的活动的代码:

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;

import com.psyhclo.R;
import com.psyhclo.CallDataHelper.OpenHelper;

import android.app.Activity;
import android.app.ListActivity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.content.ContentValues;
import android.content.Context;

public class RatedCalls extends ListActivity {

private Context context;
private static TextView txtView;
private SQLiteDatabase db;
private CallDataHelper dh = null;
StringBuilder sb = new StringBuilder();
OpenHelper openHelper = new OpenHelper(this.context);


public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Cursor cursor = getContentResolver().query(
            android.provider.CallLog.Calls.CONTENT_URI, null, null, null,
            android.provider.CallLog.Calls.DATE + " DESC ");

    dh = new CallDataHelper(this);  
    db = openHelper.getWritableDatabase();

    startManagingCursor(cursor);
    int numberColumnId = cursor
            .getColumnIndex(android.provider.CallLog.Calls.NUMBER);
    int durationId = cursor
            .getColumnIndex(android.provider.CallLog.Calls.DURATION);
    int contactNameId = cursor
            .getColumnIndex(android.provider.CallLog.Calls.CACHED_NAME);
    int dateId = cursor.getColumnIndex(android.provider.CallLog.Calls.DATE);
    int numTypeId = cursor
            .getColumnIndex(android.provider.CallLog.Calls.CACHED_NUMBER_TYPE);
    Date dt = new Date();
    int hours = dt.getHours();
    int minutes = dt.getMinutes();
    int seconds = dt.getSeconds();
    String currTime = hours + ":" + minutes + ":" + seconds;

    ArrayList<String> callList = new ArrayList<String>();
    if (cursor.moveToFirst()) {
        do {

            String contactNumber = cursor.getString(numberColumnId);
            String contactName = cursor.getString(contactNameId);
            String duration = cursor.getString(durationId);
            String callDate = DateFormat.getDateInstance().format(dateId);
            String numType = cursor.getString(numTypeId);

            ContentValues values = new ContentValues();

            values.put("contact_id", 1);
            values.put("contact_name", contactName);
            values.put("number_type", numType);
            values.put("contact_number", contactNumber);
            values.put("duration", duration);
            values.put("date", callDate);
            values.put("current_time", currTime);
            values.put("cont", 1);

            this.db.insert(CallDataHelper.TABLE_NAME, null, values);

            this.dh.insert(1, contactName, numType, contactNumber,
                    duration, callDate, currTime);
            Toast.makeText(getBaseContext(), "Inserted!", Toast.LENGTH_LONG);
            callList.add("Contact Number: " + contactNumber
                    + "\nContact Name: " + contactName + "\nDuration: "
                    + duration + "\nDate: " + callDate);

        } while (cursor.moveToNext());
    }
    setListAdapter(new ArrayAdapter<String>(this, R.layout.listitem,
            callList));
    ListView lv = getListView();
    lv.setTextFilterEnabled(true);

    lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {

            Toast.makeText(getApplicationContext(),
                    ((TextView) view).getText(), Toast.LENGTH_SHORT).show();

        }
    });
}
    }

这是名为 CallDataHelper.java 的Datahelper类,其中OpenHelper类被声明为子类。

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.SQLiteStatement;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

public class CallDataHelper {

private static final String DATABASE_NAME = "calls.db";
private static final int DATABASE_VERSION = 1;
protected static final String TABLE_NAME = "contact_data";

private Context context;
private SQLiteDatabase db;

public CallDataHelper(Context context) {
    this.context = context;
    OpenHelper openHelper = new OpenHelper(this.context);
    this.db = openHelper.getWritableDatabase();
}

public boolean insert(Integer cId, String cName, String numType,
        String cNum, String dur, String date, String currTime) {
    this.db.execSQL("insert into "
            + TABLE_NAME
            + " (contact_id, contact_name, number_type, contact_number, duration, date, current_time, cont) "
            + " values( " + cId + ", " + cName + ", " + numType + ", "
            + cNum + ", " + dur + ", " + date + ", " + currTime + ", 1)");
    return true;        
}   

public void update(String word) {
    this.db.execSQL("UPDATE words SET cont = cont + 1 WHERE (word= ?)",
            new String[] { word });
}

public void deleteAll() {
    this.db.delete(TABLE_NAME, null, null);
}

public boolean select(String wrd) {

    String word;
    Cursor cursor = this.db.query(TABLE_NAME, new String[] { "word" },
            "word like ?", new String[] { wrd }, null, null, null);
    if (cursor.moveToFirst()) {
        do {
            word = cursor.getString(0);
        } while (cursor.moveToNext());
    }
    if (cursor != null && !cursor.isClosed()) {
        cursor.close();
        return true;
    } else {
        return false;
    }
}

public List<String> selectAll() {
    List<String> list = new ArrayList<String>();
    Cursor cursor = this.db.query(TABLE_NAME, new String[] { "word" },
            null, null, null, null, "cont desc");
    if (cursor.moveToFirst()) {
        do {
            list.add(cursor.getString(0).toUpperCase());
        } while (cursor.moveToNext());
    }
    if (cursor != null && !cursor.isClosed()) {
        cursor.close();
    }
    return list;
}

public static class OpenHelper extends SQLiteOpenHelper {

    OpenHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE "
                + TABLE_NAME
                + "(id INTEGER PRIMARY KEY AUTOINCREMENT, contact_id INTEGER, contact_name VARCHAR(50), number_type VARCHAR(50), contact_number VARCHAR(50), duration TIME, date DATE, current_time TIME, cont INTEGER)");

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.w("RatedCalls Database",
                "Upgrading database, this will drop tables and recreate.");
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(db);
    }
}
    }

3 个答案:

答案 0 :(得分:0)

您在创建活动时实例化openHelper,此时context为空。

private Context context;

OpenHelper openHelper = new OpenHelper(this.context);

db = openHelper.getWritableDatabase();

也许你打算这样做?

dh = new CallDataHelper(this);  
db = dh.getWritableDatabase();

答案 1 :(得分:0)

看看你的OpenHelper课程。 您已将其声明为static类,并且其中包含构造函数。

删除static以便能够实例化OpenHelper

此外,您已使用

初始化openHelper
OpenHelper openHelper = new OpenHelper(this.context);

在任何方法之外,所以你没有this对当前对象的任何引用。

尝试:

OpenHelper openHelper;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    openHelper = new OpenHelper(this);

答案 2 :(得分:0)