android与mysql数据库同步_Android-将SQLite与MySQL同步的最佳方法

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 19:15   843   0

bd96500e110b49cbb3cd949968f18be7.png

I'm working on a project containing web app and mobile app which records daily user's data. User are able to delete, update their data and they can use many devices to insert data.

I intend to develop this way:

User enter their data and then insert to SQLite. A service will start periodically (each 5hr or sth) to sync with MySQL using timestamp.

I did search for a sample using service and timestamp on the internet but I found nothing. It would be great if there are a sample or tutorial.

I'm new at Android and I have no idea what is the best way to develop an app like this. Thanks in advance.

----EDIT----

I consider using timestamp or synced. Which is more effective?

解决方案

you could use volley library by google or any alternative libraries, it depends on how you want to send the data, the best approach is that you use JSON to make your life easier, get the data from sqlite that you like to sync with your backend and send it over JsonObjectRequest using volley, for example your request can look like this

jsonObjectRequest postForm = new JsonObjectRequest(Request.Method.POST, URL, YourJsonData, new Response.Listener() {

@Override

public void onResponse(JSONObject response) {

// here you can get your response.

},new Response.ErrorListener() {

@Override

public void onErrorResponse(VolleyError error) {

// here you can tell there is something went wrong.

});

u could add a new value which indicates whether the value has been sync or no from your local database. for example, lets say you have a table called student and this table has three columns which are ID, NAME and synced in above code when your response return success update that row synced column with true|false which indicates whether this row synced with your backend or no. and to get the data from your database you should do something like this.

public String getStudents() {

List students = new ArrayList();

String query = "SELECT * FROM " + STUDENT+ "where synced=0";

SQLiteDatabase db = this.getWritableDatabase();

Cursor cursor = db.rawQuery(query, null);

if (cursor.moveToFirst()) {

do {

Student st = new Student();

st.setId(cursor.getString(cursor.getColumnIndex(ID)));

st.setName(cursor.getString(cursor.getColumnIndex(NAME)));

st.setSynced(cursor.getInt(cursor.getColumnIndex(SYNCED)));

students.add(st);

} while (cursor.moveToNext());

}

db.close();

return new Gson().toJson(students);

}

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP