如何将SQLite数据从Android发送到MySQL服务器?

时间:2021-11-03 06:13:30

I am trying to send my SQLite data with online MySQL server but to no avail. Naturally, I ran to Google and was lucky enough to find this. Apparently it's supposed to work and it does but I am not receiving the data on my server.

我正在尝试用在线MySQL服务器发送我的SQLite数据,但是没有用。我很自然地跑到谷歌,很幸运地找到了这个。显然,它应该是可以工作的,但我没有收到服务器上的数据。

I know this question has been asked here and here, but I haven't been able to patch it up using the suggestions given.

我知道这里和这里都有人问过这个问题,但是我还不能用给出的建议来弥补这个问题。

Here is what I have tried. This is how I convert my SQLite data into JSON using GSON:

这是我试过的。这就是我如何使用GSON将我的SQLite数据转换成JSON:

public String composeJSONfromSQLite() {
     ArrayList<HashMap<String, String>> offlineList;
     offlineList = new ArrayList<HashMap<String, String>>();
     String selectQuery = "SELECT  * FROM offlineTable ";
     SQLiteDatabase database = this.getWritableDatabase();
     Cursor cursor = database.rawQuery(selectQuery, null);
     if (cursor.moveToFirst()) {
     do {
     HashMap<String, String> map = new HashMap<String, String>();
     map.put("zip", cursor.getString(1));
     map.put("phone", cursor.getString(2));
     map.put("uid", cursor.getString(3));
     offlineList.add(map);

      } while (cursor.moveToNext());
      }
     database.close();
     Gson gson = new GsonBuilder().create();
     //Use GSON to serialize Array List to JSON
     return gson.toJson(offlineList);
}

And this is how I send it to my server:

这是我发送给我的服务器的方式:

public void syncSQLiteMySQLDB() {

     AsyncHttpClient client = new AsyncHttpClient();

     RequestParams params = new RequestParams();  
     params.put("offline",loadCheckoutDB.composeJSONfromSQLite());

     Log.d("offline data log", loadCheckoutDB.composeJSONfromSQLite());
     client.addHeader("session_id", getapikey());
     client.addHeader("Content-Type", "application/json");

     client.post("http://example.com/offline/api", params, new AsyncHttpResponseHandler() {

     @Override
      public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
      String s = new String(responseBody);

     Log.d("response to sync", s);

     try {

    JSONObject obj = new JSONObject(s);

     if (obj.getBoolean("success")) {

     String success = obj.getString("message");
      //Toast.makeText(getApplicationContext(), success, Toast.LENGTH_LONG).show();

    } else {

      String failure = obj.getString("message");
      //Toast.makeText(getApplicationContext(), failure, Toast.LENGTH_LONG).show();

      }
      } catch (JSONException e) {

      }

      }

      @Override

    public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

     // Toast.makeText(getApplicationContext(), "Failed to sync with server", Toast.LENGTH_LONG).show();
    Log.d("sqlite sync error", String.valueOf(error));

     progbar.setVisibility(View.INVISIBLE);
     }

    });
}

And when I log what the JASON looks like from Android I get this format:

当我从Android上记录JASON的样子时,我得到了这个格式:

[{
 "zip": "325,
  "phone": "78291849",
  "uid": "14538177211"
 }]

But on my server I still get an empty array. What am I doing wrong?

但在我的服务器上,我仍然得到一个空数组。我做错了什么?

This is how my request format should look like:

以下是我的申请格式:

{
  "offline":[
  {
 "zip": "325,
  "phone": "78291849",
  "uid": "14538177211"
 }
]
}

Here is how I receive the request:

以下是我收到的请求:

public function massData() 
// offline sync
{

$input = Input::all();

 return $input;

2 个解决方案

#1


1  

Add your list to a map where key is offline and value that list:

将您的列表添加到一个映射,其中键是脱机的,值为该列表:

public String composeJSONfromSQLite() {
     ArrayList<HashMap<String, String>> offlineList;
     offlineList = new ArrayList<HashMap<String, String>>();
     String selectQuery = "SELECT  * FROM offlineTable ";
     SQLiteDatabase database = this.getWritableDatabase();
     Cursor cursor = database.rawQuery(selectQuery, null);
     if (cursor.moveToFirst()) {
     do {
     HashMap<String, String> map = new HashMap<String, String>();
     map.put("zip", cursor.getString(1));
     map.put("phone", cursor.getString(2));
     map.put("uid", cursor.getString(3));
     offlineList.add(map);

      } while (cursor.moveToNext());
      }
     HashMap<String, ArrayList<HashMap<String, String>>> offlineMap = new HashMap<String, ArrayList<HashMap<String, String>>>();
     offlineMap.put("offline", offlineList);
     database.close();
     Gson gson = new GsonBuilder().create();
     //Use GSON to serialize Array List to JSON
     return gson.toJson(offlineMap);
}

#2


0  

Here's how I have done it:

我是这样做的:

 public void syncSQLiteMySQLDB() {

   //i get my json string from sqlite, see the code i posted above about this
        final String json = loadCheckoutDB.composeJSONfromSQLite();

        new Thread() {
            public void run() {
                makeRequest("http://myexample/offline/api", json);
            }
        }.start();

    }

    public void makeRequest(String uri, String json) {
        try {
            HttpClient client = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(uri);
            httpPost.setEntity(new StringEntity(json));
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("session_id", getapikey());
            httpPost.setHeader("Content-type", "application/json");
            HttpResponse response = client.execute(httpPost);
            if (response != null) {

                String responseBody = EntityUtils.toString(response.getEntity());
                Log.d("response to sync", responseBody);
                Object jsonObj = new JSONTokener(responseBody).nextValue();
                if (jsonObj instanceof JSONObject) {
                    JSONObject jsonObject = (JSONObject) jsonObj;
                    //further actions on jsonObjects

                } else if (jsonObj instanceof JSONArray) {
                    //further actions on jsonArray
                    JSONArray jsonArray = (JSONArray) jsonObj;
                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

From logging numerous responses I discovered that I was not sending content-type using my previous method. After trying out this code, it worked.

通过记录大量的响应,我发现我没有使用以前的方法发送内容类型。在尝试了这段代码之后,它成功了。

#1


1  

Add your list to a map where key is offline and value that list:

将您的列表添加到一个映射,其中键是脱机的,值为该列表:

public String composeJSONfromSQLite() {
     ArrayList<HashMap<String, String>> offlineList;
     offlineList = new ArrayList<HashMap<String, String>>();
     String selectQuery = "SELECT  * FROM offlineTable ";
     SQLiteDatabase database = this.getWritableDatabase();
     Cursor cursor = database.rawQuery(selectQuery, null);
     if (cursor.moveToFirst()) {
     do {
     HashMap<String, String> map = new HashMap<String, String>();
     map.put("zip", cursor.getString(1));
     map.put("phone", cursor.getString(2));
     map.put("uid", cursor.getString(3));
     offlineList.add(map);

      } while (cursor.moveToNext());
      }
     HashMap<String, ArrayList<HashMap<String, String>>> offlineMap = new HashMap<String, ArrayList<HashMap<String, String>>>();
     offlineMap.put("offline", offlineList);
     database.close();
     Gson gson = new GsonBuilder().create();
     //Use GSON to serialize Array List to JSON
     return gson.toJson(offlineMap);
}

#2


0  

Here's how I have done it:

我是这样做的:

 public void syncSQLiteMySQLDB() {

   //i get my json string from sqlite, see the code i posted above about this
        final String json = loadCheckoutDB.composeJSONfromSQLite();

        new Thread() {
            public void run() {
                makeRequest("http://myexample/offline/api", json);
            }
        }.start();

    }

    public void makeRequest(String uri, String json) {
        try {
            HttpClient client = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(uri);
            httpPost.setEntity(new StringEntity(json));
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("session_id", getapikey());
            httpPost.setHeader("Content-type", "application/json");
            HttpResponse response = client.execute(httpPost);
            if (response != null) {

                String responseBody = EntityUtils.toString(response.getEntity());
                Log.d("response to sync", responseBody);
                Object jsonObj = new JSONTokener(responseBody).nextValue();
                if (jsonObj instanceof JSONObject) {
                    JSONObject jsonObject = (JSONObject) jsonObj;
                    //further actions on jsonObjects

                } else if (jsonObj instanceof JSONArray) {
                    //further actions on jsonArray
                    JSONArray jsonArray = (JSONArray) jsonObj;
                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

From logging numerous responses I discovered that I was not sending content-type using my previous method. After trying out this code, it worked.

通过记录大量的响应,我发现我没有使用以前的方法发送内容类型。在尝试了这段代码之后,它成功了。