Android - Best way to sync SQLite with MySQL
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<JSONObject>() {
@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<Student> students = new ArrayList<Student>();
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);
}
The esieast way AFAIK is to use a lib like http://loopj.com/android-async-http/ or volley lije k0sh says to send data to a PHP script that will manage you mysql data. You'll have to write a php( or java) script in your server to receive your data ( You should write a REST API)
To select your HTTP lib, you should look here:
What is the most robust HTTP library for android?
You should really care about how you are going to sync your datas, because it could drain your battery. Here you will learn how to optimize your updates:
https://developer.android.com/training/efficient-downloads/index.html
Hope it helps!