我有一个运行良好的JsonParser。我可以将数据传递给PHP / MySQL,我可以检索数据。问题是在一些Android应用程序活动中我有多个AsyncTasks。
一个例子:
问题:
我需要获得成功的价值,但是当JsonParser收到第二个值(订阅 - 第一个值是checkSubscription)时,logcat会告诉我成功没有值,但成功有值。
logcat的:
W/System.err: org.json.JSONException: No value for success
响应:
11-25 17:22:37.346 22731-22909/com.package.package D/JSON Parser: result: {"subsuccess":0,"message":"Not Subscribed"}
11-25 17:22:37.346 22731-22909/com.package.package D/JSON Parser: {"success":1,"message":"Subscribed."}
第二行,标签成功的第一个值是我需要的。
JsonParser.class:
package com.package.package;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
public class JsonParser {
String charset = "UTF-8";
HttpURLConnection conn;
DataOutputStream wr;
StringBuilder result = new StringBuilder();
URL urlObj;
JSONObject jObj = null;
StringBuilder sbParams;
String paramsString;
String json = "";
public JSONObject makeHttpRequest(String url, String method,
HashMap<String, String> params) {
sbParams = new StringBuilder();
int i = 0;
for (String key : params.keySet()) {
try {
if (i != 0) {
sbParams.append("&");
}
sbParams.append(key).append("=")
.append(URLEncoder.encode(params.get(key), charset));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
i++;
}
if (method.equals("POST")) {
// request method is POST
try {
urlObj = new URL(url);
conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept-Charset", charset);
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
//request.setEntity(new BufferingRepresentation(request.getEntity());
conn.connect();
paramsString = sbParams.toString();
wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(paramsString);
wr.flush();
wr.close();
} catch (IOException e) {
e.printStackTrace();
}
} else if (method.equals("GET")) {
// request method is GET
if (sbParams.length() != 0) {
url += "?" + sbParams.toString();
}
try {
urlObj = new URL(url);
conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(false);
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept-Charset", charset);
conn.setConnectTimeout(15000);
conn.connect();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
//Receive the response from the server
InputStream in = new BufferedInputStream(conn.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
result.append(line + "\n");
}
json = result.toString();
Log.d("JSON Parser", "result: " + result.toString());
} catch (IOException e) {
e.printStackTrace();
}
conn.disconnect();
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
Log.d("JSON Parser Obj", jObj.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON Object
return jObj;
}
}
的AsyncTask:
class checkSubscription extends AsyncTask<String, String, String> {
int success = 0;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(DetailsActivity.this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected String doInBackground(String... args) {
String url_check = meuhelper.ip + meuhelper.url_check_subscription;
// Building Parameters
HashMap<String, String> params = new HashMap<>();
params.put("id", args[0]);
params.put("nome", args[1]);
params.put("email", args[2]);
JSONObject json = jsonParser.makeHttpRequest(url_check,
"POST", params);
try {
final int subscription = json.getInt(TAG_SUBSCRIPTION);
String strSuccess = Integer.toString(subscription);
Log.e("Check - ok", strSuccess);
if (subscription == 1) {
runOnUiThread(new Runnable() {
@Override
public void run() {
//subUnsub();
btnSub.setText(R.string.btnUnsubscribe);
Log.d("SUBSCRIPTION =====>", "1");
}
});
} else if (subscription == 0){
runOnUiThread(new Runnable() {
@Override
public void run() {
//subUnsub();
btnSub.setText(R.string.btnSubscribe);
Log.d("SUBSCRIPTION =====>", "0");
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (pDialog.isShowing())
pDialog.dismiss();
}
}
class registrarAssinatura extends AsyncTask<String, String, String> {
int regSuccess = 0;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(DetailsActivity.this);
pDialog.setCancelable(false);
pDialog.setMessage("Loading");
pDialog.show();
}
@Override
protected String doInBackground(String... args) {
String url_create = meuhelper.ip + meuhelper.url_create_subscription;
HashMap<String, String> params = new HashMap<>();
params.put("email", args[0]);
params.put("nome", args[1]);
JSONObject json = jsonParser.makeHttpRequest(url_create,
"POST", params);
if (json != null) {
try {
regSuccess = json.getInt(TAG_SUCCESS);
String x = json.getJSONObject(TAG_SUCCESS).get(TAG_SUCCESS).toString();
Log.d("WHAT", x);
message = json.getString(TAG_MESSAGE);
Log.d("Success", message);
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(String json) {
super.onPostExecute(json);
if (pDialog.isShowing())
pDialog.dismiss();
if (regSuccess == 1) {
runOnUiThread(new Runnable() {
@Override
public void run() {
//subUnsub();
Log.d("REGISTRAR =====>", "REGISTRADO");
}
});
} else if (regSuccess == 0) {
runOnUiThread(new Runnable() {
@Override
public void run() {
//subUnsub();
Log.d("FAIL TO REGISTER =====>", "REGISTRADO");
}
});
}
}
}
class cancelarAssinatura extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(DetailsActivity.this);
pDialog.setCancelable(false);
pDialog.setMessage("Loading");
pDialog.show();
}
@Override
protected String doInBackground(String... args) {
String url_cancel = meuhelper.ip + meuhelper.url_cancel_subscription;
HashMap<String, String> params = new HashMap<>();
params.put("email", args[0]);
params.put("nome", args[1]);
JSONObject json = jsonParser.makeHttpRequest(url_cancel,
"POST", params);
try {
int cancelSuccess = json.getInt(TAG_SUCCESS);
String strSuccess = Integer.toString(cancelSuccess);
Log.e("Cancel - ok", strSuccess);
if (cancelSuccess == 1) {
Log.e("Cancel - feito", strSuccess);
runOnUiThread(new Runnable() {
@Override
public void run() {
//subUnsub();
}
});
} else if (cancelSuccess == 0){
runOnUiThread(new Runnable() {
@Override
public void run() {
//subUnsub();
}
});
Log.e("Cancel - deu ruim", strSuccess);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (pDialog.isShowing())
pDialog.dismiss();
}
}
以上是同一活动中的3个AsyncTask。所有这些都运作良好,我无法得到成功的回应。
11-25 18:08:45.884 31070-31218/com.podchest.podchest D/JSON Parser: result: {"subsuccess":0,"message":"Not Subscribed"}
11-25 18:08:45.884 31070-31218/com.podchest.podchest D/JSON Parser: {"success":1,"message":"Subscribed."}
11-25 18:08:45.884 31070-31218/com.podchest.podchest D/JSON Parser Obj: {"message":"Not Subscribed","subsuccess":0}
11-25 18:08:45.884 31070-31218/com.podchest.podchest D/JSON TO STRING: {"message":"Not Subscribed","subsuccess":0}
以上JDev测试。那么,我没有收到JsonParser的第二个回复?
我整天都试图解决它。我已经阅读了Stack上的其他帖子,没有人帮助过我。 我希望你能帮助我。感谢。
答案 0 :(得分:1)
看起来这是JSONParser from my blog。
最近有人提到他们必须做一个小改动才能让它与多个请求一起工作,我的意思是用更改来更新我的博客。
更改是每次发出请求时初始化result
StringBuilder。
以下是包含修改后代码的完整类:
public class JsonParser {
String charset = "UTF-8";
HttpURLConnection conn;
DataOutputStream wr;
//StringBuilder result = new StringBuilder();
StringBuilder result; //modified - don't initialize here
URL urlObj;
JSONObject jObj = null;
StringBuilder sbParams;
String paramsString;
String json = "";
public JSONObject makeHttpRequest(String url, String method,
HashMap<String, String> params) {
sbParams = new StringBuilder();
int i = 0;
for (String key : params.keySet()) {
try {
if (i != 0) {
sbParams.append("&");
}
sbParams.append(key).append("=")
.append(URLEncoder.encode(params.get(key), charset));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
i++;
}
if (method.equals("POST")) {
// request method is POST
try {
urlObj = new URL(url);
conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept-Charset", charset);
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
//request.setEntity(new BufferingRepresentation(request.getEntity());
conn.connect();
paramsString = sbParams.toString();
wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(paramsString);
wr.flush();
wr.close();
} catch (IOException e) {
e.printStackTrace();
}
} else if (method.equals("GET")) {
// request method is GET
if (sbParams.length() != 0) {
url += "?" + sbParams.toString();
}
try {
urlObj = new URL(url);
conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(false);
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept-Charset", charset);
conn.setConnectTimeout(15000);
conn.connect();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
//Receive the response from the server
InputStream in = new BufferedInputStream(conn.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
result = new StringBuilder(); //added
while ((line = reader.readLine()) != null) {
result.append(line + "\n");
}
json = result.toString();
Log.d("JSON Parser", "result: " + result.toString());
} catch (IOException e) {
e.printStackTrace();
}
conn.disconnect();
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
Log.d("JSON Parser Obj", jObj.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON Object
return jObj;
}
}