I'm trying to connect toa mysql database with an android application with an HTTP connection and then retriving a JSONArray to scan results from the query. Here is the code:
public class MyActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
new JSONfunction().execute();
}
private class JSONfunction extends AsyncTask<Void,Void,JSONArray> {
private JSONArray getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONArray jArray = null;
// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// Convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
jArray=new JSONArray(result);
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
return jArray;
}
@Override
protected JSONArray doInBackground(Void... voids) {
JSONArray jArray=getJSONfromURL("http://192.168.1.5/ConnectData/index.php");
return jArray;
}
protected void onPostExecute(JSONArray result) {
TextView prova = (TextView)findViewById(R.id.txtProva);
try {
JSONObject rec = result.getJSONObject(1);
prova.setText(rec.getString("first_name"));
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data " + e.toString());
}
}
}
I'm getting an error when it is executing the while. After 2 or 3 cycles of the while the application crashes. Can you give me any help?
[edit]
I'm getting this error: 11-28 20:42:19.006 27688-27702/com.example.marco.provadatabase E/log_tag﹕ Error converting result org.json.JSONException: Value !DOCTYPE of type java.lang.String cannot be converted to JSONArray
[edit 2]
Ok I understood the problem. BUt now I'm facing a new one. Today a tried again to execute the code but now I am getting a time out exception on thi line HttpResponse response = httpclient.execute(httppost); (It worked fine yesterday and I didn't change anything). It isn't a URL problem because if I put it on a browser it works fine.
您的响应类型为String,应将其转换为JSONObject
Here is the problem
result = sb.toString();
jArray=new JSONArray(result);
You are trying to get jsonarray of your response string which i believe don't have a jsonarray at it's root. Can you please share the response for your request.
For Your Timeout Problem
In my example two timeouts are set. The connection timeout throws "java.net.SocketTimeoutException: Socket is not connected" and the socket timeout "java.net.SocketTimeoutException: The operation timed out".
HttpGet httpGet = new HttpGet(url);
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpResponse response = httpClient.execute(httpGet);
If you want to set the Parameters of any existing HTTPClient (eg DefaultHttpClient or AndroidHttpClient) you can use the function setParams().
httpClient.setParams(httpParameters);
Hop it clear things up for you :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.