Foros del Web » Programando para Internet » Android »

[SOLUCIONADO] Problema con la sincronizacion de Sqlite con Mysql

Estas en el tema de Problema con la sincronizacion de Sqlite con Mysql en el foro de Android en Foros del Web. Tengo el problema que no me guadar en la tabla si lo recibo pero me da error , en el momento de transformarlo a Json ...
  #1 (permalink)  
Antiguo 14/04/2015, 08:10
Avatar de Maverick2786  
Fecha de Ingreso: diciembre-2012
Mensajes: 107
Antigüedad: 11 años, 3 meses
Puntos: 1
Problema con la sincronizacion de Sqlite con Mysql

Tengo el problema que no me guadar en la tabla si lo recibo pero me da error , en el momento de transformarlo a Json

Gracias por ayuda de antemano . (Soy nuevo en esto)

Método que manda la info al servidor
Código Java:
Ver original
  1. public void sync(View v) {
  2.         // Tag used to cancel the request
  3.         String tag_string_req = "req_login";
  4.        
  5.  
  6.         pDialog.setMessage("Logging in...");
  7.         pDialog.show();
  8.  
  9.         StringRequest strReq = new StringRequest(Method.POST,
  10.                 AppConfig.URL_SYNC, new Response.Listener<String>() {
  11.                     public void onResponse(String response) {
  12.                         Log.d("Login Response",
  13.                                 "Login Response: " + response.toString());
  14.                         pDialog.cancel();
  15.                        
  16.                         String user = config.getUser();
  17.  
  18.  
  19.                         try {
  20.                             JSONObject jObj = new JSONObject(response);
  21.                             boolean error = jObj.getBoolean("error");
  22.  
  23.                             // Check for error node in json
  24.                             if (!error) {
  25.                                 // user successfully logged in
  26.                                 // Create login session
  27.                                
  28.                                 int contLogin = objSqlt.getUser(user);
  29.                                 if (contLogin == 0) {
  30.                                     JSONObject obj = jObj.getJSONObject("user");
  31.                                     Integer id_mysql = obj.getInt("id_mysql");
  32.                                     String user1 = obj.getString("user");
  33.                                     String pass_encrypted = obj.getString("pass_encrypted");
  34.                                     String pass1 = obj.getString("pass");
  35.  
  36.                                     // Inserting row in users table
  37.                                     objSqlt.addUser(id_mysql, user1, pass_encrypted, pass1);
  38.                                 }
  39.  
  40.                             } else {
  41.                                 session.setControl_login(false);
  42.                                 String errorMsg = jObj.getString("error_msg");
  43.                                 Toast.makeText(getApplicationContext(),
  44.                                         errorMsg, Toast.LENGTH_LONG).show();
  45.                             }
  46.                         } catch (JSONException e) {
  47.                             e.printStackTrace();
  48.                         }
  49.                     }
  50.                 }, new Response.ErrorListener() {
  51.  
  52.                     public void onErrorResponse(VolleyError error) {
  53.                         Log.e("Sysn Error: ", error.getMessage());
  54.                         Toast.makeText(getApplicationContext(),
  55.                                 error.getMessage(), Toast.LENGTH_LONG).show();
  56.                         pDialog.cancel();
  57.                     }
  58.                 }) {
  59.             @Override
  60.             protected Map<String, String> getParams() {
  61.                 Map<String, String> params = objSqlt.getJSONfromSQLite();
  62.                 return params;
  63.             }
  64.         };
  65.  
  66.         // Adding request to request queue
  67.         AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
  68.     }

Mi funcion de la clase sqlite, que hace la consulta a la base de datos de android
Código Java:
Ver original
  1. public Map<String, String> getJSONfromSQLite(){
  2.         Map<String, String> array = new HashMap<String, String>();
  3.         Map<String, String> json = new HashMap<String, String>();
  4.         SQLiteDatabase database = this.getWritableDatabase();
  5.         int control=0;
  6.        
  7.         String selectQuery = "SELECT  id_sqlite, user, company, form, checkBox, date FROM chequeo where status = '2' ";
  8.        
  9.        
  10.         Cursor cursor = database.rawQuery(selectQuery, null);
  11.        
  12.         if (cursor.moveToFirst()) {
  13.             do {
  14.                 HashMap<String, String> map = new HashMap<String, String>();
  15.                 map.put("id_sqlite", cursor.getString(0));
  16.                 map.put("user", cursor.getString(1));
  17.                 map.put("company", cursor.getString(2));
  18.                 map.put("form", cursor.getString(3));
  19.                 map.put("checkBox", cursor.getString(4));
  20.                 map.put("date", cursor.getString(5));
  21.                 array.put(control+"",map+"");
  22.                 control++;
  23.             } while (cursor.moveToNext());
  24.         }
  25.         database.close();
  26.         Log.d("map", array.toString());
  27.        
  28.         json.put("json", array.toString());
  29.         return json;
  30.     }

EL error que me muestra
Código Log:
Ver original
  1. 4-14 14:07:07.938: D/Login Response(1038): Login Response:
  2.  
  3. 04-14 14:07:07.938: D/Login Response(1038): string(819) "{3={date=2015-04-10, checkBox=[[0], [1], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0]], form=2, user=a, id_sqlite=4, company=2}, 2={date=2015-04-10 20:57:59, checkBox=[[1], [1], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0]], form=3, user=a, id_sqlite=3, company=1}, 1={date=2015-04-10 20:50:05, checkBox=[[0], [0], [0], [0], [1], [0], [0], [0], [0], [0], [0], [0]], form=1, user=a, id_sqlite=2, company=1}, 0={date=2015-04-10 20:33:17, checkBox=[[0], [1], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0]], form=2, user=a, id_sqlite=1, company=1}, 5={date=2015-04-13, checkBox=[[0], [1], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0]], form=2, user=a, id_sqlite=6, company=3}, 4={date=2015-04-13, checkBox=[[1], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0]], form=1, user=a, id_sqlite=5, company=3}}"
  4. 04-14 14:07:07.938: D/Login Response(1038): []$id_sqlite,$user,$company,$form,$checkbox,$date)
  5.  
  6. 04-14 14:07:07.948: W/System.err(1038): org.json.JSONException: Value string(819) of type java.lang.String cannot be converted to JSONObject
  7. 04-14 14:07:07.968: W/System.err(1038):     at org.json.JSON.typeMismatch(JSON.java:111)
  8. 04-14 14:07:07.968: W/System.err(1038):     at org.json.JSONObject.<init>(JSONObject.java:158)
  9. 04-14 14:07:07.968: W/System.err(1038):     at org.json.JSONObject.<init>(JSONObject.java:171)
  10. 04-14 14:07:07.988: W/System.err(1038):     at com.example.php_mysql_sqlite.MainActivity$1.onResponse(MainActivity.java:131)
  11. 04-14 14:07:07.988: W/System.err(1038):     at com.example.php_mysql_sqlite.MainActivity$1.onResponse(MainActivity.java:1)
  12. 04-14 14:07:07.997: W/System.err(1038):     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
  13. 04-14 14:07:08.018: W/System.err(1038):     at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
  14. 04-14 14:07:08.048: W/System.err(1038):     at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
  15. 04-14 14:07:08.048: W/System.err(1038):     at android.os.Handler.handleCallback(Handler.java:725)
  16. 04-14 14:07:08.048: W/System.err(1038):     at android.os.Handler.dispatchMessage(Handler.java:92)
  17. 04-14 14:07:08.057: W/System.err(1038):     at android.os.Looper.loop(Looper.java:137)
  18. 04-14 14:07:08.057: W/System.err(1038):     at android.app.ActivityThread.main(ActivityThread.java:5041)
  19. 04-14 14:07:08.057: W/System.err(1038):     at java.lang.reflect.Method.invokeNative(Native Method)
  20. 04-14 14:07:08.068: W/System.err(1038):     at java.lang.reflect.Method.invoke(Method.java:511)
  21. 04-14 14:07:08.068: W/System.err(1038):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
  22. 04-14 14:07:08.068: W/System.err(1038):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
  23. 04-14 14:07:08.068: W/System.err(1038):     at dalvik.system.NativeStart.main(Native Method)

Pagina php del servidor
Código PHP:
Ver original
  1. <?php
  2.  
  3. include_once 'include/DB_Functions.php';
  4. //Create Object for DB_Functions clas
  5. $db = new DB_Functions();
  6. //Get JSON posted by Android Application
  7. $json = $_POST["json"];
  8.  
  9. var_dump($json);
  10.  
  11. $db->storeTemporal($json);
  12. //Remove Slashes
  13.     $json = stripslashes($json);
  14. }
  15. //Decode JSON into an Array
  16. $data = json_decode($json);
  17.  
  18. //Util arrays to create response JSON
  19. $a = array();
  20. $b = array();
  21. //Loop through an Array and insert data read from JSON into MySQL DB
  22. for ($i = 0; $i < count($data); $i++) {
  23. //Store User into MySQL DB
  24.     $res = $db->guardar_chequeo($data[$i]->id_sqlite, $data[$i]->user, $data[$i]->company, $data[$i]->form, $data[$i]->checkbox, $data[$i]->date);
  25.     //Based on inserttion, create JSON response
  26.     if ($res) {
  27.         $b["id"] = $data[$i]->userId;
  28.         $b["status"] = 'yes';
  29.         array_push($a, $b);
  30.     } else {
  31.         $b["id"] = $data[$i]->userId;
  32.         $b["status"] = 'no';
  33.         array_push($a, $b);
  34.     }
  35. }
  36. //Post JSON response back to Android Application
  37. echo json_encode($a);
  38. ?>

Como pueden ver, el servidor si lo recibe y lo imprime, pero despues da el error
  #2 (permalink)  
Antiguo 15/04/2015, 10:10
Avatar de Maverick2786  
Fecha de Ingreso: diciembre-2012
Mensajes: 107
Antigüedad: 11 años, 3 meses
Puntos: 1
Respuesta: Problema con la sincronizacion de Sqlite con Mysql

Aqui la solucion

Dentro de mi clase que hace la consulta a sqlite
Código Java:
Ver original
  1. public JSONObject getJSONfromSQLite(){
  2.         JSONObject json_row = new JSONObject();
  3.         SQLiteDatabase database = this.getWritableDatabase();
  4.         int cont=0;
  5.        
  6.         String selectQuery = "SELECT  id_sqlite, user, company, form, checkBox, date FROM chequeo where status = '2' ";
  7.        
  8.        
  9.         Cursor cursor = database.rawQuery(selectQuery, null);
  10.        
  11.         if (cursor.moveToFirst()) {
  12.             do {
  13.                 JSONObject json_val = new JSONObject();
  14.                 try{
  15.                     cont++;
  16.                     json_val.put("id_sqlite", cursor.getString(0));
  17.                     json_val.put("user", cursor.getString(1));
  18.                     json_val.put("company", cursor.getString(2));
  19.                     json_val.put("form", cursor.getString(3));
  20.                     json_val.put("checkBox", cursor.getString(4));
  21.                     json_val.put("date", cursor.getString(5));
  22.                     json_row.put("cont"+cont,json_val);
  23.                    
  24.                 }
  25.                 catch(Exception e)
  26.                 {
  27.                     Log.e("getJSONfromSQLite catch", e.getMessage());
  28.                 }
  29.             } while (cursor.moveToNext());
  30.         }
  31.         database.close();
  32.        
  33.         JSONObject json = new JSONObject();
  34.        
  35.         try{
  36.             json.put("json",json_row);
  37.             json.put("cont",cont);
  38.         }
  39.         catch(Exception e){
  40.             Log.e("json catch", e.getMessage());
  41.         }
  42.        
  43.         return  json;
  44.     }

Dentro de la clase que manda los datos al servidor
Código Java:
Ver original
  1. public void sync(View v) {
  2.         // Tag used to cancel the request
  3.         String tag_string_req = "req_login";
  4.        
  5.  
  6.         pDialog.setMessage("Logging in...");
  7.         pDialog.show();
  8.  
  9.         StringRequest strReq = new StringRequest(Method.POST,
  10.                 AppConfig.URL_SYNC, new Response.Listener<String>() {
  11.                     public void onResponse(String response) {
  12.                        
  13.                         try {
  14.                             Log.d("Login Response",
  15.                                     "Login Response: " + response.toString());
  16.                             pDialog.cancel();
  17.                            
  18.                             String user = config.getUser();
  19.                            
  20.                             JSONObject jObj = new JSONObject(response);
  21.                             boolean error = jObj.getBoolean("error");
  22.  
  23.                             // Check for error node in json
  24.                             if (!error) {
  25.                                 // user successfully logged in
  26.                                 // Create login session
  27.                                
  28.                                 int contLogin = objSqlt.getUser(user);
  29.                                 if (contLogin == 0) {
  30.                                     JSONObject obj = jObj.getJSONObject("user");
  31.                                     Integer id_mysql = obj.getInt("id_mysql");
  32.                                     String user1 = obj.getString("user");
  33.                                     String pass_encrypted = obj.getString("pass_encrypted");
  34.                                     String pass1 = obj.getString("pass");
  35.  
  36.                                     // Inserting row in users table
  37.                                     objSqlt.addUser(id_mysql, user1, pass_encrypted, pass1);
  38.                                 }
  39.  
  40.                             } else {
  41.                                 session.setControl_login(false);
  42.                                 String errorMsg = jObj.getString("error_msg");
  43.                                 Toast.makeText(getApplicationContext(),
  44.                                         errorMsg, Toast.LENGTH_LONG).show();
  45.                             }
  46.                         } catch (JSONException e) {
  47.                             e.printStackTrace();
  48.                         }
  49.                     }
  50.                 }, new Response.ErrorListener() {
  51.                     public void onErrorResponse(VolleyError error) {
  52.                         Log.e("Sysn Error: ", "Error en la conexion");
  53.                         Toast.makeText(getApplicationContext(),
  54.                                 "Error en la conexion", Toast.LENGTH_LONG).show();
  55.                         pDialog.cancel();
  56.                     }
  57.                 }) {
  58.             @Override
  59.             protected Map<String, String> getParams() {
  60.                 Map<String, String> params = new HashMap<String, String>();
  61.                 JSONObject json = objSqlt.getJSONfromSQLite();
  62.                
  63.                 try{
  64.                     params.put("json", json.getString("json"));
  65.                     params.put("cont", json.getString("cont"));
  66.                 } catch(Exception e){
  67.                     Log.e("getParams", e.getMessage());
  68.                 }
  69.                 return params;
  70.             }
  71.         };
  72.  
  73.         // Adding request to request queue
  74.         AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
  75.     }

Etiquetas: activity, androi, app, mysql, sincronizacion, sqlite, view
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 17:25.