I'm using Volley to load the JSON string to the SQLite, but I faced with problem that Volley fill the SQLite fields randomly, one time one field is with JSON in the second time the same field is empty.
I'm thinking about implementing progress dialog, maybe UI thread can stop Volley, but I'm not sure...
My method:
private void loadJsonToSQLite() {
RequestQueue queue = Volley.newRequestQueue(this);
mDB = this.openOrCreateDatabase(Constants.DATABASE_NAME, MODE_PRIVATE, null);
for (int i = 0; i < routeArray.length; i++) {
if (!mDB.isOpen()) {
mDB = getApplicationContext().openOrCreateDatabase(Constants.DATABASE_NAME, MODE_PRIVATE, null);
}
final String urlPart = routeArray[i];
final String urlPartReverse = routeArrayReverse[i];
final String tableName = "[" + urlPart + "]";
mDB.execSQL("CREATE TABLE " + tableName + " (keyId INTEGER PRIMARY KEY, route TEXT, routeReverse TEXT)");
StringRequest stringRequest = new StringRequest(Request.Method.GET, url + urlPart,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Matcher m = MY_PATTERN.matcher(response);
if (m.find()) {
String extracted = m.group(1).trim();
ContentValues initialValues = new ContentValues();
initialValues.put("keyId", 1);
initialValues.put("route", extracted);
if (!mDB.isOpen()) {
mDB = getApplicationContext().openOrCreateDatabase(Constants.DATABASE_NAME, MODE_PRIVATE, null);
}
mDB.insert(tableName, null, initialValues);
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
queue.add(stringRequest);
mDB.close();
StringRequest stringRequestReverse = new StringRequest(Request.Method.GET, url + urlPartReverse,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Matcher m = MY_PATTERN.matcher(response);
if (m.find()) {
String extracted = m.group(1).trim();
ContentValues initialValues = new ContentValues();
initialValues.put("routeReverse", extracted);
if (!mDB.isOpen()) {
mDB = getApplicationContext().openOrCreateDatabase(Constants.DATABASE_NAME, MODE_PRIVATE, null);
}
mDB.update(tableName,initialValues,null,null);
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
queue.add(stringRequestReverse);
mDB.close();
}
}
Maybe I'm wrong somewhere with Volley?
I have JSON strings in different links-ending, because of that I'm using loop.
Aucun commentaire:
Enregistrer un commentaire