I am a beginner in android development. I have upload the file, and get the response from server. However, the response contains the value that I dont want. The server response as: Value {"time_used":53840,"result_idcard":{"index1":0,"index2":0,"confidence":87.42464,"}}.
I only want the confidence level only. How I can extract that? When I run the code below, the logcat shows:
Error: org.json.JSONException of type org.json.JSONObject cannot be converted to JSONArray.
Please help me..
/** * Uploading the file to server */
private class UploadFileToServer extends AsyncTask<Void, Integer, String> {
String docPath= null;
String facePath=null;
public UploadFileToServer(String docPath, String facePath) throws JSONException {
this.docPath = docPath;
this.facePath = facePath;
}
@Override
protected void onPreExecute() {
// setting progress bar to zero
progressBar.setProgress(0);
super.onPreExecute();
}
@Override
protected void onProgressUpdate(Integer... progress) {
// Making progress bar visible
progressBar.setVisibility(View.VISIBLE);
// updating progress bar value
progressBar.setProgress(progress[0]);
// updating percentage value
txtPercentage.setText(String.valueOf(progress[0]) + "%");
//code to show progress in notification bar
FileUploadNotification fileUploadNotification = new FileUploadNotification(UploadActivity.this);
fileUploadNotification.updateNotification(String.valueOf(progress[0]), "Image 123.jpg", "Camera Upload");
}
@Override
protected String doInBackground(Void... params) {
return uploadFile();
}
@SuppressWarnings("deprecation")
public String uploadFile() {
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Config.FILE_UPLOAD_URL);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new ProgressListener() {
@Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
entity.addPart("imageIdCard", new FileBody(new File(docPath)));
entity.addPart("imageBest", new FileBody(new File(facePath)));
totalSize = entity.getContentLength();
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
return responseString;
}
@Override
protected void onPostExecute(String result) {
//super.onPostExecute(result);
//if (result != null)
try
{
//Convert response string to Json Array
JSONArray ja = new JSONArray(result);
//Iterate through and retrieve club fields
int n = ja.length();
for (int i = 0; i < n; i++) {
//Get individual Json object from Json Array
JSONObject jo = ja.getJSONObject(i);
//Retrieve each Json object's fields
String request_id = jo.getString("request_id");
Double confidence = jo.getDouble("confidence");
//float confidence= BigDecimal.valueOf(jo.getDouble("result_idcard/confidence")).floatValue();
}
} catch (JSONException e) {
Log.e("JSONException", "Error: " + e.toString());
}
//Log.e(TAG, "Response from server: " + result);
// showing the server response in an alert dialog
showAlert(result);
}
}
You're converting the JSON result to JSONArray
but the result is just an object. So directly parse it to object and get the nodes you need. And also, the result_idcard
is object, you also need to convert it to JSONObject
then get the confidence
node.
Try this:
@Override
protected void onPostExecute(String result) {
try {
JSONObject jsonObject = new JSONObject(result);
//Retrieve each Json object's fields
JSONObject request_id = jsonObject.getJSONObject("result_idcard");
Double confidence = request_id.getDouble("confidence");
showAlert(confidence);
} catch (JSONException e) {
e.printStackTrace();
}
}
Based on the OP's question (so far) and the (invalid) JSON example the OP provided I have hacked out a little test for them to try. Perhaps the OP will get the idea of how this works.
Just put this code somewhere in you activity and call startJsonTest();
. You will see the response in the logcat.
private void startJsonTest(){
// The JSON the OP provide in their question!
String json = "{'time_use':53840,'result_idcard':{'index1':0,'index2':0,'confidence':87.42464}}";
testYourJson(json);
}
private void testYourJson(String result) {
try {
if(result == null || result.isEmpty()){
Log.e("testYourJson", "Something went wrong!");
return;
}
Log.e("testYourJson", result);
JSONObject jsonObject = new JSONObject(result);
//Retrieve each Json object's fields
int time = jsonObject.optInt("time_use", -1);
Log.e("testYourJson", "time = " + time);
JSONObject request_id = jsonObject.getJSONObject("result_idcard");
Double confidence = request_id.optDouble("confidence", -222.0f);
int index1 = request_id.optInt("index1", -1);
int index2 = request_id.optInt("index2", -1);
// Show a little confidence ;-)
Log.e("testYourJson", "confidence = " + confidence);
Log.e("testYourJson", "index1 = " + index1);
Log.e("testYourJson", "index2 = " + index2);
} catch (JSONException e) {
Log.e("testYourJson", e.getMessage());
}
}
The only difference to Tenten's solution (which is correct) is that I have used optInt
and optDouble
because you can substitute optional values.
This works! I have tested it. But I suspect that the JSON you have is different to what you provide. Good Luck!
EDIT After taking a good long HARD look at the screen shot the OP has linked to his Question it appears as if index1
and index2
are actually Double
values! so the actual working code would need to compensate for that!
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.