我正在提取不同book_name的json數據&其工作正常。但如果書不存在,我的應用程序崩潰。我知道JsonObject獲取空數據,但我當書未找到時,希望它做某件事而不是崩潰。我的代碼是: `如何檢查url是否存在或取消json數據
public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
final String TAG = "AsyncTaskParseJson.java";
// set your json string url here
Intent po=getIntent();
String bok=po.getStringExtra("bookname");
String newName = bok.replaceAll("\\s", "%20");
String yourJsonStringUrl = "http://www.bsservicess.com/photoUpload/star_avg.php?bookName="+newName;
// contacts JSONArray
JSONArray dataJsonArr = null;
@Override
protected void onPreExecute() {}
protected String doInBackground(String... arg0) {
if(exists(yourJsonStringUrl)) {
try {
JSONParser jParser = new JSONParser();
// get json string from url
JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);
// get the array of users
dataJsonArr = json.getJSONArray("result");
JSONObject c = dataJsonArr.getJSONObject(0);
// na=c.getString("avg");
ratenumS = c.getString("avg");
numberS = c.getString("num");
starts = Float.parseFloat(c.getString("avg"));
} catch (JSONException e) {
e.printStackTrace();
}
}else{
starts=0;
numberS="0";
}
return null;
}
@Override
protected void onPostExecute(String strFromDoInBg) {
super.onPostExecute(strFromDoInBg);
ratenum.setText(ratenumS);
number.setText("("+numberS+")");
netRate.setRating(starts);
// Toast.makeText(mybookview.this, Float.toString(starts),Toast.LENGTH_SHORT).show();
}
Plz幫助我。 `
public JSONObject getJSONFromUrl(String url) {
// make HTTP request
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
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();
json = sb.toString();
} catch (Exception e) {
Log.e(TAG, "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e(TAG, "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}`
你可以發佈你的'JSONParser'類嗎? – Bill
okk我發表在mty編輯問題 –