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

最佳答案

只需在您的方法中添加一个上下文... public static JSONObject getJSONfromURL(String url, Context context) { Toast.makeText(context...);},然后从一个活动或其他上下文中调用它...从一个活动:getJSONfromURL(url, this);,因为这可能不会完成UIThread,所以它将位于线程或AsyncTask,如果它在Activity中,则可以执行以下操作:getJSONfromURL(url, MyHappyActivity.this);另外,请考虑使用应用程序而不是Activity ... Activity中的getApplicationContext()将为您提供上下文:getJSONfromURL(url, getApplicationContext());如果从在一个活动中。

07-24 09:48
查看更多