如何从Android发送的SQLite数据MySQL服务器 [英] How to send SQLite data from android to MySQL server

查看:169
本文介绍了如何从Android发送的SQLite数据MySQL服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

,所以我想在网上与MySQL服务器,但没有avail.Naturally送我的SQLite的数据,我跑了谷歌和幸运找到的这个。显然,它应该工作,它不会,但我没有收到我的服务器上的数据。

是的,我知道这个问题已经被问<一个href=\"http://stackoverflow.com/questions/23797747/how-to-send-all-sqlite-data-to-online-server\">here和这里,但我还没有能够使用的建议修补它给出了

因此​​,这里是我tried.This是如何使用我我GSON SQLite的数据转化成JSON:

\r
\r

公共字符串composeJSONfromSQLite(){\r
 ArrayList的&LT;&HashMap的LT;字符串,字符串&GT;&GT; offlineList;\r
 offlineList =新的ArrayList&LT;&HashMap的LT;字符串,字符串&GT;&GT;();\r
 字符串selectQuery =SELECT * FROM offlineTable\r
 SQLiteDatabase数据库= this.getWritableDatabase();\r
 光标光标= database.rawQuery(selectQuery,NULL);\r
 如果(cursor.moveToFirst()){\r
 做{\r
 HashMap的&LT;字符串,字符串&GT;地图=新的HashMap&LT;字符串,字符串&GT;();\r
 map.put(ZIP,cursor.getString(1));\r
 map.put(手机,cursor.getString(2));\r
 map.put(UID,cursor.getString(3));\r
 offlineList.add(地图);\r
\r
  }而(cursor.moveToNext());\r
  }\r
 database.close();\r
 GSON GSON =新GsonBuilder()创建()。\r
 //使用GSON序列化数组列表,以JSON\r
 返回gson.toJson(offlineList);\r
 }

\r

\r
\r

这就是我如何将其发送到我的服务器:

\r
\r

公共无效syncSQLiteMySQLDB(){\r
   \r
 AsyncHttpClient客户端=新AsyncHttpClient();\r
   \r
 RequestParams PARAMS =新RequestParams();\r
 params.put(离线,loadCheckoutDB.composeJSONfromSQLite());\r
            \r
 Log.d(离线数据日志,loadCheckoutDB.composeJSONfromSQLite());\r
 client.addHeader(session_id的,getapikey());\r
 client.addHeader(内容类型,应用/ JSON);\r
\r
 client.post(http://example.com/offline/api,则params,新AsyncHtt presponseHandler(){\r
             \r
 @覆盖\r
  公共无效的onSuccess(INT状态code,头[]头,字节[] responseBody){\r
  字符串s =新的String(responseBody);\r
   \r
 Log.d(回应同步,S);\r
   \r
 尝试{\r
   \r
JSONObject的OBJ =新的JSONObject(S);\r
   \r
 如果(obj.getBoolean(成功)){\r
   \r
 字符串成功= obj.getString(信息);\r
  //Toast.makeText(getApplicationContext(),成功,Toast.LENGTH_LONG).show();\r
   \r
}其他{\r
  \r
  串故障= obj.getString(信息);\r
  //Toast.makeText(getApplicationContext(),故障,Toast.LENGTH_LONG).show();\r
\r
  }\r
  }赶上(JSONException E){\r
\r
  }\r
\r
  }\r
\r
  @覆盖\r
  \r
公共无效onFailure处(INT状态code,头[]头,字节[] responseBody,Throwable的错误){\r
  \r
 // Toast.makeText(getApplicationContext(),无法与服务器同步,Toast.LENGTH_LONG).show();\r
Log.d(sqlite的同步错误,将String.valueOf(错误));\r
  \r
 progbar.setVisibility(View.INVISIBLE);\r
 }\r
\r
});\r
}

\r

\r
\r

当我登录了JSON的样子从Android的我得到这个格式:

\r
\r

[{\r
 拉链:325,\r
  手机:78291849,\r
  UID:14538177211\r
 }]

\r

\r
\r

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

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

\r
\r

{\r
  离线:\r
  {\r
 拉链:325,\r
  手机:78291849,\r
  UID:14538177211\r
 }\r
]\r
}

\r

\r
\r

由于这里是要求我如何接收请求:

\r
\r

公共职能massData()\r
//离线同步\r
{\r
  \r
$输入=输入::所有();\r
  \r
 返回$输入;

\r

\r
\r


解决方案

也许有一个人谁将会就这个问题寻求帮助跌倒。下面是我做的:

\r
\r

公共无效syncSQLiteMySQLDB(){\r
 \r
   //我从我的SQLite的JSON字符串,见code I上面张贴这个\r
        最终的JSON字符串= loadCheckoutDB.composeJSONfromSQLite();\r
   \r
        新的Thread(){\r
            公共无效的run(){\r
                makeRequest的(HTTP:// myexample中/离线/ API,JSON);\r
            }\r
        }。开始();\r
\r
    }\r
\r
    公共无效makeRequest的(URI字符串,字符串的json){\r
        尝试{\r
            HttpClient的客户端=新DefaultHttpClient();\r
            HttpPost httpPost =新HttpPost(URI);\r
            httpPost.setEntity(新StringEntity(JSON));\r
            httpPost.setHeader(接受,应用/ JSON);\r
            httpPost.setHeader(session_id的,getapikey());\r
            httpPost.setHeader(内容类型,应用/ JSON);\r
            HTT presponse响应= client.execute(httpPost);\r
            如果(响应!= NULL){\r
\r
                串responseBody = EntityUtils.toString(response.getEntity());\r
                Log.d(回应同步,responseBody);\r
                对象jsonObj =新JSONTokener(responseBody).nextValue();\r
                如果(jsonObj的instanceof的JSONObject){\r
                    的JSONObject的JSONObject =(JSONObject的)jsonObj;\r
                    //在一个JSONObjects进一步行动\r
\r
                }否则如果(jsonObj的instanceof JSONArray),其中{\r
                    //对jsonArray进一步行动\r
                    JSONArray jsonArray =(JSONArray),其中jsonObj;\r
                }\r
            }\r
        }赶上(UnsupportedEncodingException五){\r
            e.printStackTrace();\r
        }赶上(ClientProtocolException E){\r
            e.printStackTrace();\r
        }赶上(IOException异常五){\r
            e.printStackTrace();\r
        }赶上(JSONException E){\r
            e.printStackTrace();\r
        }\r
    }

\r

\r
\r

从记录多个响应我发现我没有使用我的previous方法发送内容类型。尝试这种code后,它的工作。谢谢大家谁与把我推到记录所有各种建议走了过来。

So 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.

And yes, i know this question has been asked here and here, but i havent been able to patch it up using the suggestions given.

So here is what i have tried.This is how i convert my SQLite data into JSON using GSON:

 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 json looks like from android i get this format:

[{
 "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"
 }
]
}

As requested here is how i receive the request:

public function massData() 
// offline sync
{
  
$input = Input::all();
  
 return $input;

解决方案

Maybe there's someone who will stumble upon this question seeking help. 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. Thanks everyone who came up with various suggestions that pushed me to log everything.

这篇关于如何从Android发送的SQLite数据MySQL服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆