This method seems pretty great, however, when using it with production code and using it for an object that might be null seems unwieldy. Consider my example:
public class ShowDialogTask extends AsyncTask<Void, Void, Void> {
private WeakReference<Context> contextReference;
public ShowDialogTask(Context context) {
contextReference = new WeakReference<>(context);
}
@Override
protected Void doInBackground(Void... voids) {
...do a long running task...
return null;
}
@Override
protected void onPostExecute(Void void) {
super.onPostExecute(void);
Context ctx = Objects.requireNonNull(contextReference.get(), "Context became null");
AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
builder.setTitle("Dialog title");
builder.setCancelable(true);
builder.create().show();
}
In the onPostExecute() function, I set a local variable object ctx using the Objects.requireNonNull method. My problem with that is that it's a bit difficult for me to reproduce making the contextReference.get() equal to null, and it can definitely possibly happen in production.
I would like to know the best way to use this functionality for production purposes.
My first idea would be to wrap the code in a try-catch, but doing that everywhere seems like bad programming:
try {
Context ctx = Objects.requireNonNull(contextReference.get(), "Context became null");
AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
builder.setTitle("Dialog title");
builder.setCancelable(true);
builder.create().show();
} catch (Throwable t) {
Log.d(TAG, t.getMessage());
}