DialogFragment - reference from db to MainActivity Android Studio - android

In my database when a condition is fulfilles i'd like to appear a AlertDialog popup. I've tried to do it in two ways, like this
dataBaseHandler
Cursor c = db.rawQuery(selectQuery, null);
if (c.moveToFirst()) {
result = c.getInt(c.getColumnIndex(KEY_COUPONS_TIMES_TO_USE))
-c.getInt(c.getColumnIndex(KEY_COUPONS_TIMES_USED));
if (result < 4) {
MainActivity alert = new MainActivity();
alert.showAlert();
}
}
MainActivity
public void showAlert() {
AlertDialog.Builder myAlert = new AlertDialog.Builder(this);
myAlert.setMessage("Text").create()
myAlert.show();
}
There's no red errors in the code but when a condition is fulfilled during using the application, critical error appears on the screen. Here's what console says
D/QUERY: UPDATE coupons SET times_used = times_used + 1 WHERE id=1
D/AndroidRuntime: Shutting down VM
W/dalvikvm: threadid=1: thread exiting with
uncaught exception(group=0xa4ccfb20)
[10-17 06:13:14.364 1579: 1724 D/]
HostConnection::get() New Host Connection established 0xb9986d90, tid 1724
E/AndroidRuntime: FATAL EXCEPTION: main
Process: promocje, PID: 2744 java.lang.NullPointerException
at android.content.ContextWrapper.getApplicationInfo
(ContextWrapper.java:152)
at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:103)
at android.app.AlertDialog.resolveDialogTheme(AlertDialog.java:143)
at android.app.AlertDialog$Builder.<init>(AlertDialog.java:360)
at promocje.MainActivity.showAlert(MainActivity.java:164)
at promocje.db.engine.DatabaseHandler.useCoupon
(DatabaseHandler.java:889)
at promocje.adapter.CouponListAdapter.useCoupon
(CouponListAdapter.java:166)
at promocje.adapter.CouponListAdapter$1$1.onFinish
(CouponListAdapter.java:144)
at android.os.CountDownTimer$1.handleMessage(CountDownTimer.java:118)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Application terminated.
I have tried also to this around in alternate way
dataBaseHandler
Cursor c = db.rawQuery(selectQuery, null);
if (c.moveToFirst()) {
result = c.getInt(c.getColumnIndex(KEY_COUPONS_TIMES_TO_USE))
- c.getInt(c.getColumnIndex(KEY_COUPONS_TIMES_USED));
if (result < 4) {
PopUpFragment popup = new PopUpFragment();
popup.show(FragmentManager manager, String tag);
}
New java file with Dialog Fragment
public class PopUpFragment extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("I'm a PopUp")
.setPositiveButton("Button 1", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// POSITIVE BUTTON
}
})
.setNegativeButton("Delete me", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// Create the AlertDialog object and return it
return builder.create();
}
}
Here i've got some problems with parameters in .show() method.
Any help would be appreciated!

Related

alertDialogBuilder crashes only when relaunching the APP

I have a "alertDialogBuilder" to rename an entry when a button is pressed. This works fine when the App is freshly opened. But If I press the back button (meaning the App is minimized and I am back at the Android home-screen), when I relaunch the App and press the button, this time the APP crashes. This happens every time and I have no idea how to debug this. I have checked the lifecycle and "onPause" and "onStop" are called when pressing the back button. But I don't see why that should be a problem.
Any ideas?
Here is the code where I launch the prompt dialogue in a helper class:
public void loadPromptInput(Context promptcontext, final OnOkGetText onOk, String InitialTxt) {
//pathText.setText("Prompt input");
LayoutInflater li = LayoutInflater.from(promptcontext);
View promptsView = li.inflate(R.layout.prompts_dialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder( promptcontext);
// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
final EditText userInput = (EditText) promptsView
.findViewById(R.id.editTextDialogUserInput);
userInput.setText("");
userInput.append(InitialTxt);
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
onOk.hereIsYouText(userInput.getText().toString());
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
// make the keyboard shown by default
alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com...., PID: 31622
android.view.WindowManager$BadTokenException: Unable to add window --
token android.os.BinderProxy#423c9940 is not valid; is your activity
running?
at android.view.ViewRootImpl.setView(ViewRootImpl.java:532)
at
android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:259)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:286)
at
com....myUtils.loadPromptInput(myUtils.java:71)
at
com....MainActivity$6.onReceive(MainActivity.java:557)
at
android.support.v4.content.LocalBroadcastManager.executePendingBroadcasts(LocalBroadcastManager.java:308)
at
android.support.v4.content.LocalBroadcastManager.access$000(LocalBroadcastManager.java:46)
at
android.support.v4.content.LocalBroadcastManager$1.handleMessage(LocalBroadcastManager.java:118)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5095)
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:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602)
at
com.zte.heartyservice.SCC.FrameworkBridge.main(FrameworkBridge.java:136)
at dalvik.system.NativeStart.main(Native Meth
od)
It would be helpful looking at your code to see where you call:
void loadPromptInput(Context promptcontext...
...most probably you are passing as parameter an instance of a context no more valid.
In any case before calling your method check if the activity is finishing:
//in a fragment
if(getActivity() != null && !getActivity().isFinishing()) {
loadPromptInput(getActivity()...
}
//in an activity
if(!isFinishing()) {
loadPromptInput(this...
}

NullPointerException while calling Intent for Setting

In my code, I displayed an alert dialog when the internet is not available. In that dialog I set a message "Internet Not Available." In that dialog I put two buttons 'Refresh' & 'Setting'. When the internet's gone & dialog comes, I clicked on Setting button it gives
This is the error (Logcat).
E: FATAL EXCEPTION: main Process:
com.appiphy.spacecomp.spinnerframework1, PID: 30424
java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.ActivityThread$ApplicationThread
android.app.ActivityThread.getApplicationThread()' on a null object
reference
at android.app.Activity.startActivityForResult(Activity.java:3823)
at android.app.Activity.startActivityForResult(Activity.java:3784)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:784)
at android.app.Activity.startActivity(Activity.java:4094)
at android.app.Activity.startActivity(Activity.java:4062)
at com.appiphy.spacecomp.spinnerframework1.activity.MainActivity$10.onClick(MainActivity.java:967)
at android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:157)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5297)
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:908)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)
startActivity(new Intent(android.provider.Settings.ACTION_SETTINGS));
I used above line to open Settings on a device.
How to solve the above error?
Try this:
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(new ContextThemeWrapper(this, android.R.style.Theme_Holo_Light_Dialog));
alertDialogBuilder
.setMessage("No internet connec" +
"" +
"tion on your device. Would you like to enable it?")
.setTitle("No Internet Connection")
.setCancelable(false)
.setPositiveButton(" Enable Internet ",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent dialogIntent = new Intent(android.provider.Settings.ACTION_SETTINGS);
dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(dialogIntent);
}
});
alertDialogBuilder.setNegativeButton(" Cancel ", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
I don't know whether your dialog is inside your activity or in some other utility class. If its outside the activity, then you should use context to start the intent. You can pass the context of the activity, and call
Intent intent = new Intent(android.provider.Settings.ACTION_SETTINGS));
mContext.startActivity(intent); mContext is the context which you will pass fro the activity.

Why does ad.show() fail?

I have this method in which i want to create an AlertDialog but when I call it the application stops working when it reaches ad.show
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is necessary for Traffic Finder");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
//mContext.startActivity(intent);
startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// Create Alert Dialog
AlertDialog ad= alertDialog.create();
// Showing Alert Message
ad.show();
}
I get this:
08-26 20:47:11.462 28940-29005/? E/AndroidRuntime﹕ FATAL EXCEPTION: IntentService[CoordinatesService]
Process: com.example.manos.trafficfinder, PID: 28940
android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
at android.view.ViewRootImpl.setView(ViewRootImpl.java:566)
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 com.example.manos.trafficfinder.GPSTracker.showSettingsAlert(GPSTracker.java:182)
at com.example.manos.trafficfinder.GeographicCoordinates.getLatitudeString(GeographicCoordinates.java:32)
at com.example.manos.trafficfinder.DataManagement.addPosition(DataManagement.java:116)
at com.example.manos.trafficfinder.CoordinatesService.onHandleIntent(CoordinatesService.java:28)
at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.os.HandlerThread.run(HandlerThread.java:61)
The Context passed to AlertDialog.Builder seems incorrect. Try YourClass.this instead of mContext.

How to resolve : android.view.WindowManager$BadTokenException - is your activity running?

I have an activity with lot of Dialogs for ex Dialog_1, Dialog_2, Dialog_3, I have implemented a WebView in one of the Dialogs lets say Dialog_2. When navigate through the Dialog's, first time the Dialog_2 with the WebView opens with no problem, but second time when I navigate to Dialog_3 and come back to Dialog_2 OR Dialog_1 to Dialog_2 and touch the WebView I get an error as mentioned bellow.
I have looked at Bad token exception but it does not work still using
if (! this.isFinishing()) {
showDialog(DIALOG_ADD_A_PERSON_BODY_MAP)
}
FATAL EXCEPTION: main
android.view.WindowManager$BadTokenException: Unable to add window -- token android.view.ViewRootImpl$W#41ec0fc8 is not valid; is your activity running?
FATAL EXCEPTION: main
android.view.WindowManager$BadTokenException: Unable to add window -- token android.view.ViewRootImpl$W#41ec0fc8 is not valid; is your activity running?
at android.view.ViewRootImpl.setView(ViewRootImpl.java:806)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:265)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:73)
at android.widget.ZoomButtonsController.setVisible(ZoomButtonsController.java:373)
at android.webkit.ZoomControlEmbedded.show(ZoomControlEmbedded.java:41)
at android.webkit.ZoomManager.invokeZoomPicker(ZoomManager.java:1728)
at android.webkit.WebViewClassic.startDrag(WebViewClassic.java:11645)
at android.webkit.WebViewClassic.handleTouchEventCommon(WebViewClassic.java:11170)
at android.webkit.WebViewClassic.onHandleUiTouchEvent(WebViewClassic.java:3225)
at android.webkit.WebViewClassic.onHandleUiEvent(WebViewClassic.java:3135)
at android.webkit.WebViewClassic.access$12000(WebViewClassic.java:278)
at android.webkit.WebViewClassic$PrivateHandler.dispatchUiEvent(WebViewClassic.java:13405)
at android.webkit.WebViewInputDispatcher.dispatchUiEvent(WebViewInputDispatcher.java:1078)
at android.webkit.WebViewInputDispatcher.dispatchUiEvents(WebViewInputDispatcher.java:1066)
at android.webkit.WebViewInputDispatcher.access$300(WebViewInputDispatcher.java:78)
at android.webkit.WebViewInputDispatcher$UiHandler.handleMessage(WebViewInputDispatcher.java:1392)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5365)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
The Dialog code is
case DIALOG_ADD_A_PERSON_BODY_MAP:
try {
LayoutInflater inflaterBodyMap = this
.getLayoutInflater();
final View inflatorBodyMap = inflaterBodyMap
.inflate(
R.layout.dialog_incident_window_body_map,
null);
bodyMapWebView = (WebView) inflatorBodyMap.findViewById(R.id.webView);
bodyMapWebView.getSettings().setJavaScriptEnabled(true);
//bodyMapWebView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
//bodyMapWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
bodyMapWebView.getSettings().setBuiltInZoomControls(true);
bodyMapWebView.getSettings().setSupportZoom(true);
bodyMapWebView.loadUrl("https://www.google.co.uk");
bodyMapWebView.addJavascriptInterface(new WebAppInterface(this), "Android");
builder.setTitle("Injured person");
builder.setView(inflatorBodyMap);
builder.setPositiveButton("Next",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
showDialog(DIALOG_ADD_A_PERSON_WAS_THE_PERSON_INJURED_ET);
wasThePersonInjured.setText(map_incident_addAPerson.get("InjuredNotes"));
}
});
builder.setNegativeButton("Back",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
showDialog(DIALOG_ADD_A_PERSON_WAS_THE_PERSON_INJURED);
}
});
return builder.create();
} catch (Exception e) {
e.printStackTrace();
}
How do I resolve this error. Your help and suggestions much appreciated.
This happens if your Activity has been killed due to some reason and window token of your activity has expired but you try and access it anyways. So to solve this put this in onPause:
#Override
protected void onPause() {
super.onPause();
if ((progress != null) && progress.isShowing()) {
progress.dismiss();
}
progress = null;
}

Android Radio Button Not selected giving error

I have a Android Radio button, i need to display the error message if the Radio button is not selected. Hence i included the below Java code, but its giving the below error.
Logcat ERROR:
07-12 16:00:08.139: E/AndroidRuntime(8282): Uncaught handler: thread main exiting due to uncaught exception
07-12 16:00:08.149: E/AndroidRuntime(8282): java.lang.NullPointerException
07-12 16:00:08.149: E/AndroidRuntime(8282): at com.example.triviality.QuizActivity$1.onClick(QuizActivity.java:67)
In the 67th Line the below sentence is there
String answerval = (String) answer.getText();
Please find the Partial Java Code:
butNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RadioGroup grp=(RadioGroup)findViewById(R.id.radioGroup1);
RadioButton answer=(RadioButton)findViewById(grp.getCheckedRadioButtonId());
String answerval = (String) answer.getText();
if (answerval == "")
{
AlertDialog.Builder alertDialog = new AlertDialog.Builder(QuizActivity.this);
alertDialog.setTitle(" ");
alertDialog.setIcon(R.drawable.wrong);
alertDialog.setMessage("Please select one Option");
alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
}
});
alertDialog.show();
}
}
You want to display error message when no RadioButton are selected.
If that's the case then grp.getCheckedRadioButtonId() will return -1 and hence answer will be null.
Then if you try to do answer.getText() you will get a NullPointerException because you are caling getText on a null object.
EDIT:
Replace
RadioButton answer=(RadioButton)findViewById(grp.getCheckedRadioButtonId());
String answerval = (String) answer.getText();
if (answerval == "")
with
if(grp.getCheckedRadioButtonId()==-1)

Categories

Resources