-1

with this simple function i want to save records into database but i get this error :

java.lang.NullPointerException 

for this line:

SQLiteDatabase db = this.getWritableDatabase();

My full DatabaseHandler class:

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

call and use:

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])));

UPDATED POST

TSMS class with save method on database:

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 class:

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

    public User(String userName, String passWord) {
        this.userName = userName;
        this.passWord = passWord;
    }
}
DolDurma
  • 15,753
  • 51
  • 198
  • 377
  • possible duplicate of [nullPointerException for SQLiteOpenHelper.getWritableDatabase(), Android](http://stackoverflow.com/questions/15964850/nullpointerexception-for-sqliteopenhelper-getwritabledatabase-android) – Jens Aug 30 '14 at 07:21
  • @TuxWorld can you show me that how you initialize your `TSMS` class in your activity ..because i think you still not solve your last question properly.. – Ranjit Aug 30 '14 at 07:27
  • Can you provide us with the full stacktrace plz? – hoomi Aug 30 '14 at 07:27
  • @TuxWorld I just want to see in which activity you write or initialize the `ReceiveFields` class like `ReceiveFields obj = new ReceiveFields(context)` ..i did not found this one in this class.. – Ranjit Aug 30 '14 at 07:34
  • Are you using this code DatabaseHandler db = new DatabaseHandler(context); in your activity? – Piyush Aug 30 '14 at 07:35
  • @PG_Android i'm using save on java class not an activity – DolDurma Aug 30 '14 at 07:35

2 Answers2

2

Change your TSMS class constructor

public TSMS(Context context , User user) {
    this.user = user;
    this.context = context;
}
Piyush
  • 18,895
  • 5
  • 32
  • 63
  • after change constructor i get error `null`: `java.lang.NullPointerException` for `SQLiteDatabase db = this.getWritableDatabase();` – DolDurma Aug 30 '14 at 07:49
  • In which class this line showing error SQLiteDatabase db = this.getWritableDatabase();? – Piyush Aug 30 '14 at 07:50
  • in `DatabaseHandler` class. i'm change constructors to : `public DatabaseHandler(Context context,String DB_NAME, int Version) { super(context, DB_NAME, null, Version); this.context = context; } public DatabaseHandler(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); }` – DolDurma Aug 30 '14 at 07:55
  • i think my this line is not correct into `TSMS` class` : `DatabaseHandler db = new DatabaseHandler(context);` for this constructor: `DatabaseHandler(Context context)` in `DataBaseHandler` class – DolDurma Aug 30 '14 at 08:09
  • You have to just use that context variable for this DatabaseHandler db = new DatabaseHandler(context); which you have globally declared in TSMS class – Piyush Aug 30 '14 at 08:11
  • my code is `DatabaseHandler db = new DatabaseHandler(context);` why i get `NULL` now? – DolDurma Aug 30 '14 at 08:16
  • have you changed ut TSMS class constructor same as my answer? – Piyush Aug 30 '14 at 08:19
  • Excuse me, i get this error now. `java.lang.IllegalStateException: getWritableDatabase called recursively` can i paste files to check it? – DolDurma Aug 30 '14 at 08:43
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/60284/discussion-between-tuxworld-and-pg-android). – DolDurma Aug 30 '14 at 08:43
  • Check these http://stackoverflow.com/questions/9547259/java-lang-illegalstateexceptiongetwritabledatabase-called-recursively,http://stackoverflow.com/questions/19889103/getdatabase-called-recursively-when-insert-a-record-in-ocreate-of-my-dbhelper-cl – Piyush Aug 30 '14 at 08:44
  • 1
    http://stackoverflow.com/questions/19889103/getdatabase-called-recursively-when-insert-a-record-in-ocreate-of-my-dbhelper-cl , http://stackoverflow.com/questions/9547259/java-lang-illegalstateexceptiongetwritabledatabase-called-recursively – Piyush Aug 30 '14 at 08:56
1

from your last question and from this question

As far my knowledge I think you still not sure about Context in android .

Some suggestions to solve your root problem:

1) In ReceiveFields() constructor you just use a context variable to solve the error like below..

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

And here you can use PG_Android's solution to fix the error but you still not solve your root problem if you will not pass the main context from your activity.

Just check your main activity from where you call/initialize the main class( I think TSMS) and pass the proper context the fix the main issue like:

 TSMS obj = new TSMS(your_current_activity.this);

here your your_current_activity.this will working as the main context in all your classes and databases.. i think you understand..

Community
  • 1
  • 1
Ranjit
  • 5,130
  • 3
  • 30
  • 66
  • 1
    after read PG_Android comment, post and change constructor i'm using `tsms = new TSMS(context,new User(this.username, this.password));` now but after running application for save into database i get `Null` error – DolDurma Aug 30 '14 at 08:03
  • For that just check some where you didn't get your value to insert in database. – Piyush Aug 30 '14 at 08:09
  • @TuxWorld In `TSMS(context,new User(this.username, this.password))` ..2nd parameter is fine..but you have to make sure the 1st parameter (i.e context) must holds the activity context..like I suggest in my answer..i.e `your_activity.this` – Ranjit Aug 30 '14 at 08:46
  • @RanjitPati i'm change it after see your comment – DolDurma Aug 30 '14 at 08:49