gpt4 book ai didi

android - 将 Context 传递给辅助类以在 Try/Catch 时显示 Toast

转载 作者:行者123 更新时间:2023-11-30 04:08:54 29 4
gpt4 key购买 nike

我有一个 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;
}
}

最佳答案

刚刚在您的方法中添加了一个 Context...public static JSONObject getJSONfromURL(String url, Context context) { Toast.makeText(context...); 然后从 Activity 中调用它或其他上下文...来自 Activity :getJSONfromURL(url, this); 因为这可能不会在 UIThread 中完成,所以它将在线程或 AsyncTask 中,如果它在Activity,你可以这样做:getJSONfromURL(url, MyHappyActivity.this); 另外,考虑使用 Application 而不是 Activity ... Activity 的 getApplicationContext() 会给你那个上下文:getJSONfromURL(url, getApplicationContext()); 如果从 Activity 中调用。

关于android - 将 Context 传递给辅助类以在 Try/Catch 时显示 Toast,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11147128/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com