php - 与 Mysql Sqlite 同步

标签 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);
}

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

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:如果你给我负分,请留言说说我做错了什么,学习因为我有时会遇到这种情况而不是那次失败

最佳答案

类中的函数,它对 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形式的数据

关于php - 与 Mysql Sqlite 同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29630209/

相关文章:

php - Laravel 缓存返回损坏的数据(redis 驱动程序)

php - 导入 mySQL 数据 - 错误的字符集

mysql - mysql 中值 11.1234 的数据类型是什么?

python - 连接到 MySql 服务器失败 - Python

PHP Bootstrap 多选选项

android - 对话框中的按钮设置事件时android崩溃

java - getIntent().getStringExtra ("name") 返回 null

android - Android TV 上的 Facebook 登录

Java MySQL 准备语句批处理

php - 优化 AJAX 网站以使用最少的资源