I want to write some SQL to a database, however when executing it I get a nullpointer error. I think I do something wrong with passing the Context from WhatsApi.java
to MessageService.java
. (See the Context.MODE_PRIVATE
)
This part from MessageService.java
db = openOrCreateDatabase("msgstore", Context.MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS messages(`from` TEXT, `to` TEXT, message TEXT, id TEXT, t TEXT);");
This in WhatsApi.java
MessageService msg = new MessageService();
msg.saveMessage(mContext, "mynumber", to, message, id, time());
I suggest you guys to see this link too:
https://github.com/gi097/WhatsApi-Android/commit/3875d97458095f792c73f275648629aaaf726751
Any help is appreciated. Sorry for the maybe unclear look, but I hope you guys understand.
Well I use this in one of my Projects DatabaseHandler dbHandler=null;//Database handler class//global var SQLiteDatabase contactDatabase=null;// globalvar . . //some function{ if(dbHandler==null) dbHandler = new DatabaseHandler(this);//service context if(contactDatabase==null) contactDatabase=dbHandler.getWritableDatabase(); ArrayList<information>list= new ArrayList<information>(); String selectQuery = "SELECT * FROM " + DatabaseHandler.TABLE_CONTACTS; Cursor cursor = contactDatabase.rawQuery(selectQuery, null);
DatabaseHandler dbHandler=null;//Database handler class//global var SQLiteDatabase contactDatabase=null;// globalvar . . //some function{ if(dbHandler==null) dbHandler = new DatabaseHandler(this);//service context if(contactDatabase==null) contactDatabase=dbHandler.getWritableDatabase(); ArrayList<information>list= new ArrayList<information>(); String selectQuery = "SELECT * FROM " + DatabaseHandler.TABLE_CONTACTS; Cursor cursor = contactDatabase.rawQuery(selectQuery, null);
You should never instantiate an Activity
or Service
yourself with the new
keyword. It is Android's responsibility to start these components because Android needs to also do some additional setup, including provide a base Context
for these components. That is why you get a NullPointerException
in your service class. You have to actually use startService()
to make the service run properly.
In my opinion, since WhatsApi
already has a Context, I don't see any reason you need to bother having the service save the data. Just open the database and save the data in WhatsApi
.
By the way, since you're using SQLite, you really should be using SQLiteOpenHelper
instead of calling methods like openOrCreateDatabase()
directly. See this guide for more information.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.