【问题标题】:How can I send SQLite data from Android to a MySQL server?如何将 SQLite 数据从 Android 发送到 MySQL 服务器?
【发布时间】:2016-01-28 17:01:15
【问题描述】:

我正在尝试使用在线 MySQL 服务器发送我的 SQLite 数据,但无济于事。自然而然地,我跑到谷歌,幸运地找到了this。显然它应该可以工作,但我没有在我的服务器上收到数据。

我知道有人问过这个问题 herehere,但我无法使用给出的建议来修补它。

这是我尝试过的。这就是我使用 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);
}

这就是我将它发送到我的服务器的方式:

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

    });
}

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

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

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

我的请求格式应该是这样的:

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

这是我收到请求的方式:

public function massData() 
// offline sync
{

$input = Input::all();

 return $input;

【问题讨论】:

  • 但目前未在服务器上发送array 。像client.addHeader("data", loadCheckoutDB.composeJSONfromSQLite()); 那样做
  • 感谢您的早期回复。我试过了,但我的响应仍然是 [],一个空数组。
  • 展示如何在服务器端代码中访问offline
  • 堆栈片段与 Java 代码无关。请从对您其他帖子的修改中学习。

标签: java android mysql json sqlite


【解决方案1】:

将您的列表添加到键为 offline 的地图中并为该列表赋值:

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】:

    这是我的做法:

     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();
            }
        }
    

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

    【讨论】:

    • 有没有可能使用 volley 实现这一点的方法?
    • @shaiToro 使用库可以删除自己编写的所有不安全样板。查看 okhttp 或 volley
    • @shaiToro 我尝试使用 volley 但无法将内容类型获取到 application/json。不知道为什么。
    猜你喜欢
    • 2017-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-24
    • 1970-01-01
    • 1970-01-01
    • 2013-12-13
    相关资源
    最近更新 更多