请,我想将我的短信存储到sqlite数据库中。我已经完成了关注,但我的应用程序崩溃了。
@Override
public void onReceive(Context context, Intent intent){
if(intent.getAction().equals(SMS_RECEIVED)){
Bundle bundle = intent.getExtras();
Object[] messages = (Object[]) bundle.get("pdus");
SmsMessage[] sms = new SmsMessage[messages.length];
for (int j=0; j < messages.length; j++) {
sms[j] = SmsMessage.createFromPdu((byte[]) messages[j]);
}
for (SmsMessage msg : sms) {
body = msg.getMessageBody();
DateFormat dateFormatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
dateFormatter.setLenient(false);
Date today = new Date();
String datemess = dateFormatter.format(today);
String sql = "INSERT INTO table_message (DATEMESSAGE, CONTENU) VALUES("+datemess+" , "+ body+")" ;
db.execSQL(sql);
}
}
}
logcat的:
E/AndroidRuntime(255): Uncaught handler: thread main exiting due to uncaught exception E/AndroidRuntime(255): java.lang.RuntimeException: Unable to start receiver com.exo22.SMSReceiver: java.lang.NullPointerException E/AndroidRuntime(255): at android.app.ActivityThread.handleReceiver(ActivityThread.java:2646) E/AndroidRuntime(255): at android.app.ActivityThread.access$3100(ActivityThread.java:119) E/AndroidRuntime(255): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1913) E/AndroidRuntime(255): at android.os.Handler.dispatchMessage(Handler.java:99) E/AndroidRuntime(255): at android.os.Looper.loop(Looper.java:123) E/AndroidRuntime(255): at android.app.ActivityThread.main(ActivityThread.java:4363) E/AndroidRuntime(255): at java.lang.reflect.Method.invokeNative(Native Method) E/AndroidRuntime(255): at java.lang.reflect.Method.invoke(Method.java:521) E/AndroidRuntime(255): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860) E/AndroidRuntime(255): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618) E/AndroidRuntime(255): at dalvik.system.NativeStart.main(Native Method) E/AndroidRuntime(255): Caused by: java.lang.NullPointerException E/AndroidRuntime(255): at com.exo22.SMSReceiver.onReceive(SMSReceiver.java:45) E/AndroidRuntime(255): at android.app.ActivityThread.handleReceiver(ActivityThread.java:2637) E/AndroidRuntime(255): ... 10 more
答案 0 :(得分:0)
在SQL命令中,必须引用字符串。
但是,为避免格式化此类问题或SQL注入攻击,请使用参数:
db.execSQL("INSERT INTO table_message (DATEMESSAGE, CONTENU) VALUES(?,?)",
new Object[] { datemess, body });