我希望在移动设备不在覆盖区域时存储一些数据。当服务回来时,它将在服务器上传数据。但数据没有插入。我在网上查了很多tutorail。但一直都是这样。 app appexpecatelyly。
LogCat错误
10-12 12:08:54.754: E/Service Example(1374): Service Started..
10-12 12:08:54.814: E/AndroidRuntime(1374): FATAL EXCEPTION: main
10-12 12:08:54.814: E/AndroidRuntime(1374): java.lang.RuntimeException: Unable create service com.remote.synchronizer.haris.OfflineDataService: java.lang.NullPointerException
10-12 12:08:54.814: E/AndroidRuntime(1374): at android.app.ActivityThread.handleCreateService(ActivityThread.java:1955)
10-12 12:08:54.814: E/AndroidRuntime(1374): at android.app.ActivityThread.access$2500(ActivityThread.java:117)
10-12 12:08:54.814: E/AndroidRuntime(1374): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:985)
10-12 12:08:54.814: E/AndroidRuntime(1374): at android.os.Handler.dispatchMessage(Handler.java:99)
10-12 12:08:54.814: E/AndroidRuntime(1374): at android.os.Looper.loop(Looper.java:123)
10-12 12:08:54.814: E/AndroidRuntime(1374): at android.app.ActivityThread.main(ActivityThread.java:3683)
10-12 12:08:54.814: E/AndroidRuntime(1374): at java.lang.reflect.Method.invokeNative(Native Method)
10-12 12:08:54.814: E/AndroidRuntime(1374): at java.lang.reflect.Method.invoke(Method.java:507)
10-12 12:08:54.814: E/AndroidRuntime(1374): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
10-12 12:08:54.814: E/AndroidRuntime(1374): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
10-12 12:08:54.814: E/AndroidRuntime(1374): at dalvik.system.NativeStart.main(Native Method)
10-12 12:08:54.814: E/AndroidRuntime(1374): Caused by: java.lang.NullPointerException
10-12 12:08:54.814: E/AndroidRuntime(1374): at com.remote.synchronizer.haris.SQLiteAdapter.Write(SQLiteAdapter.java:59)
10-12 12:08:54.814: E/AndroidRuntime(1374): at com.remote.synchronizer.haris.OfflineDataService.onCreate(OfflineDataService.java:37)
10-12 12:08:54.814: E/AndroidRuntime(1374): at android.app.ActivityThread.handleCreateService(ActivityThread.java:1945)
10-12 12:08:54.814: E/AndroidRuntime(1374): ... 10 more
SQLiteAdapter
package com.remote.synchronizer.haris;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class SQLiteAdapter extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Product";
public static final String TABLE_NAME = "Order";
public static final int DATABASE_VERSION = 1;
public static final String KEY_ID = "_id";
public static final String KEY_NAME = "name";
public static final String KEY_SHOP = "shop";
private static final String KEY_CITY = "city";
private static final String KEY_DATE = "date";
private static final String KEY_ORDER = "order";
private static final String CREATE_TABLE =
"CREATE TABLE " + TABLE_NAME + " ("
+ KEY_ID + " integer primary key autoincrement, "
+ KEY_NAME + " VARCHAR,"
+ KEY_SHOP + " VARCHAR," + KEY_CITY + " VARCHAR, " + KEY_DATE + " VARCHAR, " + KEY_ORDER + " VARCHAR " + ");";
public SQLiteAdapter(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
private SQLiteDatabase sqLiteDatabase;
private SQLiteAdapter sqLiteHelper;
/*private Context context;
public SQLiteAdapter(Context c){
context = c;
}
*/
public void Read() throws android.database.SQLException {
sqLiteDatabase = sqLiteHelper.getReadableDatabase();
}
public void Write() throws android.database.SQLException {
sqLiteDatabase = sqLiteHelper.getWritableDatabase();
}
public void close(){
sqLiteHelper.close();
}
public long insert(String name, String shop, String city, String date, String order){
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_NAME, name);
contentValues.put(KEY_SHOP, shop);
contentValues.put(KEY_SHOP, city);
contentValues.put(KEY_DATE, date);
contentValues.put(KEY_ORDER, order);
return sqLiteDatabase.insert(TABLE_NAME, null, contentValues);
}
public int deleteAll(){
return sqLiteDatabase.delete(TABLE_NAME, null, null);
}
/*public void delete_byID(int id){
sqLiteDatabase.delete(TABLE_NAME, KEY_ID+"="+id, null);
}
public Cursor queueAll(){
String[] columns = new String[]{KEY_ID, KEY_NAME, KEY_SHOP, KEY_CITY, KEY_DATE, KEY_ORDER};
Cursor cursor = sqLiteDatabase.query(TABLE_NAME, columns,
null, null, null, null, null);
return cursor;
}*/
public List<NameValuePair> getAllContacts() {
List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
String selectQuery = "SELECT * FROM " + TABLE_NAME;
Read();
Cursor cursor = sqLiteDatabase.rawQuery(selectQuery, null);
if(cursor.moveToFirst()){
while(!cursor.isAfterLast())
{
postParameters.add(new BasicNameValuePair("User", cursor.getString(cursor.getColumnIndex(KEY_NAME))));
postParameters.add(new BasicNameValuePair("ShopName", cursor.getString(cursor.getColumnIndex(KEY_SHOP))));
postParameters.add(new BasicNameValuePair("city", cursor.getString(cursor.getColumnIndex(KEY_CITY))));
postParameters.add(new BasicNameValuePair("OrderDate", cursor.getString(cursor.getColumnIndex(KEY_DATE))));
postParameters.add(new BasicNameValuePair("OrderDetail", cursor.getString(cursor.getColumnIndex(KEY_ORDER))));
cursor.moveToNext();
}
}
cursor.close();
return postParameters;
};
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(SQLiteAdapter.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + CREATE_TABLE);
onCreate(db);
}
}
OfflineDataService.java
package com.remote.synchronizer.haris;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import org.apache.http.NameValuePair;
import android.app.IntentService;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
public class OfflineDataService extends IntentService {
boolean wifi,edge;
private Timer timer= new Timer();
SQLiteDatabase db;
String un,shop,city,date,order;
private SQLiteAdapter mySQLiteAdapter;
Cursor cursor;
public OfflineDataService() {
super("OfflineDataService");
}
@Override
public void onCreate() {
super.onCreate();
Log.e("Service Example", "Service Started.. ");
mySQLiteAdapter = new SQLiteAdapter(this);
mySQLiteAdapter.Write();
}
@Override
protected void onHandleIntent(Intent intent) {
Bundle bundle=intent.getExtras();
un=bundle.getString("un");
shop=bundle.getString("shop");
city=bundle.getString("city");
date=bundle.getString("date");
order=bundle.getString("order");
Log.e("Service Started", "Successful");
//Inserting New Record
mySQLiteAdapter.insert(un,shop,city,date,order);
timer.scheduleAtFixedRate(new TimerTask(){
@Override
public void run() {
//Checking network connectivity
wifi=NetworkInfo.Wifi(OfflineDataService.this);
edge=NetworkInfo.EDGE(OfflineDataService.this);
if(wifi==true||edge==true)
{
DataSender();
}
else
{
//Toast toast=Toast.makeText(getApplicationContext(), "Testing", toast.LENGTH_LONG).show();
}
}
}, 1000, 5000);
}
/*@Override
public void onDestroy() {
super.onDestroy();
Log.e("Service Example", "Service Destroyed.. ");
mySQLiteAdapter.deleteAll();
}*/
private void DataSender()
{
timer.cancel();
List<NameValuePair> contacts=new ArrayList<NameValuePair>();
contacts=mySQLiteAdapter.getAllContacts();
String url="http://10.0.2.2:3325/Product/Create?";
int response = 0;
try
{
response = CustomHttpClient.executeHttpPost(url, contacts);
if(response==200)
{
//notification
}
else{}
//error.setText("Sorry!! Try again later.\n Response Code: "+ response);
}
catch (Exception e)
{
e.printStackTrace();
// error.setText(e.toString());
}
}
}
我的代码出了什么问题?
log cat中的新错误
10-12 14:57:00.424: E/Service Example(1494): Service Started..
10-12 14:57:00.664: E/Database(1494): Failure 1 (near "Order": syntax error) on 0x5b7638 when preparing 'CREATE TABLE Order (_id integer primary key autoincrement, name VARCHAR,shop VARCHAR,city VARCHAR, date VARCHAR, order VARCHAR );'.
10-12 14:57:00.764: E/AndroidRuntime(1494): FATAL EXCEPTION: main
10-12 14:57:00.764: E/AndroidRuntime(1494): java.lang.RuntimeException: Unable to create service com.remote.synchronizer.haris.OfflineDataService: android.database.sqlite.SQLiteException: near "Order": syntax error: CREATE TABLE Order (_id integer primary key autoincrement, name VARCHAR,shop VARCHAR,city VARCHAR, date VARCHAR, order VARCHAR );
10-12 14:57:00.764: E/AndroidRuntime(1494): at android.app.ActivityThread.handleCreateService(ActivityThread.java:1955)
10-12 14:57:00.764: E/AndroidRuntime(1494): at android.app.ActivityThread.access$2500(ActivityThread.java:117)
10-12 14:57:00.764: E/AndroidRuntime(1494): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:985)
10-12 14:57:00.764: E/AndroidRuntime(1494): at android.os.Handler.dispatchMessage(Handler.java:99)
10-12 14:57:00.764: E/AndroidRuntime(1494): at android.os.Looper.loop(Looper.java:123)
10-12 14:57:00.764: E/AndroidRuntime(1494): at android.app.ActivityThread.main(ActivityThread.java:3683)
10-12 14:57:00.764: E/AndroidRuntime(1494): at java.lang.reflect.Method.invokeNative(Native Method)
10-12 14:57:00.764: E/AndroidRuntime(1494): at java.lang.reflect.Method.invoke(Method.java:507)
10-12 14:57:00.764: E/AndroidRuntime(1494): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
10-12 14:57:00.764: E/AndroidRuntime(1494): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
10-12 14:57:00.764: E/AndroidRuntime(1494): at dalvik.system.NativeStart.main(Native Method)
10-12 14:57:00.764: E/AndroidRuntime(1494): Caused by: android.database.sqlite.SQLiteException: near "Order": syntax error: CREATE TABLE Order (_id integer primary key autoincrement, name VARCHAR,shop VARCHAR,city VARCHAR, date VARCHAR, order VARCHAR );
10-12 14:57:00.764: E/AndroidRuntime(1494): at android.database.sqlite.SQLiteDatabase.native_execSQL(Native Method)
10-12 14:57:00.764: E/AndroidRuntime(1494): at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1763)
10-12 14:57:00.764: E/AndroidRuntime(1494): at com.remote.synchronizer.haris.SQLiteAdapter.onCreate(SQLiteAdapter.java:42)
10-12 14:57:00.764: E/AndroidRuntime(1494): at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:126)
10-12 14:57:00.764: E/AndroidRuntime(1494): at com.remote.synchronizer.haris.SQLiteAdapter.Write(SQLiteAdapter.java:59)
10-12 14:57:00.764: E/AndroidRuntime(1494): at com.remote.synchronizer.haris.OfflineDataService.onCreate(OfflineDataService.java:37)
10-12 14:57:00.764: E/AndroidRuntime(1494): at android.app.ActivityThread.handleCreateService(ActivityThread.java:1945)
10-12 14:57:00.764: E/AndroidRuntime(1494): ... 10 more
答案 0 :(得分:0)
您定义了sqLiteHelper
但从未对其进行初始化。这意味着当运行下面的这一行(在Write()
方法中)时,它会导致logcat中显示NullPointerException
。
sqLiteDatabase = sqLiteHelper.getWritableDatabase();
将其更改为...
sqLiteDatabase = this.getWritableDatabase();
..或确保sqLiteHelper
在使用前初始化。
注意:除非您初始化Read()
或我们sqLiteHelper
,否则this
方法会以相同的方式失败。
答案 1 :(得分:0)
尝试在您的Write()和Read()方法中使用
sqLiteDatabase = this.getWritableDatabase();
而不是
sqLiteDatabase = sqLiteHelper.getWritableDatabase();
或像这样初始化sqLiteHelper
sqLiteHelper = this;
答案 2 :(得分:0)
创建一个seprate函数并尝试这个,你只需要定义一个私有静态SQLiteDatabase db 来删除错误。
<强> DBhelper.java 强>
package com.example.mitul.jsontosqlite.sampledata;
import android.content.Context;
import android.content.res.Resources;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.content.ContentValues;
import android.widget.Toast;
import com.example.mitul.jsontosqlite.MainActivity;
import com.example.mitul.jsontosqlite.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class DBhelper extends SQLiteOpenHelper {
private static final String TAG = DBhelper.class.getSimpleName();
SQLiteOpenHelper sqLiteOpenHelper;
private Resources mResources;
private static final String DATABASE_NAME = "menu.db";
private static final int DATABASE_VERSION = 1;
Context context;
private static SQLiteDatabase db;
public DBhelper(Context context){
super(context,DATABASE_NAME,null,DATABASE_VERSION);
mResources = context.getResources();
db = this.getWritableDatabase();
}
@Override
public void onCreate(SQLiteDatabase db) {
final String SQL_CREATE_BUGS_TABLE = "CREATE TABLE " + Dbcontract.MenuEntry.TABLE_NAME + " (" +
Dbcontract.MenuEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
Dbcontract.MenuEntry.COLUMN_NAME + " TEXT UNIQUE NOT NULL, " +
Dbcontract.MenuEntry.COLUMN_DESCRIPTION + " TEXT NOT NULL, " +
Dbcontract.MenuEntry.COLUMN_PRICE + " TEXT NOT NULL, " +
Dbcontract.MenuEntry.COLUMN_CATEGORY + " TEXT NOT NULL, " +
Dbcontract.MenuEntry.COLUMN_PHOTO + " INTEGER NOT NULL " + " );";
db.execSQL(SQL_CREATE_BUGS_TABLE);
Log.d(TAG, "Database Created Successfully" );
try {
readDataToDb(db);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
private void readDataToDb(SQLiteDatabase db) throws IOException, JSONException {
final String MNU_NAME = "name";
final String MNU_DESCRIPTION = "description";
final String MNU_PRICE = "price";
final String MNU_CATEGORY = "category";
final String MNU_PHOTO = "photo";
try {
String jsonDataString = readJsonDataFromFile();
JSONArray menuItemsJsonArray = new JSONArray(jsonDataString);
for (int i = 0; i < menuItemsJsonArray.length(); ++i) {
String name;
String description;
String price;
String category;
String photo;
JSONObject menuItemObject = menuItemsJsonArray.getJSONObject(i);
name = menuItemObject.getString(MNU_NAME);
description = menuItemObject.getString(MNU_DESCRIPTION);
price = menuItemObject.getString(MNU_PRICE);
category = menuItemObject.getString(MNU_CATEGORY);
photo = menuItemObject.getString(MNU_PHOTO);
ContentValues menuValues = new ContentValues();
menuValues.put(Dbcontract.MenuEntry.COLUMN_NAME, name);
menuValues.put(Dbcontract.MenuEntry.COLUMN_DESCRIPTION, description);
menuValues.put(Dbcontract.MenuEntry.COLUMN_PRICE, price);
menuValues.put(Dbcontract.MenuEntry.COLUMN_CATEGORY, category);
menuValues.put(Dbcontract.MenuEntry.COLUMN_PHOTO, photo);
db.insert(Dbcontract.MenuEntry.TABLE_NAME, null, menuValues);
Log.d(TAG, "Inserted Successfully " + menuValues );
}
} catch (JSONException e) {
Log.e(TAG, e.getMessage(), e);
e.printStackTrace();
}
}
private String readJsonDataFromFile() throws IOException {
InputStream inputStream = null;
StringBuilder builder = new StringBuilder();
try {
String jsonDataString = null;
inputStream = mResources.openRawResource(R.raw.menu_item);
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputStream, "UTF-8"));
while ((jsonDataString = bufferedReader.readLine()) != null) {
builder.append(jsonDataString);
}
} finally {
if (inputStream != null) {
inputStream.close();
}
}
return new String(builder);
}
}
<强> Dbcontract.java 强>
package com.example.mitul.jsontosqlite.sampledata;
import android.provider.BaseColumns;
public class Dbcontract {
public static final class MenuEntry implements BaseColumns{
public static final String TABLE_NAME ="menu";
public static final String COLUMN_NAME ="name";
public static final String COLUMN_DESCRIPTION ="description";
public static final String COLUMN_PRICE ="price";
public static final String COLUMN_CATEGORY ="category";
public static final String COLUMN_PHOTO ="photo";
}
}
答案 3 :(得分:0)
您必须像这样从DataHelper创建一个新对象:
DatabaseHelper helper = new DataHelper(this);//write this in your MainActivity class