Android在DatabaseHandler函数中获取java.lang.NullPointerException

时间:2014-08-30 07:16:43

标签: java android android-sqlite

使用这个简单的函数我想将记录保存到数据库中,但是我收到了这个错误:

java.lang.NullPointerException 

这一行:

SQLiteDatabase db = this.getWritableDatabase();

我的完整DatabaseHandler类:

public class DatabaseHandler extends SQLiteOpenHelper{
        private static String DB_PATH                   = "";
        private static final String DATABASE_NAME       = "tsms";
        private static String RECEIVE_FIELDS_TABLE      = "ReceiveFields";
        private static final String COLUMN_ID           = "id";
        private static final String COLUMN_LASTID       = "lastId";
        private static final String COLUMN_SMSNUMBER    = "smsNumber";
        private static final String COLUMN_MOBILENUMBER = "mobileNumber";
        private static final String COLUMN_SENDERNAME   = "senderName";
        private static final String COLUMN_SMSBODY      = "smsBody";
        private static final String COLUMN_RECEIVEDATE  = "receiveDate";
        private static final int DATABASE_VERSION = 1;
        private SQLiteDatabase mDataBase;
        private static final String DATABASE_CREATE = "CREATE TABLE " + RECEIVE_FIELDS_TABLE + "("
                + COLUMN_ID           + " INTEGER NOT NULL  UNIQUE , "
                + COLUMN_LASTID       + " INTEGER NOT NULL  UNIQUE , "
                + COLUMN_SMSNUMBER    + " INTEGER NOT NULL  UNIQUE , "
                + COLUMN_MOBILENUMBER + " INTEGER NOT NULL , "
                + COLUMN_SENDERNAME   + " VARCHAR NOT NULL , "
                + COLUMN_SMSBODY      + " TEXT NOT NULL  check(typeof(" + COLUMN_SMSBODY + ") = 'text') , "
                + COLUMN_RECEIVEDATE  + " DATETIME NOT NULL , PRIMARY KEY (" + COLUMN_ID + ", " + COLUMN_LASTID + ", " + COLUMN_SMSNUMBER + "))";

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

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

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

        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + RECEIVE_FIELDS_TABLE);

        // Create tables again
        onCreate(sqLiteDatabase);
    }

    // Adding new fields
    public void addToReceived(ReceiveFields fields) {

        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();

        values.put(COLUMN_LASTID,       fields.getLastId());           // ReceiveFields last ID
        values.put(COLUMN_MOBILENUMBER, fields.getMobileNumber());     // ReceiveFields Mobile Number
        values.put(COLUMN_SENDERNAME,   fields.getSenderName());       // ReceiveFields Mobile Number
        values.put(COLUMN_SMSBODY,      fields.getSmsBody());          // ReceiveFields Mobile Number
        values.put(COLUMN_SMSNUMBER,    fields.getSmsNumber());        // ReceiveFields Mobile Number
        values.put(COLUMN_MOBILENUMBER, fields.getMobileNumber());     // ReceiveFields Mobile Number
        values.put(COLUMN_RECEIVEDATE,  String.valueOf(fields.getReceiveDate())); // ReceiveFields Mobile Number

        // Inserting Row
        db.insert(RECEIVE_FIELDS_TABLE, null, values);

        db.close(); // Closing database connection
    }
}

致电和使用:

DatabaseHandler db = new DatabaseHandler(context);

db.addToReceived(new ReceiveFields(

                            Long.valueOf(str1[0]),

                            str1[1],

                            str1[2],

                            URLDecoder.decode(str1[3], "UTF-8"),

                            URLDecoder.decode(str1[4], "UTF-8"),

                            WSDLHelper.convertDate(str1[5])));

更新帖子

TSMS类,在数据库中使用save方法:

public class TSMS {

    private User user;

    public SoapObject SoapObjectRequest;
    private Context context;

    public TSMS(User user) {
        this.user = user;
    }

    public Boolean checkUserAuth() throws TException{

        SoapObject request = new SoapObject(Strings.URL_TSMS , Strings.NAME_METHOD_IS_FROM_USERS);

        this.SoapObjectRequest = request;

        request.addProperty("userName", this.user.userName);

        request.addProperty("passWord", this.user.passWord);

        LoginFields loginSoapParser = SoapParser(WSDLHelper.convert1(WSDLHelper.call(request)));

        if ( loginSoapParser.ckeckAuth){

            return true;

        }
        else{

            return false;

        }
    }
    public LoginFields SoapParser(String result){

        String receiveResult = result;

        String split[] = result.split(",");

        LoginFields loginFields = new LoginFields();

        String numbers = split[2].trim();

        String removeBracket = numbers.substring(1, numbers.length() - 1);

        String items[] = removeBracket.split(";");

        StringBuilder panelNumbers = new StringBuilder();

        for( int i=0; i < items.length; i++){

            String r = items[i].replaceAll("[item=]","").trim();

            panelNumbers.append( r );

        }

        loginFields.ckeckAuth = (Integer.valueOf(split[0]) == 1 ) ? true : false;

        loginFields.balance   =  Integer.valueOf( split[1].trim() );

        loginFields.panelNumbers = panelNumbers;

        return  loginFields;

    }
    public List<ReceiveFields> getReceivedSMS(long idToDown, long count) throws TException {

        SoapObject request = new SoapObject(Strings.URL_TSMS , Strings.NAME_METHOD_GET_RECEIVE_MESSAGE);

        request.addProperty("userName", this.user.userName);

        request.addProperty("passWord", this.user.passWord);

        request.addProperty("idToDown", idToDown);

        request.addProperty("count_request", count);

        String str = WSDLHelper.call(request);

        String[] strings = WSDLHelper.convert2(WSDLHelper.convert1(str));

        List<ReceiveFields> receiveArray = new ArrayList<ReceiveFields>();

        DatabaseHandler db = new DatabaseHandler(context);

        if (strings != null) {

            for (int i = 0; i <= strings.length - 1; i++) {

                String[] str1 = WSDLHelper.convert3(strings[i]);

                try {

                    receiveArray.add(new ReceiveFields(

                            Long.valueOf(str1[0]),

                            str1[1],

                            str1[2],

                            URLDecoder.decode(str1[3], "UTF-8"),

                            URLDecoder.decode(str1[4], "UTF-8"),

                            WSDLHelper.convertDate(str1[5])));

                    db.addToReceived(new ReceiveFields(

                            Long.valueOf(str1[0]),

                            str1[1],

                            str1[2],

                            URLDecoder.decode(str1[3], "UTF-8"),

                            URLDecoder.decode(str1[4], "UTF-8"),

                            WSDLHelper.convertDate(str1[5])));

                }

                catch (UnsupportedEncodingException ex) {

                    throw new TException(PublicErrorList.NOT_EXIST_ERROR_DETAIL);

                }
            }
        }
        return receiveArray;
    }
    public String sendSms( SendSms sms )  throws TException {
        SoapObject request = new SoapObject(Strings.URL_TSMS , Strings.NAME_METHOD_SEND_MESSAGE);
        request.addProperty("user", this.user.userName);
        request.addProperty("pass", this.user.passWord);
        request.addProperty("sms_number", sms.senderNumber);
        request.addProperty("mobile", sms.receiverNumber);
        request.addProperty("msg", sms.text);
        request.addProperty("send_date", WSDLHelper.convertDate( sms.dateTime) );
        return WSDLHelper.call(request);
    }
}

User上课:

public class User {
    public String userName;
    public String passWord;

    public User(String userName, String passWord) {
        this.userName = userName;
        this.passWord = passWord;
    }
}

2 个答案:

答案 0 :(得分:2)

更改TSMS类构造函数

public TSMS(Context context , User user) {
    this.user = user;
    this.context = context;
}

答案 1 :(得分:1)

来自last question

据我所知,我认为你仍然不确定Context in android

解决根问题的一些建议:

1)在ReceiveFields()构造函数中,您只需使用上下文变量来解决错误,如下所示。

Context ctx = null;
public ReceiveFields(Context ctx){
  this.ctx=ctx; //create a field Context ctx;
}

在这里,你可以使用PG_Android的解决方案来解决错误,但如果你不能从你的活动中传递主要背景,你仍然无法解决根本问题。

只需检查您调用/初始化主类的主要活动(我认为是TSMS) 并通过适当的上下文修复主要问题,如:

 TSMS obj = new TSMS(your_current_activity.this);

这里你的your_current_activity.this将作为所有类和数据库中的主要上下文..我想你理解..