I have the following Utils class and I want to write a friendly toast to my users in the catch block like this:
catch (JSONException e){
Log.e(LOG_TAG, "String to JSON failed: " + e);
showToast(getActivity, "Test toast");
}
But the problem is how do I get my activity or application context? I tried this https://stackoverflow.com/a/23423970 but it doesn't work for me because I'm not sure where to get my context from? If I have to create a constructor of the Util class then it defeats the purpose of the Util class as I dont want to instantiate this class.
Here's my class:
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();
}
.....