SQLite数据库没有被创建..为什么?

时间:2011-12-23 09:24:12

标签: java android sqlite nullpointerexception broadcastreceiver

我试图将从某些特定消息收到的数据添加到SQLite数据库中。 但是,当我运行我的应用程序时,我收到的错误说...致命异常:主要由我的DBAdapter.java中的InsertTitle函数的Java Null指针异常引起

这是我的DBAdapter类

package com.lalsoft.janko;

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

public class DBAdapter 
{
public static final String KEY_ROWID = "_id";
public static final String KEY_GQTY = "gqty";
public static final String KEY_NQTY = "nqty";
public static final String KEY_DATE = "ddate";    
private static final String TAG = "DBAdapter";

private static final String DATABASE_NAME = "lalaqua";
private static final String DATABASE_TABLE = "nsales";
private static final int DATABASE_VERSION = 1;

private static final String DATABASE_CREATE =
    "create table titles (_id integer primary key autoincrement, "
    + "gqty text not null, nqty text not null, " 
    + "ddate text not null);";

private final Context context; 

private DatabaseHelper DBHelper;
private SQLiteDatabase db;

public DBAdapter(Context ctx) 
{
    this.context = ctx;
    DBHelper = new DatabaseHelper(context);
}

private static class DatabaseHelper extends SQLiteOpenHelper 
{
    DatabaseHelper(Context context) 
    {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) 
    {
        db.execSQL(DATABASE_CREATE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, 
    int newVersion) 
    {
        Log.w(TAG, "Upgrading database from version " + oldVersion 
                + " to "
                + newVersion + ", which will destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS titles");
        onCreate(db);
    }
}    

//---opens the database---
public DBAdapter open() throws SQLException 
{
    db = DBHelper.getWritableDatabase();
    return this;
}

//---closes the database---    
public void close() 
{
    DBHelper.close();
}

//---insert a title into the database---
public long insertTitle(String gqty, String nqty, String ddate) 
{
    ContentValues initialValues = new ContentValues();
    initialValues.put(KEY_GQTY, gqty);
    initialValues.put(KEY_NQTY, nqty);
    initialValues.put(KEY_DATE, ddate);
    return db.insert(DATABASE_TABLE, null, initialValues);
}

//---deletes a particular title---
public boolean deleteTitle(long rowId) 
{
    return db.delete(DATABASE_TABLE, KEY_ROWID + 
            "=" + rowId, null) > 0;
}

//---retrieves all the titles---
public Cursor getAllTitles() 
{
    return db.query(DATABASE_TABLE, new String[] {
            KEY_ROWID, 
            KEY_GQTY,
            KEY_NQTY,
            KEY_DATE}, 
            null, 
            null, 
            null, 
            null, 
            null);
}

//---retrieves a particular title---
public Cursor getTitle(long rowId) throws SQLException 
{
    Cursor mCursor =
            db.query(true, DATABASE_TABLE, new String[] {
                    KEY_ROWID,
                    KEY_GQTY, 
                    KEY_NQTY,
                    KEY_DATE
                    }, 
                    KEY_ROWID + "=" + rowId, 
                    null,
                    null, 
                    null, 
                    null, 
                    null);
    if (mCursor != null) {
        mCursor.moveToFirst();
    }
    return mCursor;
}

//---updates a title---
public boolean updateTitle(long rowId, String gqtr, 
String nqty, String ddate) 
{
    ContentValues args = new ContentValues();
    args.put(KEY_GQTY, gqtr);
    args.put(KEY_NQTY, nqty);
    args.put(KEY_DATE, ddate);
    return db.update(DATABASE_TABLE, args, 
                     KEY_ROWID + "=" + rowId, null) > 0;
}
}

这是从BroadcastReceiver扩展的类,它调用了inserttitle函数..

package com.lalsoft.janko;

import java.util.Calendar;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.gsm.SmsManager;
import android.telephony.gsm.SmsMessage;
import android.util.Log;

public class SMSReceiver extends BroadcastReceiver
{
public String SendMsgBody;
private static final String LOG_TAG = "JankoSMS";
public DBAdapter db; 
public Integer isDone=0;
public Double GrossQty,NetQty;

@Override
public void onReceive(Context context, Intent intent) 
{
    db = new DBAdapter(context); 
    //---get the SMS message passed in---
    Bundle bundle = intent.getExtras();        
    SmsMessage[] msgs = null;
    String str = "";
    String PhNo;
    String MsgBody;
    if (bundle != null)
    {
        //---retrieve the SMS message received---
        Object[] pdus = (Object[]) bundle.get("pdus");
        msgs = new SmsMessage[pdus.length];            
        for (int i=0; i<msgs.length; i++){
            msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);                
            str += "SMS from " + msgs[i].getOriginatingAddress();
            PhNo=msgs[i].getOriginatingAddress();
            str += " :";
            str += msgs[i].getMessageBody().toString();
            MsgBody=msgs[i].getMessageBody().toString();
            str += "\n";
           // EncodeSMS(MsgBody);

             String GQtyS,NQtyS,sDate;
             GQtyS="Ok";
             NQtyS="Done";
             sDate=getDate();
             Log.i(LOG_TAG, "Date" +" "+ sDate +" "+ GQtyS +" "+ NQtyS);
             long id;
             id = db.insertTitle(GQtyS ,NQtyS,sDate);    

        }

    }                         
}
public static String getDate()
{
    Calendar c = Calendar.getInstance();

    String sDate = c.get(Calendar.DAY_OF_MONTH) + "-" 
    + c.get(Calendar.MONTH)
    + "-" + c.get(Calendar.YEAR); 

    //+ " at " + c.get(Calendar.HOUR_OF_DAY) 
    //+ ":" + c.get(Calendar.MINUTE);
    return sDate;
}
}

此外,我已检查数据库未创建.. 那么这个问题的可能原因应该是什么?我该如何解决?请帮我摆脱这个麻烦。

3 个答案:

答案 0 :(得分:1)

我猜你没有调用db.open();这个方法

public DBAdapter open() throws SQLException 
{
    db = DBHelper.getWritableDatabase();
    return this;
}

答案 1 :(得分:1)

问题在于db.insert()方法的insertTitle()行。 You have to assign the value of db before using so use open the database before using by calling open()作为insertTitle()方法中的第一个语句

您的代码将如下所示

public long insertTitle(String gqty, String nqty, String ddate) 
{
    open();
    ContentValues initialValues = new ContentValues();
    initialValues.put(KEY_GQTY, gqty);
    initialValues.put(KEY_NQTY, nqty);
    initialValues.put(KEY_DATE, ddate);
    return db.insert(DATABASE_TABLE, null, initialValues);
}

答案 2 :(得分:0)

按照sunil&amp; amp;给出的上述2条建议。拉利特 包括下面的一个也就是放置db.execSQL(DATABASE_CREATE);在try catch block中

public void onCreate(SQLiteDatabase db) {
System.out.println("table created....");
          try{
        db.execSQL(DATABASE_CREATE);
          }catch (Exception e) {
            // TODO: handle exception
        }
    }