我有一个JSON助手类。如果出现错误而不是强制关闭,我一直试图显示Toast消息。问题是,因为这是一个帮助类,它没有上下文,也不能显示Toast。任何人都可以帮助引导我如何传递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;
}
}
答案 0 :(得分:1)
刚刚为您的方法添加了一个上下文... public static JSONObject getJSONfromURL(String url, Context context) { Toast.makeText(context...);}
,然后从一个Activity或其他上下文中调用它...来自一个活动:getJSONfromURL(url, this);
,因为这可能不是UIThread,那么它将在一个线程或AsyncTask中,如果它在一个Activity中,你可以这样做:getJSONfromURL(url, MyHappyActivity.this);
另外,考虑使用Application而不是Activity ...来自Activity的getApplicationContext()会给你该上下文:getJSONfromURL(url, getApplicationContext());
如果从活动中调用。