我正在尝试实现数据库同步代码(来自programmer guru的教程),其中android应用程序中的数据通过函数syncMsgUpload()
同步到远程mysql服务器。我已经很好地实现了代码,但是当我运行代码时,我的应用程序崩溃了。请帮助我正确地获取代码。 android studio logcat出现以下错误:
08-22 23:15:32.243 13248-13248/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.skibzy.skibzydesigns.MessageActivity.syncMsgUpload(MessageActivity.java:214)
at com.skibzy.skibzydesigns.MessageActivity$2$1.onMenuItemClick(MessageActivity.java:138)
at android.widget.PopupMenu.onMenuItemSelected(PopupMenu.java:142)
at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:735)
at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:160)
at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:874)
at com.android.internal.view.menu.MenuPopupHelper.onItemClick(MenuPopupHelper.java:156)
at android.widget.AdapterView.performItemClick(AdapterView.java:298)
at android.widget.AbsListView.performItemClick(AbsListView.java:1139)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:2856)
at android.widget.AbsListView$1.run(AbsListView.java:3619)
at android.os.Handler.handleCallback(Handler.java:800)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5370)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
我的DBHelper和Activity文件如下:
DBHelper
public DBHelper(Context context)
{
super(context, DATABASE_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"create table " + MESSAGES_TABLE_NAME + "("
+ MESSAGES_COLUMN_ID + " integer primary key autoincrement, "
+ MESSAGES_USER_ID + " integer, "
+ MESSAGES_COLUMN_SUBJECT + " text, "
+ MESSAGES_COLUMN_CATEGORY + " text, "
+ MESSAGES_STATUS + " text, "
+ MESSAGES_SYNC_STATUS + " text, "
+ MESSAGES_WEB_ID + " text, "
+ MESSAGES_CREATED_AT + " text)"
);
db.execSQL(
"create table " + CONVERSATION_TABLE_NAME + "("
+ CONVERSATION_COLUMN_ID + " integer primary key autoincrement, "
+ CONVERSATION_COLUMN_MESSAGE_ID + " integer, "
+ CONVERSATION_COLUMN_MESSAGE + " text, "
+ CONVERSATION_COLUMN_TYPE + " text, "
+ CONVERSATION_STATUS + " text, "
+ CONVERSATION_SYNC_STATUS + " text, "
+ CONVERSATION_WEB_ID + " text, "
+ CONVERSATION_CREATED_AT + " text)"
);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + MESSAGES_TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS " + CONVERSATION_TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
public boolean createMessage (String user_id, String subject, String category, String status, String msg, String unique) {
SQLiteDatabase db = this.getWritableDatabase();
long time = System.currentTimeMillis()/1000L;
ContentValues contentValues = new ContentValues();
contentValues.put(MESSAGES_USER_ID, user_id);
contentValues.put(MESSAGES_COLUMN_SUBJECT, subject);
contentValues.put(MESSAGES_COLUMN_CATEGORY, category);
contentValues.put(MESSAGES_STATUS, status);
contentValues.put(MESSAGES_SYNC_STATUS, "no");
contentValues.put(MESSAGES_WEB_ID, unique);
contentValues.put(MESSAGES_CREATED_AT, time);
long id = db.insert(MESSAGES_TABLE_NAME, null, contentValues);
createConv(id, msg, "q", "1", unique);
return true;
}
public boolean createConv (long msg_id,String msg, String type, String status, String unique) {
SQLiteDatabase db = this.getWritableDatabase();
long time = System.currentTimeMillis()/1000L;
ContentValues contentValues = new ContentValues();
contentValues.put(CONVERSATION_COLUMN_MESSAGE_ID, msg_id);
contentValues.put(CONVERSATION_COLUMN_MESSAGE, msg);
contentValues.put(CONVERSATION_COLUMN_TYPE, type);
contentValues.put(CONVERSATION_STATUS, status);
contentValues.put(CONVERSATION_SYNC_STATUS, "no");
contentValues.put(CONVERSATION_WEB_ID, unique);
contentValues.put(CONVERSATION_CREATED_AT, time);
db.insert(CONVERSATION_TABLE_NAME, null, contentValues);
return true;
}
/*
public Cursor getData (int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "SELECT * FROM " + CONTACTS_TABLE_NAME + " WHERE " + CONTACTS_COLUMN_ID + " = " + id + "", null);
return res;
}
public int numberOfRows(){
SQLiteDatabase db = this.getReadableDatabase();
int numRows = (int) DatabaseUtils.queryNumEntries(db, CONTACTS_TABLE_NAME);
return numRows;
}
*/
public Cursor getConvDetail(int id, String column) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "SELECT " + column + " FROM " + MESSAGES_TABLE_NAME + " WHERE " + MESSAGES_COLUMN_ID + " = " + id + "", null);
return res;
}
public boolean updateMessage (Integer id, String user_id, String subject, String category, String status, String time, String msg)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(MESSAGES_USER_ID, user_id);
contentValues.put(MESSAGES_COLUMN_SUBJECT, subject);
contentValues.put(MESSAGES_COLUMN_CATEGORY, category);
contentValues.put(MESSAGES_STATUS, status);
contentValues.put(MESSAGES_CREATED_AT, time);
db.update(MESSAGES_TABLE_NAME, contentValues, MESSAGES_COLUMN_ID +" = ? ", new String[] { Integer.toString(id) } );
return true;
}
public boolean updateContact (Integer id, String name, String phone, String email, String street,String place)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("phone", phone);
contentValues.put("email", email);
contentValues.put("street", street);
contentValues.put("place", place);
db.update("contacts", contentValues, "id = ? ", new String[] { Integer.toString(id) } );
return true;
}
public Integer deleteContact (Integer id)
{
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("contacts",
"id = ? ",
new String[] { Integer.toString(id) });
}
public ArrayList<String> getAllMessages() {
ArrayList<String> array_list = new ArrayList<String>();
//hp = new HashMap();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "SELECT * FROM " + MESSAGES_TABLE_NAME + " ORDER BY " + MESSAGES_COLUMN_ID + " DESC", null);
res.moveToFirst();
while(res.isAfterLast() == false){
array_list.add(res.getString(res.getColumnIndex(MESSAGES_COLUMN_SUBJECT)));
res.moveToNext();
}
return array_list;
}
public ArrayList<String> getAllConversations(Integer msgId) {
ArrayList<String> array_list = new ArrayList<String>();
//hp = new HashMap();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "SELECT * FROM " + CONVERSATION_TABLE_NAME + " WHERE " + CONVERSATION_COLUMN_MESSAGE_ID + " = " + msgId + " ORDER BY " + CONVERSATION_COLUMN_ID + " ASC", null);
res.moveToFirst();
while(res.isAfterLast() == false){
array_list.add(res.getString(res.getColumnIndex(CONVERSATION_COLUMN_MESSAGE)));
res.moveToNext();
}
return array_list;
}
/**
* Get list of Messages from SQLite DB as Array List
* @return
*/
public ArrayList<HashMap<String, String>> getAllMessagesSync() {
ArrayList<HashMap<String, String>> msgWordList;
msgWordList = new ArrayList<HashMap<String, String>>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "SELECT * FROM " + MESSAGES_TABLE_NAME + " ORDER BY " + MESSAGES_COLUMN_ID + " DESC", null);
if (res.moveToFirst()) {
do {
HashMap<String, String> map = new HashMap<String, String>();
map.put("id", res.getString(0));
map.put("subject", res.getString(1));
map.put("category", res.getString(2));
map.put("status", res.getString(3));
map.put("web_id", res.getString(5));
map.put("created", res.getString(6));
msgWordList.add(map);
} while (res.moveToNext());
}
db.close();
return msgWordList;
}
/**
* Get list of Users from SQLite DB as Array List
* @return
*/
public ArrayList<HashMap<String, String>> getAllConversationsSync(Integer msgId) {
ArrayList<HashMap<String, String>> convWordList;
convWordList = new ArrayList<HashMap<String, String>>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "SELECT * FROM " + CONVERSATION_TABLE_NAME + " WHERE " + CONVERSATION_COLUMN_MESSAGE_ID + " = " + msgId + " ORDER BY " + CONVERSATION_COLUMN_ID + " ASC", null);
if (res.moveToFirst()) {
do {
HashMap<String, String> map = new HashMap<String, String>();
map.put("id", res.getString(0));
map.put("msg_id", res.getString(1));
map.put("message", res.getString(2));
map.put("type", res.getString(3));
map.put("status", res.getString(4));
map.put("web_id", res.getString(6));
map.put("created", res.getString(7));
convWordList.add(map);
} while (res.moveToNext());
}
db.close();
return convWordList;
}
/**
* Compose JSON out of SQLite records
* @return
}
*/
public String msgComposeJSONphone(){
ArrayList<HashMap<String, String>> wordList;
wordList = new ArrayList<HashMap<String, String>>();
SQLiteDatabase db = this.getReadableDatabase();
String search = "no";
Cursor res = db.rawQuery( "SELECT * FROM " + MESSAGES_TABLE_NAME + " WHERE " + MESSAGES_SYNC_STATUS + " = " + search + "", null);
if (res.moveToFirst()) {
do {
HashMap<String, String> map = new HashMap<String, String>();
map.put("id", res.getString(0));
map.put("subject", res.getString(1));
map.put("category", res.getString(2));
map.put("status", res.getString(3));
map.put("web_id", res.getString(5));
map.put("created", res.getString(6));
wordList.add(map);
} while (res.moveToNext());
}
db.close();
Gson gson = new GsonBuilder().create();
//Use GSON to serialize Array List to JSON
return gson.toJson(wordList);
}
public String convComposeJSONphone(){
ArrayList<HashMap<String, String>> wordList;
wordList = new ArrayList<HashMap<String, String>>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "SELECT * FROM " + CONVERSATION_TABLE_NAME + " WHERE " + CONVERSATION_SYNC_STATUS
+ " = no", null);
if (res.moveToFirst()) {
do {
HashMap<String, String> map = new HashMap<String, String>();
map.put("id", res.getString(0));
map.put("msg_id", res.getString(1));
map.put("message", res.getString(2));
map.put("type", res.getString(3));
map.put("status", res.getString(4));
map.put("web_id", res.getString(6));
map.put("created", res.getString(7));
wordList.add(map);
} while (res.moveToNext());
}
db.close();
Gson gson = new GsonBuilder().create();
//Use GSON to serialize Array List to JSON
return gson.toJson(wordList);
}
/**
* Get Sync status of SQLite
* @return
*/
public String getMsgSyncStatus(){
String msg = null;
if(this.dbMsgSyncCount() == 0){
msg = "SQLite and Remote MySQL DBs are in Sync!";
}else{
msg = "Message Sync needed\n";
}
return msg;
}
public String getConvSyncStatus(){
String msg = null;
if(this.dbConvSyncCount() == 0){
msg = "SQLite and Remote MySQL DBs are in Sync!";
}else{
msg = "Conversations Sync needed\n";
}
return msg;
}
/**
* Get SQLite records that are yet to be Synced
* @return
*/
public int dbMsgSyncCount(){
int count = 0;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery( "SELECT * FROM " + MESSAGES_TABLE_NAME + " WHERE " + MESSAGES_SYNC_STATUS
+ " = '"+"no"+"'", null);
count = cursor.getCount();
db.close();
return count;
}
public int dbConvSyncCount(){
int count = 0;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery( "SELECT * FROM " + CONVERSATION_TABLE_NAME + " WHERE " + CONVERSATION_SYNC_STATUS
+ " = no", null);
count = cursor.getCount();
db.close();
return count;
}
/**
* Update Sync status against each User ID
* @param id
* @param status
*/
public void updateMsgSyncStatus(String id, String status){
SQLiteDatabase database = this.getWritableDatabase();
String updateQuery = "Update " + MESSAGES_TABLE_NAME + " set " + MESSAGES_SYNC_STATUS + " = '" + status +"' where " + MESSAGES_COLUMN_ID + " = '"+ id +"'";
Log.d("query", updateQuery);
database.execSQL(updateQuery);
database.close();
}
public void updateConvSyncStatus(String id, String status){
SQLiteDatabase database = this.getWritableDatabase();
String updateQuery = "Update " + CONVERSATION_TABLE_NAME + " set " + CONVERSATION_SYNC_STATUS + " = '" + status +"' where " + CONVERSATION_COLUMN_ID + " = '"+ id +"'";
Log.d("query", updateQuery);
database.execSQL(updateQuery);
database.close();
}
活动代码
public class MessageActivity extends ActionBarActivity implements ISideNavigationCallback {
//Utils Class
Utils util;
final Context context = this;
//TOOLBAR
private Toolbar toolbar;
//CONSTANT BUTTONS
private ImageButton btnCall;
private ImageButton btnMessage;
private ImageButton btnLocate;
//Side Menu
private ButtonAwesome menuBtn;
private SideNavigationView sideNavigationView;
private ListView obj;
DBHelper mydb;
//Progress Dialog Object
ProgressDialog prgDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message);
util = new Utils(this);
TextView appTit = (TextView) findViewById(R.id.appTitle);
String pageTitle = "My Messages";
appTit.setText((CharSequence)pageTitle);
sideNavigationView = (SideNavigationView) findViewById(R.id.side_navigation_view);
sideNavigationView.setMenuItems(R.menu.menu_main);
sideNavigationView.setMenuClickCallback(this);
sideNavigationView.setMode(SideNavigationView.Mode.LEFT);
mydb = new DBHelper(this);
ArrayList array_list = mydb.getAllMessages();
ArrayAdapter arrayAdapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1, array_list);
obj = (ListView)findViewById(R.id.list);
obj.setAdapter(arrayAdapter);
obj.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
int id_To_Search = arg0.getCount() - arg2;
String sbj = "subject";
String uniqueCode = "web_id";
Cursor theSbj = mydb.getConvDetail(id_To_Search, sbj);
Cursor theCode = mydb.getConvDetail(id_To_Search, uniqueCode);
theSbj.moveToFirst();
theCode.moveToFirst();
String subject = theSbj.getString(theSbj.getColumnIndex(DBHelper.MESSAGES_COLUMN_SUBJECT));
String unique = theCode.getString(theCode.getColumnIndex(DBHelper.MESSAGES_WEB_ID));
Bundle dataBundle = new Bundle();
dataBundle.putInt("id", id_To_Search);
dataBundle.putString("msgSubject", subject);
dataBundle.putString("unique", unique);
Intent intent = new Intent(getApplicationContext(), ViewMessage.class);
intent.putExtras(dataBundle);
startActivity(intent);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
util.menuSwitch(item.getItemId());
return true;
}
public void syncMsgUpload(){
//Create AsycHttpClient object
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
ArrayList<HashMap<String, String>> userList = mydb.getAllMessagesSync();
if(userList.size()!=0){
if(mydb.dbMsgSyncCount() != 0){
prgDialog.show();
params.put("msgJSON", mydb.msgComposeJSONphone());
client.post("http://192.168.43.87/custserv/app/message/create_msg.php",params ,new AsyncHttpResponseHandler() {
@Override
public void onSuccess(String response) {
System.out.println(response);
prgDialog.hide();
try {
JSONArray arr = new JSONArray(response);
System.out.println(arr.length());
for(int i=0; i<arr.length();i++){
JSONObject obj = (JSONObject)arr.get(i);
System.out.println(obj.get("id"));
System.out.println(obj.get("status"));
mydb.updateMsgSyncStatus(obj.get("id").toString(),obj.get("status").toString());
}
Toast.makeText(getApplicationContext(), "DB Sync completed!", Toast.LENGTH_LONG).show();
} catch (JSONException e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(), "Error Occured [Server's JSON response might be invalid]!", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
@Override
public void onFailure(int statusCode, Throwable error,
String content) {
// TODO Auto-generated method stub
prgDialog.hide();
if(statusCode == 404){
Toast.makeText(getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show();
}else if(statusCode == 500){
Toast.makeText(getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet]", Toast.LENGTH_LONG).show();
}
}
});
}else{
Toast.makeText(getApplicationContext(), "SQLite and Remote MySQL DBs are in Sync!", Toast.LENGTH_LONG).show();
}
}else{
Toast.makeText(getApplicationContext(), "Messages", Toast.LENGTH_LONG).show();
}
}
public void syncConvUpload(){
//Create AsycHttpClient object
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
ArrayList<HashMap<String, String>> userList = mydb.getAllMessagesSync();
if(userList.size()!=0){
if(mydb.dbConvSyncCount() != 0){
prgDialog.show();
params.put("convJSON", mydb.convComposeJSONphone());
client.post("http://192.168.43.87/custserv/app/message/create_conv.php",params ,new AsyncHttpResponseHandler() {
@Override
public void onSuccess(String response) {
System.out.println(response);
prgDialog.hide();
try {
JSONArray arr = new JSONArray(response);
System.out.println(arr.length());
for(int i=0; i<arr.length();i++){
JSONObject obj = (JSONObject)arr.get(i);
System.out.println(obj.get("id"));
System.out.println(obj.get("status"));
mydb.updateSyncStatus(obj.get("id").toString(),obj.get("status").toString());
}
Toast.makeText(getApplicationContext(), "DB Sync completed!", Toast.LENGTH_LONG).show();
} catch (JSONException e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(), "Error Occured [Server's JSON response might be invalid]!", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
@Override
public void onFailure(int statusCode, Throwable error,
String content) {
// TODO Auto-generated method stub
prgDialog.hide();
if(statusCode == 404){
Toast.makeText(getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show();
}else if(statusCode == 500){
Toast.makeText(getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet]", Toast.LENGTH_LONG).show();
}
}
});
}else{
Toast.makeText(getApplicationContext(), "SQLite and Remote MySQL DBs are in Sync!", Toast.LENGTH_LONG).show();
}
}else{
Toast.makeText(getApplicationContext(), "No data in SQLite DB, please do enter User name to perform Sync action", Toast.LENGTH_LONG).show();
}
}
}