1

我有一个 JSON 助手类。如果出现错误,我一直在尝试显示 Toast 消息,而不是强制关闭它。问题是,由于这是一个辅助类,它没有上下文并且无法显示 Toast。任何人都可以帮助我在如何传递上下文方面朝着正确的方向前进吗?

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

1 回答 1

1

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

于 2012-06-21T21:41:12.177 回答