I am trying to show a Toast when my API-Request doesn't work due to No-Internet-Connection. To start of easy, I just tried to show a Toast as soon as the try-block fails and then I want to show the Toast in the catch-block. I tried the approach from developer.android.com but I can't even start the Application.
My code in the catch-block is this:
} catch {
Context context = getApplicationContext();
Toast.makeText(context, "No Internet Connection.", Toast.LENGTH_SHORT).show();
}
I seem to have problems with the getApplicationContext()
Method, because this is highlighted red.
It seems to be a problem because I am using this Inside a Fragment. I read something with using Activity activity = getActivity()
but when trying to insert this activity
as the context in the makeText()
Method, I get this Error Message:
E/AndroidRuntime: FATAL EXCEPTION: Thread-4
Process: com.example.dhapp, PID: 16158
java.lang.NullPointerException: Can't toast on a thread that has not called Looper.prepare()
at com.android.internal.util.Preconditions.checkNotNull(Preconditions.java:157)
at android.widget.Toast.getLooper(Toast.java:287)
at android.widget.Toast.<init>(Toast.java:256)
at android.widget.Toast.makeText(Toast.java:891)
at android.widget.Toast.makeText(Toast.java:879)
at com.example.dhapp.SearchFragment$apiThread.run(SearchFragment.java:112)
Any tips on how I get this to work? Thanks a lot in Advance!