Ich versuche, eine anzuzeigen, wenn eine Ausnahme in meiner Dienstprogrammklasse ausgelöst wird.Anzeigen der Snackbar aus der Dienstprogrammklasse
Utils.class
public class Utils {
private static String LOG_TAG = Utils.class.getSimpleName();
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 (Exception e)
{
runError(); // <-- The method that displays the Snackbar
}
return batchOperations;
}
Und jetzt hier ist die Methode, die zur Anzeige versucht die SnackBar
:
private static void runError()
{
Snackbar.make(this.findViewById(android.R.id.content), "OOPS that's an error :/", Snackbar.LENGTH_LONG).show();
}
Nun das Problem ist: Ich bin nicht in der Lage context
zu bekommen Anruf SnackBar
. Ich habe versucht zu ersetzen this
mit:
getContext()
getActivity()
getApplicationContext()
Da keiner dieser Arbeit habe ich versucht, eine Application-Klasse zu schaffen global Kontext zu erhalten.
public class StockMain extends Application
{
private static StockMain instance;
public static StockMain getInstance() {
return instance;
}
public static Context getContext(){
return instance;
// or return instance.getApplicationContext();
}
@Override
public void onCreate() {
instance = this;
super.onCreate();
}
}
Und versucht zu ändern, wobei das Verfahren runError()
zu:
private static void runError()
{
Snackbar.make(StockMain.getContext().findViewById(android.R.id.content), "OOPS that's an error :/", Snackbar.LENGTH_LONG).show();
}
Leider, die nicht so gut funktionieren! Also, wie behebt man dieses Problem?
Cant Sie speichern einen statischen Kontext oder einen Blick irgendwo und es verwenden? –
Rufen Sie die Methode "quoteJsonToContentVals" in einer beliebigen Aktivität auf? –
@ ρяσѕρєяK Ja, ich rufe es an, und ich erhalte Ergebnisse, ich bin in der Lage, Log zu loggen, wenn eine Ausnahme auftritt, – OBX