Nicky Manali Nicky Manali - 4 months ago 19
JSON Question

how to check if url exist or not to fetch json data

I am fetching json data for different book_name & its working fine.but in case if book does not exists my app get collapse.I know that JsonObject fetching null data but i want it to do something rather than collapse when book not found. My code is:
`

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 help me.
`

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;
}


}`

Answer
// get json string from url

JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);
if(json == null){
    //url parsing didn't work
    return;
}