【发布时间】:2016-11-02 00:18:30
【问题描述】:
我有以下 Utils 类,我想在 catch 块中为我的用户写一个友好的祝酒词,如下所示:
catch (JSONException e){
Log.e(LOG_TAG, "String to JSON failed: " + e);
showToast(getActivity, "Test toast");
}
但问题是如何获取我的活动或应用程序上下文? 我试过这个https://stackoverflow.com/a/23423970 但它对我不起作用,因为我不确定从哪里获得我的上下文?如果我必须创建 Util 类的构造函数,那么它就违背了 Util 类的目的,因为我不想实例化这个类。
这是我的课:
public class Utils {
public static boolean showPercent = true;
public static ArrayList quoteJsonToContentVals(String JSON){
ArrayList<ContentProviderOperation> batchOperations = new ArrayList<>();
JSONObject jsonObject = null;
JSONArray resultsArray = null;
try{
jsonObject = new JSONObject(JSON);
if (jsonObject != null && jsonObject.length() != 0){
jsonObject = jsonObject.getJSONObject("query");
int count = Integer.parseInt(jsonObject.getString("count"));
if (count == 1){
jsonObject = jsonObject.getJSONObject("results")
.getJSONObject("quote");
batchOperations.add(buildBatchOperation(jsonObject));
} else{
resultsArray = jsonObject.getJSONObject("results").getJSONArray("quote");
if (resultsArray != null && resultsArray.length() != 0){
for (int i = 0; i < resultsArray.length(); i++){
jsonObject = resultsArray.getJSONObject(i);
batchOperations.add(buildBatchOperation(jsonObject));
}
}
}
}
} catch (JSONException e){
Log.e(LOG_TAG, "String to JSON failed: " + e);
showToast(getActivity, "Test toast");
}
return batchOperations;
}
public static void showToast(Context context, String text) {
Toast.makeText(context, text, Toast.LENGTH_LONG).show();
}
.....
【问题讨论】:
-
您需要一个有效的上下文来显示
Toast。
标签: android android-fragments toast