Unable to add window (Android) - java

I've tried using the context from new AlertDialog.Builder(mContext) with the context from adapter constructor, i.e. mContext, with
My deleteComment() function:
private void deleteComment(int position) {
String currentUserObjectId = ParseUser.getCurrentUser().getObjectId();
ParseQuery<ParseObject> query = new ParseQuery<>("Yeet");
query.whereEqualTo(ParseConstants.KEY_OBJECT_ID, mYeets.get(position).getObjectId());
query.whereContains(ParseConstants.KEY_SENDER_ID, currentUserObjectId);
query.findInBackground((yeet, e) -> {
if (e == null) {
for (ParseObject yeetObject : yeet) {
if (yeetObject.getParseObject(ParseConstants.KEY_SENDER_AUTHOR_POINTER).getObjectId().equals((ParseUser.getCurrentUser().getObjectId()))) {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(mContext);
dialogBuilder.setTitle("Delete");
dialogBuilder.setMessage("Do you want to delete this Yeet?");
dialogBuilder.setPositiveButton("Yes", (dialog, which) -> {
// Iterate over all messages and delete them
for (ParseObject delete : yeet) {
delete.deleteInBackground();
/*this.adapter.remove(mYeets.get(position));*/
this.adapter.notifyDataSetChanged();
Toast.makeText(mContext, "Yeet deleted", Toast.LENGTH_SHORT).show();
}
});
dialogBuilder.setNegativeButton("No", (dialog, which) -> {
});
AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();
}
}
} else {
Log.e("Error", e.getMessage());
}
});
}
The exception:
android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
at android.view.ViewRootImpl.setView(ViewRootImpl.java:571)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:310)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:85)
at android.app.Dialog.show(Dialog.java:319)
at com.yitter.profile.UserProfileAdapter.lambda$deleteComment$115(UserProfileAdapter.java:286)
at com.yitter.profile.UserProfileAdapter.access$lambda$2(UserProfileAdapter.java:0)
at com.yitter.profile.UserProfileAdapter$$Lambda$3.done(Unknown Source)
at com.parse.ParseTaskUtils$2$1.run(ParseTaskUtils.java:116)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Here is a gist of my Adapter class if that helps:
https://gist.github.com/santafebound/bf496bbfee2da81b60312207121853b0

Make sure mContext is an Activity.
Calling new AlertDialog.Builder(activity.getApplicationContext()) will throw this same error, but new AlertDialog.Builder(activity) works fine when calling show().
Looks like AlertDialog is designed to use context from visible elements only, as an Activity, and not from an ApplicationContext, Service, etc.

Related

google tells me that my app crashes on (only) Google Pixel 2 (virtuel)

I'm trying to publish my app in google play console.
But it tells me that it crashes on Google Pixel 2 (virtuel) (works on the 9 others) with 2 errors (very similar)
Google Pixel 2 (virtuel) 1080x1920 Android 12 (SDK 31) - x86_64 en_US
Error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.activity.result.ActivityResultLauncher.launch(java.lang.Object)' on a null object reference
Detail:
FATAL EXCEPTION: Thread-2
Process: xxxxxxxx, PID: 8724
java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.activity.result.ActivityResultLauncher.launch(java.lang.Object)' on a null object reference
at xxxxxxxx.models.StockInputDialog.lambda$init$9$xxxxxxxx-models-StockInputDialog(StockInputDialog.java:417)
at xxxxxxxx.models.StockInputDialog$$ExternalSyntheticLambda9.onClick(Unknown Source:2)
at android.view.View.performClick(View.java:7441)
at android.view.View.performClickInternal(View.java:7418)
at android.view.View.access$3700(View.java:835)
at android.view.View$PerformClick.run(View.java:28676)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at androidx.test.espresso.base.Interrogator.loopAndInterrogate(Interrogator.java:10)
at androidx.test.espresso.base.UiControllerImpl.loopUntil(UiControllerImpl.java:7)
at androidx.test.espresso.base.UiControllerImpl.loopUntil(UiControllerImpl.java:1)
at androidx.test.espresso.base.UiControllerImpl.injectMotionEvent(UiControllerImpl.java:5)
at androidx.test.espresso.action.MotionEvents.sendUp(MotionEvents.java:6)
at androidx.test.espresso.action.MotionEvents.sendUp(MotionEvents.java:1)
at androidx.test.espresso.action.Tap.sendSingleTap(Tap.java:5)
at androidx.test.espresso.action.Tap.-$$Nest$smsendSingleTap(Unknown Source:0)
at androidx.test.espresso.action.Tap$1.sendTap(Tap.java:1)
at androidx.test.espresso.action.GeneralClickAction.perform(GeneralClickAction.java:4)
at androidx.test.espresso.ViewInteraction$SingleExecutionViewAction.perform(ViewInteraction.java:2)
at androidx.test.espresso.ViewInteraction.doPerform(ViewInteraction.java:21)
at androidx.test.espresso.ViewInteraction.-$$Nest$mdoPerform(Unknown Source:0)
at androidx.test.espresso.ViewInteraction$1.call(ViewInteraction.java:6)
at androidx.test.espresso.ViewInteraction$1.call(ViewInteraction.java:1)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loopOnce(Looper.java:201)
at android.os.Looper.loop(Looper.java:288)
at android.app.ActivityThread.main(ActivityThread.java:7839)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
My code is explained (and the reason why) startActivityForResult migration, call registerForActivityResult outside activity, and simplified to the maximum:
public class StockActivity extends AppCompatActivity implements DialogCloseListener {
private ActivityResultLauncher<Intent> stockGalleryActivityResultLauncher;
private ActivityResultLauncher<Intent> stockCameraActivityResultLauncher;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
stockCameraActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
result -> {
// code
});
stockGalleryActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
result -> {
// code
});
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (id == R.id.action_add) {
mStockInputDialog = new StockInputDialog(this, stockCameraActivityResultLauncher, stockGalleryActivityResultLauncher,);
return true;
} else {
return super.onOptionsItemSelected(item);
}
}
}
public class StockInputDialog {
private final Context mContext;
private AlertDialog mInputDialog;
private ActivityResultLauncher<Intent> stockCameraActivityResultLauncher;
private ActivityResultLauncher<Intent> stockGalleryActivityResultLauncher;
public StockInputDialog(Context context, ActivityResultLauncher<Intent> pStockCameraActivityResultLaunchera, ActivityResultLauncher<Intent> pStockGalleryActivityResultLauncher) {
mContext = context;
stockCameraActivityResultLauncher = pStockCameraActivityResultLaunchera;
stockGalleryActivityResultLauncher = pStockGalleryActivityResultLauncher;
LayoutInflater li = LayoutInflater.from(this.mContext);
mPromptsView = li.inflate(R.layout.text_input_stock, null);
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this.mContext);
alertDialogBuilder.setView(mPromptsView);
final ImageButton imgButtonCam = mPromptsView.findViewById(R.id.addCam);
final ImageButton imgButtonGal = mPromptsView.findViewById(R.id.addGal);
imgButtonCam.setOnClickListener(view -> {
Uri uri = FileProvider.getUriForFile(mContext, "fr.foo.bar.provider",
new Product(Consts.TEMP_NUM).getIMGPathCacheFile(mContext));
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
stockCameraActivityResultLauncher.launch(intent); <= ERROR
});
imgButtonGal.setOnClickListener(view -> {
stockGalleryActivityResultLauncher.launch(new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)) <= ERROR
});
}
}
The 2 errors correspond to the 2 launch()
What I don't understand is that I'm using this same principle elsewhere in the application without an error being raised.
No more crashes when testing the "nullity" of the launchers (#Abdo21 2nd answer).
imgButtonCam.setOnClickListener(view -> {
Uri uri = FileProvider.getUriForFile(mContext, "fr.novazur.donteat.provider",
new Product(Consts.TEMP_NUM).getIMGPathCacheFile(mContext));
if (stockCameraActivityResultLauncher != null)
stockCameraActivityResultLauncher.launch(uri);
else
Toast.makeText(mContext, R.string.featureAbsent, Toast.LENGTH_LONG).show();
});
imgButtonGal.setOnClickListener(view -> {
if (stockGalleryActivityResultLauncher != null)
stockGalleryActivityResultLauncher.launch("image/*");
else
Toast.makeText(mContext, R.string.featureAbsent, Toast.LENGTH_LONG).show();
});
That's what I should have done from the start. I'm a little sorry for not having thought of it, it's so obvious. I guess it's related to the creation of the AlertDialog which should not allow immediate access to the launchers. What I don't understand in this case is why only the Pixel 2 crashes, but problem seems to be solved for the moment. Thanks all.

How to show Alert Dialog box in Service android

Iam new to android,I want to show alert dialog box in service,I used two methods as shown below
First one without Layout
AlertDialog.Builder builder = new AlertDialog.Builder(MyService.this);
builder.setTitle("Test dialog");
builder.setMessage("Content");
builder.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
System.exit(0);
}
});
AlertDialog alert = builder.create();
alert.getWindow().setType(WindowManager.LayoutParams.TYPE_TOAST);
alert.show();
but iam getting error like this as shown as below
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.materialdialoginservice, PID: 25846
android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?
at android.view.ViewRootImpl.setView(ViewRootImpl.java:993)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:387)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:95)
at android.app.Dialog.show(Dialog.java:344)
at com.example.materialdialoginservice.MyService$3.run(MyService.java:98)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:224)
at android.app.ActivityThread.main(ActivityThread.java:7561)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:995)
Second one with Layout
AlertDialog.Builder builder = new AlertDialog.Builder(MyService.this);
View view = View.inflate(context, R.layout.activity_layout_view, null);
AlertDialog dialog = builder.create();
dialog.setView(view);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {//8.0 new features
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY - 1);
} else {
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_TOAST);
}
dialog.show();
Window dialogWindow = dialog.getWindow();
dialogWindow.setGravity(Gravity.CENTER);
I am getting error like this,
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.textstuff, PID: 27418
java.lang.RuntimeException: Unable to start service com.example.textstuff.MyService#134fed7 with Intent { cmp=com.example.textstuff/.MyService }: android.view.WindowManager$InvalidDisplayException: Unable to add window android.view.ViewRootImpl$W#124c071 -- the specified display can not be found
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:4196)
at android.app.ActivityThread.access$2000(ActivityThread.java:233)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1946)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:224)
at android.app.ActivityThread.main(ActivityThread.java:7561)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:995)
Added permission in Manifest file like this
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<uses-permission android:name="android.permission.SYSTEM_OVERLAY_WINDOW"/>
Just remove :
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // 8.0 new features
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY - 1);
} else {
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_TOAST);
}
And try :
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT)
UPDATE
In Android 6.0 Marshmallow, the user must explicitly allow your app to "draw over other apps". So add
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
Now in marshmallow use this method to handle runtime permission:
#TargetApi(Build.VERSION_CODES.M)
private void handleOverlaySettings() {
final Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + getPackageName()));
try {
startActivityForResult(intent, 11);
} catch (ActivityNotFoundException e) {
Log.e(TAG, e.getMessage());
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 11:
final boolean overlayEnabled = Settings.canDrawOverlays(this);
// handle the remaining logic
break;
}
}
Now show the dialog in service as below:
final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this, R.style.AppTheme_MaterialDialogTheme);
dialogBuilder.setTitle(R.string.dialog_title);
dialogBuilder.setMessage(R.string.dialog_message);
dialogBuilder.setNegativeButton(R.string.btn_back,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}
);
final AlertDialog dialog = dialogBuilder.create();
final Window dialogWindow = dialog.getWindow();
final WindowManager.LayoutParams dialogWindowAttributes = dialogWindow.getAttributes();
// Set fixed width (350dp) and WRAP_CONTENT height
final WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(dialogWindowAttributes);
lp.width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 350, getResources().getDisplayMetrics());
lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
dialogWindow.setAttributes(lp);
// Set to TYPE_SYSTEM_ALERT so that the Service can display it
dialogWindow.setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
dialogWindowAttributes.windowAnimations = R.style.DialogAnimation;
dialog.show();
All set now this solution should work. Good luck

DialogFragment crashes when calling show()

I want to display a simple DialogFragment within a Fragment, but it crashes every time the show() method is called.
It either crashes back to the MainActivity or it throws me a NullPointer Exception that does not seem to be related to the crash directly. I think Logcat swallows the actual problem somehow.
Here is the call and the DialogFragment subclass:
private void showCheatingDialog() {
DialogFragment newFragment = new CheatingDialogFragment();
newFragment.show(getChildFragmentManager(), "CheatingDialogFragment");
}
#Override
public void onCheatingPositiveClick(DialogFragment dialog) {
try {
client.puzzleDone(BLUFF);
} catch(IOException ex) {
Log.e("tiles", ex.toString());
Toast.makeText(getActivity(), "Connection to the server failed", Toast.LENGTH_LONG).show();
Intent intent = new Intent(getActivity(), MainActivity.class);
startActivity(intent);
}
}
#Override
public void onCheatingCancelClick(DialogFragment dialog) {
// do nothing
}
public class CheatingDialogFragment extends DialogFragment {
public interface CheatingDialogListener {
public void onCheatingPositiveClick(DialogFragment dialog);
public void onCheatingCancelClick(DialogFragment dialog);
}
CheatingDialogListener listener;
// Override the Fragment.onAttach() method to instantiate the CheatingDialogListener
#Override
public void onAttach(Context context) {
super.onAttach(context);
// Verify that the host activity implements the callback interface
try {
// Instantiate the CheatingDialogListener so we can send events to the host
listener = (CheatingDialogListener) context;
} catch (ClassCastException e) {
// The activity doesn't implement the interface, throw exception
throw new ClassCastException(getActivity().toString()
+ " must implement CheatingDialogListener");
}
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Build the dialog and set up the button click handlers
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.cheating_dialog_fragment)
.setPositiveButton(R.string.cheating_dialog_positive, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Send the positive button event back to the host activity
listener.onCheatingPositiveClick(CheatingDialogFragment.this);
}
})
.setNegativeButton(R.string.cheating_dialog_cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Send the negative button event back to the host activity
listener.onCheatingCancelClick(CheatingDialogFragment.this);
}
});
return builder.create();
}
}
Here's the exception Logcat shows:
2021-06-17 08:45:04.952 7095-7095/com.example.se2_gruppenphase_ss21 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.se2_gruppenphase_ss21, PID: 7095
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.se2_gruppenphase_ss21.networking.AvailableRoom.getName()' on a null object reference
at com.example.se2_gruppenphase_ss21.menu.RoomFragment.onCreateView(RoomFragment.java:86)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2698)
at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:320)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1187)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1356)
at androidx.fragment.app.FragmentManager.moveFragmentToExpectedState(FragmentManager.java:1434)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1497)
at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:2625)
at androidx.fragment.app.FragmentManager.dispatchActivityCreated(FragmentManager.java:2577)
at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:247)
at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:541)
at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:210)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1435)
at android.app.Activity.performStart(Activity.java:8024)
at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3475)
at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:221)
at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:201)
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:173)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)

Android - java.lang.RuntimeException: Could not read input channel file descriptors from parcel

I'm getting a FATAL EXCEPTION: main when I run the app. It run first but for a few seconds it crash.
Here is my Logcat :
java.lang.RuntimeException: Could not read input channel file descriptors from parcel.
at android.view.InputChannel.nativeReadFromParcel(Native Method)
at android.view.InputChannel.readFromParcel(InputChannel.java:148)
at android.view.IWindowSession$Stub$Proxy.addToDisplay(IWindowSession.java:752)
at android.view.ViewRootImpl.setView(ViewRootImpl.java:527)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:282)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:85)
at android.app.Dialog.show(Dialog.java:298)
at android.app.AlertDialog$Builder.show(AlertDialog.java:993)
at com.mobext.shakeys.ActivityMain$ProcessData.onPostExecute(ActivityMain.java:545)
at com.mobext.shakeys.ActivityMain$ProcessData.onPostExecute(ActivityMain.java:212)
at android.os.AsyncTask.finish(AsyncTask.java:636)
at android.os.AsyncTask.access$500(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Inside my ActivityMain.java:542 in alrt.show() this is where the logcat point it:
#Override
protected void onPostExecute(Boolean result) {
Log.i(TAG, "onPostExecute");
super.onPostExecute(result);
if(result){
Log.i(TAG, "TASK IS DONE");
try {
PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
app.saveToLastPref(ActivityMain.this, app.PREFS_PREV_VERSION, pInfo.versionName);
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent intent = new Intent(getApplicationContext(), ActivityMenuPage.class);
startActivity(intent);
finish();
}else{
ActivityMain.this.deleteDatabase("DBSHAKEYS");
Builder alrt = new AlertDialog.Builder(mcontext);
alrt.setMessage("Update failed. Please check your internet connection and try again.");
alrt.setPositiveButton("Okay", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alrt.show();
}
}
}
And in ActivityMain.java:212 :
public class ProcessData extends AsyncTask<Void, Void, Boolean>
I think Builder is your custom class that you are using now to show the AlertDialog.
Here is what may happened
The onPostExecute() method was called automatically after your some background process was finished executing. And then It tried to use the Builder class which may be currently being used by another process and still running in the memory.
How can it be solved then ?
Review your code and see if the dialog is already being shown using
Builder class.
Simply change this line
Builder alrt = new AlertDialog.Builder(mcontext); to normally AlertDialog.Builder alrt = new AlertDialog.Builder(mcontext);
and see if this works.

Layout inflater is null

Can someone help me?
I don't know why have I javaNullExepction in LayoutInflater.Here is my code :
This code is in fragment :
ServiceManager.getInstance().getCampaign( new Callback <Campaign>() {
#Override
public void success(Campaign campaign, Response response) {
campaigns = campaign;
adapter = new RecyclerCampaignAdapter(getActivity(), campaign);
recyclerView.setAdapter(adapter);
recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(getActivity()).marginProvider(adapter).showLastDivider().build());
adapter.notifyDataSetChanged();
if (progressBar.isShown()) {
progressBar.setVisibility(View.INVISIBLE);
}
}
#Override
public void failure(RetrofitError retrofitError) {
Toast.makeText(getActivity(), "Failed" + retrofitError, Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
});
here is code in my adapter :
public RecyclerCampaignAdapter (Activity activity, Campaign campaignList) {
this.activity = activity;
this.campaignList = campaignList;
this.inflater= LayoutInflater.from(activity);
}
I think getActivity() == null I don't know how can I fix it.
java.lang.NullPointerException
at android.view.LayoutInflater.from(LayoutInflater.java:212)
at tr.org.yyd.yeryuzudoktorlari.adapter.RecyclerCampaignAdapter.(RecyclerCampaignAdapter.java:38)
at tr.org.yyd.yeryuzudoktorlari.fragment.CampaignFragment$1.success(CampaignFragment.java:69)
at tr.org.yyd.yeryuzudoktorlari.fragment.CampaignFragment$1.success(CampaignFragment.java:65)
at retrofit.CallbackRunnable$1.run(CallbackRunnable.java:45)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5756)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
at dalvik.system.NativeStart.main(Native Method)
EDIT:
I use replace method on frgment transaction when user clicks on an item from menu.So CampaignFragment works okey when the user clicks in first time but it crashes when user clicks again while it is still on.
If I change into another fragment and come back to CampaginFragment there is no crash.
The answer just that.I don't know how that fix it but it worked.It's just a control.
if (getActivity() != null) {
adapter = ....

Categories