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になります(その場合)がアクティビティ内にある場合は、これを行うことができます。getJSONfromURL(url, MyHappyActivity.this);また、アクティビティの代わりにアプリケーションを使用することを検討してください...アクティビティからのgetApplicationContext()は、そのコンテキストを提供しますgetJSONfromURL(url, getApplicationContext());。アクティビティ内から呼び出された場合。

于 2012-06-21T21:41:12.177 に答える