与Mysql Sqlite同步

时间:2015-04-14 14:36:12

标签: php android mysql sqlite

我遇到的问题是,如果我收到它,我就不会保存在表格中但是在转换Json时它给了我错误

提前感谢您的帮助。 (我对此不熟悉)

将信息发送到服务器的方法

public void sync(View v) {
    // Tag used to cancel the request
    String tag_string_req = "req_login";


    pDialog.setMessage("Logging in...");
    pDialog.show();

    StringRequest strReq = new StringRequest(Method.POST,
            AppConfig.URL_SYNC, new Response.Listener<String>() {
                public void onResponse(String response) {
                    Log.d("Login Response",
                            "Login Response: " + response.toString());
                    pDialog.cancel();

                    String user = config.getUser();


                    try {
                        JSONObject jObj = new JSONObject(response);
                        boolean error = jObj.getBoolean("error");

                        // Check for error node in json
                        if (!error) {
                            // user successfully logged in
                            // Create login session

                            int contLogin = objSqlt.getUser(user);
                            if (contLogin == 0) {
                                JSONObject obj = jObj.getJSONObject("user");
                                Integer id_mysql = obj.getInt("id_mysql");
                                String user1 = obj.getString("user");
                                String pass_encrypted = obj.getString("pass_encrypted");
                                String pass1 = obj.getString("pass");

                                // Inserting row in users table
                                objSqlt.addUser(id_mysql, user1, pass_encrypted, pass1);
                            }

                        } else {
                            session.setControl_login(false);
                            String errorMsg = jObj.getString("error_msg");
                            Toast.makeText(getApplicationContext(),
                                    errorMsg, Toast.LENGTH_LONG).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {

                public void onErrorResponse(VolleyError error) {
                    Log.e("Sysn Error: ", error.getMessage());
                    Toast.makeText(getApplicationContext(),
                            error.getMessage(), Toast.LENGTH_LONG).show();
                    pDialog.cancel();
                }
            }) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = objSqlt.getJSONfromSQLite();
            return params;
        }
    };

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}

我的函数sqlite类查询数据库android

public Map<String, String> getJSONfromSQLite(){
    Map<String, String> array = new HashMap<String, String>();
    Map<String, String> json = new HashMap<String, String>();
    SQLiteDatabase database = this.getWritableDatabase();
    int control=0;

    String selectQuery = "SELECT  id_sqlite, user, company, form, checkBox, date FROM chequeo where status = '2' ";


    Cursor cursor = database.rawQuery(selectQuery, null);

    if (cursor.moveToFirst()) {
        do {
            HashMap<String, String> map = new HashMap<String, String>();
            map.put("id_sqlite", cursor.getString(0));
            map.put("user", cursor.getString(1));
            map.put("company", cursor.getString(2));
            map.put("form", cursor.getString(3));
            map.put("checkBox", cursor.getString(4));
            map.put("date", cursor.getString(5));
            array.put(control+"",map+"");
            control++;
        } while (cursor.moveToNext());
    }
    database.close();
    Log.d("map", array.toString());

    json.put("json", array.toString());
    return json;
}

日志显示我

04-14 14:07:07.938: D/Login Response(1038): Login Response: 

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}}"

04-14 14:07:07.938: D/Login Response(1038): 
[]$id_sqlite,$user,$company,$form,$checkbox,$date)

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

04-14 14:07:07.968: W/System.err(1038):     at 
org.json.JSON.typeMismatch(JSON.java:111)

04-14 14:07:07.968: W/System.err(1038):     at org.json.JSONObject.<init>
(JSONObject.java:158)

04-14 14:07:07.968: W/System.err(1038):     at org.json.JSONObject.<init>
(JSONObject.java:171)

04-14 14:07:07.988: W/System.err(1038):     at    
com.example.php_mysql_sqlite.MainActivity$1. 
onResponse(MainActivity.java:131)

04-14 14:07:07.988: W/System.err(1038):     at 
com.example.php_mysql_sqlite.MainActivity$1. 
onResponse(MainActivity.java:1)

04-14 14:07:07.997: W/System.err(1038):     at  
com.android.volley.toolbox.StringRequest. 
deliverResponse(StringRequest.java:60)

04-14 14:07:08.018: W/System.err(1038):     at 
com.android.volley.toolbox.StringRequest. 
deliverResponse(StringRequest.java:30)

04-14 14:07:08.048: W/System.err(1038):     at 
com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable. 
run(ExecutorDelivery.java:99)

04-14 14:07:08.048: W/System.err(1038):     at 
android.os.Handler.handleCallback(Handler.java:725)

04-14 14:07:08.048: W/System.err(1038):     at 
android.os.Handler.dispatchMessage(Handler.java:92)

04-14 14:07:08.057: W/System.err(1038):     at 
android.os.Looper.loop(Looper.java:137)

04-14 14:07:08.057: W/System.err(1038):     at 
android.app.ActivityThread.main(ActivityThread.java:5041)

04-14 14:07:08.057: W/System.err(1038):     at 
java.lang.reflect.Method.invokeNative(Native Method)

04-14 14:07:08.068: W/System.err(1038):     at 
java.lang.reflect.Method.invoke(Method.java:511)

04-14 14:07:08.068: W/System.err(1038):     at 
com.android.internal.os.ZygoteInit$MethodAndArgsCaller. 
run(ZygoteInit.java:793)

04-14 14:07:08.068: W/System.err(1038):     at 
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)

04-14 14:07:08.068: W/System.err(1038):     at 
dalvik.system.NativeStart.main(Native Method)

页面php服务器

<?php
include_once 'include/DB_Functions.php';
//Create Object for DB_Functions clas
$db = new DB_Functions();
//Get JSON posted by Android Application
$json = $_POST["json"];

var_dump($json);

$db->storeTemporal($json);
//Remove Slashes
if (get_magic_quotes_gpc()) {
$json = stripslashes($json);
}
//Decode JSON into an Array
$data = json_decode($json);

//Util arrays to create response JSON
$a = array();
$b = array();
//Loop through an Array and insert data read from JSON into MySQL DB
for ($i = 0; $i < count($data); $i++) {
//Store User into MySQL DB
$res = $db->guardar_chequeo($data[$i]->id_sqlite, $data[$i]->user,    $data[$i]->company, $data[$i]->form,$data[$i]->checkbox, $data[$i]->date);
//Based on inserttion, create JSON response
if ($res) {
    $b["id"] = $data[$i]->userId;
    $b["status"] = 'yes';
    array_push($a, $b);
} else {
    $b["id"] = $data[$i]->userId;
    $b["status"] = 'no';
    array_push($a, $b);
}
}
//Post JSON response back to Android Application
echo json_encode($a);
?>

如您所见,如果服务器接收并打印,但随后给出错误

PS:如果你给我负面评价,请对我做错的事情发表评论,要了解有时候发生在我身上而不是那次失败

1 个答案:

答案 0 :(得分:0)

类中的函数,它对sqlite进行查询

public JSONObject getJSONfromSQLite(){
    JSONObject json_row = new JSONObject();
    SQLiteDatabase database = this.getWritableDatabase();
    int cont=0;

    String selectQuery = "SELECT  id_sqlite, user, company, form, checkBox, date FROM chequeo where status = '2' ";


    Cursor cursor = database.rawQuery(selectQuery, null);

    if (cursor.moveToFirst()) {
        do {
            JSONObject json_val = new JSONObject();
            try{
                cont++;
                json_val.put("id_sqlite", cursor.getString(0));
                json_val.put("user", cursor.getString(1));
                json_val.put("company", cursor.getString(2));
                json_val.put("form", cursor.getString(3));
                json_val.put("checkBox", cursor.getString(4));
                json_val.put("date", cursor.getString(5));
                json_row.put("cont"+cont,json_val);

            }
            catch(Exception e)
            {
                Log.e("getJSONfromSQLite catch", e.getMessage());
            }
        } while (cursor.moveToNext());
    }
    database.close();

    JSONObject json = new JSONObject();

    try{
        json.put("json",json_row);
        json.put("cont",cont);
    }
    catch(Exception e){
        Log.e("json catch", e.getMessage());
    }

    return  json;
}

类中将数据发送到服务器的函数

public void sync(View v) {
    // Tag used to cancel the request
    String tag_string_req = "req_login";


    pDialog.setMessage("Logging in...");
    pDialog.show();

    StringRequest strReq = new StringRequest(Method.POST,
            AppConfig.URL_SYNC, new Response.Listener<String>() {
                public void onResponse(String response) {

                    try {
                        Log.d("Login Response",
                                "Login Response: " + response.toString());
                        pDialog.cancel();

                        String user = config.getUser();

                        JSONObject jObj = new JSONObject(response);
                        boolean error = jObj.getBoolean("error");

                        // Check for error node in json
                        if (!error) {
                            // user successfully logged in
                            // Create login session

                            int contLogin = objSqlt.getUser(user);
                            if (contLogin == 0) {
                                JSONObject obj = jObj.getJSONObject("user");
                                Integer id_mysql = obj.getInt("id_mysql");
                                String user1 = obj.getString("user");
                                String pass_encrypted = obj.getString("pass_encrypted");
                                String pass1 = obj.getString("pass");

                                // Inserting row in users table
                                objSqlt.addUser(id_mysql, user1, pass_encrypted, pass1);
                            }

                        } else {
                            session.setControl_login(false);
                            String errorMsg = jObj.getString("error_msg");
                            Toast.makeText(getApplicationContext(),
                                    errorMsg, Toast.LENGTH_LONG).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
                public void onErrorResponse(VolleyError error) {
                    Log.e("Sysn Error: ", "Error en la conexion");
                    Toast.makeText(getApplicationContext(),
                            "Error en la conexion", Toast.LENGTH_LONG).show();
                    pDialog.cancel();
                }
            }) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
            JSONObject json = objSqlt.getJSONfromSQLite();

            try{
                params.put("json", json.getString("json"));
                params.put("cont", json.getString("cont"));
            } catch(Exception e){
                Log.e("getParams", e.getMessage());
            }
            return params;
        }
    };

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}

现在我用php

以post的形式获取数据