I have a JSON helper class. I have been trying to to display a Toast message if there was an error instead of just having it force closed. Problem is, since this is a helper class, it has no Context and cant display Toast. Can anyone please help steer me in the right direction on how to pass Context?
public class JSONfunction {
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONObject json = null;
// HTTP Post
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("JSONfunction", "Error converting internet " + 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();
} catch (Exception e) {
Log.e("JSONfunction", "Error converting result " + e.toString());
}
try {
json = new JSONObject(result);
} catch (JSONException e) {
Log.e("JSONfunction", "Error parsing data " + e.toString());
}
return json;
}
public static JSONArray getJSONArray(String string) {
// TODO Auto-generated method stub
return null;
}
public static String getString(String string) {
// TODO Auto-generated method stub
return null;
}
}
Just added a Context to your method…
public static JSONObject getJSONfromURL(String url, Context context) { Toast.makeText(context...);}and then call it from an Activity or other context… From an activity:getJSONfromURL(url, this);since this will likely not be done an UIThread, then it’ll be in a thread or AsyncTask, if that is inside an Activity, you can do this:getJSONfromURL(url, MyHappyActivity.this);Also, consider using the Application instead of the Activity… getApplicationContext() from an Activity will give you that context:getJSONfromURL(url, getApplicationContext());if called from within an Activity.