Shared Preference for alert dialog is making my application non responsive - android

I have a bit of usual problem here. I have a alertdialog that launches as soon as my application has been launched and as soon as the user clicks the ok button that dialog will never display again unless it has been deleted and installed again. It works when I try it on my emulator for the first time and by first time I mean when I launch the application as soon I am done writing the code for the shared preference for the alertdialog. But when I close the emulator and launch my application again, the alertdialog doesn't display and my application doesn't respond to anything. I do not know if this happened to anybody before and I do not know if this was suppose to happen. Can somebody help me understand what is going and why application doesn't respond to anything after the first time the application has been launched. Also my logcat did not display any errors either.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final SharedPreferences settings = getSharedPreferences("pref_name", 0);
boolean installed = settings.getBoolean("installed", false);
if(!installed){
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("Title");
alertDialog.setIcon(R.drawable.ic_launcher);
alertDialog.setAdapter(new MyAdapter(), null);
alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("installed", true);
editor.commit();
}
});
alertDialog.show();
final EditText et = (EditText) findViewById(R.id.editText1);
Button getAnswer = (Button) findViewById(R.id.button1);
getAnswer.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (et.getText().toString().length()==0) {
Toast.makeText(getApplicationContext(),"Can't Be Blank!",Toast.LENGTH_LONG).show();
}else{
EditText et = (EditText) findViewById(R.id.editText1);
String searchTerm = et.getText().toString().trim();
Intent in = new Intent(MainActivity.this, ListView.class);
in.putExtra("TAG_SEARCH", searchTerm);
startActivity(in);
}
}
});
}
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
}}

You need to move this code
final EditText et = (EditText) findViewById(R.id.editText1);
Button getAnswer = (Button) findViewById(R.id.button1);
getAnswer.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (et.getText().toString().length()==0) {
Toast.makeText(getApplicationContext(),"Can't Be Blank!",Toast.LENGTH_LONG).show();
}else{
EditText et = (EditText) findViewById(R.id.editText1);
String searchTerm = et.getText().toString().trim();
Intent in = new Intent(MainActivity.this, ListView.class);
in.putExtra("TAG_SEARCH", searchTerm);
startActivity(in);
}
}
});
}
out of the if part of your code. As Shobhit is saying, this is never getting run the next time you run your app. It only runs if installed is false which is never true after the first run.
Edit-Avoid window leak errors with the Dialog
You can always check if the Dialog is open with dialog.isShowing() and close the Dialog if returns true before the Activity is destroyed or something (another Activity) comes on top. You can do this in onPause().
#Override
public void onPause()
{
if (dialog != null && dialog.isShowing())
{
dialog.dismiss();
super.onPause();
}
}

Move this code into an AsyncTask. It's not good practice to do any work in the onCreate(). The OnCreate() is only for creating the Activity. Start your AsyncTask in the OnResume() Look at this activity-life-cycle Here is the AsyncTask
final SharedPreferences settings = getSharedPreferences("pref_name", 0);
boolean installed = settings.getBoolean("installed", false);
if(!installed){
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("Title");
alertDialog.setIcon(R.drawable.ic_launcher);
alertDialog.setAdapter(new MyAdapter(), null);
alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("installed", true);
editor.commit();
}
});
alertDialog.show();

What you have is as follows:
if(!installed){
// Show dialog
// Else Everything inside it
}
When your app starts first time, it goes inside loop and shows the dialog. Next time when you restart, the value the SharedPreference is true, so it does not go inside the loop and nothing happen. On restarting the phone/emulator ShraredPreference does not delete, so is still true and does not go inside the loop, so nothing happens.
If you do the indentation of your program clearly, then it might be visible in bettr way.

Related

Android - Update TextView on dialog dimiss listener

I show a dialog where the user can enter a String value in an edittext and I want to display this value in an textview in the main layout after the dialog is dismissed. When the user clicks on the button "Ok" of the dialog, the textview is well refreshed, but I tried to do the same from the dismiss listener on the dialog it isn't, but I know the rest of the code is run. I tried to make it run on the mainthread but it didn't solve the problem. Here is the code, thanks for your help.
final Dialog dialogStatus = new Dialog(Activity.this);
dialogStatus.setContentView(R.layout.dialog_layout);
Button Bok = (Button) dialogStatus.findViewById(R.id.bt_dialog_ok);
final EditText ETname = (EditText) dialogStatus.findViewById(R.id.et_dialog);
Bok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
update(String.valueOf(ETname.getText()));
dialogStatus.dismiss();
}
});
dialogStatus.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
// TODO Auto-generated method stub
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
update(String.valueOf(ETname.getText()));
}
});
}
});
dialogStatus.show();
}
public void update(String etValue){
final SharedPreferences sharedPrefUnit = getSharedPreferences(SHARED_PREFS, 0);
SharedPreferences.Editor settings = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE).edit();
settings.putString(STRING_VALUE, etValue);
TextView.setText(sharedPrefUnitScore.getString(STRING_VALUE, etValue, ""));
settings.commit();
}
public void update(String etValue){
final SharedPreferences sharedPrefUnit = getSharedPreferences(SHARED_PREFS, 0);
SharedPreferences.Editor settings = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE).edit();
settings.putString(STRING_VALUE, etValue);
settings.commit();
TextView.setText(etValue);
}
Because you were trying to get the value from shared preference before committing it.
If you won't commit it then it won't save.

Show popup activity only once the app starts

I have added a popup activity inside my app which is popping after 15 seconds of my app start. But when I am opening another activity and coming back to my main activity the popup showing again. I want it to appear only the first time when user is opening the app. What changes I should make? Appreciate the help.
Here is the popup code:
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
if (context != null) {
AlertDialog.Builder alert = new AlertDialog.Builder(context, R.style.MyAlertDialogStyle)
.setTitle("Title")
.setMessage("Message")
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
Intent intent = new Intent(MainActivity.this, WebActivity.class);
startActivity(intent);
}
})
.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int which) {
dialogInterface.dismiss();
// do nothing
}
});
mDialog = alert.create();
mDialog.getWindow().getAttributes().windowAnimations = R.style.MyAlertDialogStyle;
if (!((Activity) context).isFinishing())
mDialog.show();
// .setIcon(R.drawable.inr1)
// .show();
}
}
}, 15000);
You can do this if it needs to pop up only on application start
public class MyApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
//Set some flag on global constant
}
}
save a tag(counter) in sharedPrefrances for that When the application starts up interpretation is the first time app start
You can use a global variable in the application class like this.
public class global extends Application
// some Boolean variable to hold status
And make sure you put this class inside android manifests application tag
android:name
Add this code in your MainActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
if(sharedPreferences.getBoolean("IS_FIRST_TIME", true)) {
//show your dialog here
//...
//change the value of your sharedPreferences
sharedPreferences.edit().putBoolean("IS_FIRST_TIME", false).apply();
}
}
please check the activity lifecycle.
Note:Remove Handler.
Note 2:Create method and call the dialog
Note 3:check the below method in lifecycle.
onPause ():
Called as part of the activity lifecycle when an activity is going into the background, but has not (yet) been killed. The counterpart to onResume(). When activity B is launched in front of activity A, this callback will be invoked on A. B will not be created until A's onPause() returns, so be sure to not do anything lengthy here.
save a boolean inside sharedpreferences read its value and determine weather running for the first time or not.
here is the code that will help you.
public void firstimeRun(boolean value) {
SharedPreferences sharedPreferences = getPrefrenceManager();
sharedPreferences.edit().putBoolean("key", value).apply();
}
public boolean isRunningForthefirstTime() {
SharedPreferences sharedPreferences = getPrefrenceManager();
return sharedPreferences.getBoolean("key", false);
}
private SharedPreferences getPrefrenceManager() {
return PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
}
Type finish(); after your startActivity(intent);

Android dialog dismisses on second click only. Why?

Why doesn't dialog dismiss on the first click (but shows Toast) ?
On the second click it dismisses (Toast is shown again).
private void networkDialog(){
final Dialog dialog = new Dialog(EnterActivity.this, android.R.style.Theme_Translucent_NoTitleBar);
dialog.setContentView(R.layout.custom_dialog);
Button nobutton = (Button) dialog.findViewById(R.id.dialogButLeft);
nobutton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
Toast.makeText(getApplicationContext(), "DIALOG", Toast.LENGTH_LONG).show();
}
});
dialog.show();
}
Try this way .Let me inform .I hope it will help you.
private void networkDialog()
{
final Dialog dialog = new Dialog(EnterActivity.this, android.R.style.Theme_Translucent_NoTitleBar);
dialog.setContentView(R.layout.custom_dialog);
Button nobutton = (Button) dialog.findViewById(R.id.dialogButLeft);
nobutton.setOnClickListener(this);
dialog.show();
}
Then Use onClick switch Statement
public void onClick(View view)
{
switch (view.getId())
{
case R.id.dialogButLeft:
Toast.makeText(getApplicationContext(), "DIALOG", Toast.LENGTH_LONG).show();
dialog.dismiss();
break;
}
}
A bit late but a colleague had the same issue and referred to this, are you absolutely sure that you're not creating two dialogs by calling networkDialog() twice?
Add some unique text to the dialog that will be visible to you when it's displayed like System.currentTimeMillis(), that way you can see if it's called twice because the text is different.
Or add logging / run in debug
Make your Button also final like this:
private void networkDialog(){
final Dialog dialog = new Dialog(EnterActivity.this, android.R.style.Theme_Translucent_NoTitleBar);
dialog.setContentView(R.layout.custom_dialog);
final Button nobutton = (Button) dialog.findViewById(R.id.dialogButLeft);
nobutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
Toast.makeText(getApplicationContext(), "DIALOG", Toast.LENGTH_LONG).show();
}
});
dialog.show();
}
it's working for me in my app like this:
// Initialize variables
final Dialog passwordDialog = new Dialog(BPMActivity.this,R.style.CustomDialogStyle);
passwordDialog.setContentView(R.layout.password_view);
final Button btnCancel=(Button) passwordDialog.findViewById(R.id.btn_cancel);
btnCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
passwordDialog.dismiss();
}
});
passwordDialog.show();
I don't know if this is still relevant to the OP. But I've been banging my head against the wall for quite some time trying to figure this one out. It appears to happen in later (5-6+) Android versions and did not occur on a 4.4.2 device which I have. The solution I've found is to setFocusableInTouchMode of the Button to false:
button.setFocusableInTouchMode(false)
This answer gave me the idea:
I have to click the button twice for it to work

User input alertdialog not opening after button click in BluetoothChat

Hi I'm an android newbie and I've been stuck for a week on this. Any help would be appreciated! I've done a lot of research and can't figure out what is wrong. I've successfully run the bluetoothchat sample code on two phones and successfully communicated via bluetooth. I've also successfully written and run a standalone app that, after a button click on the main activity, opens a custom alertdialog which accepts user input, and passes the input back to the main activity. But when I write the alertdialog code into the BluetoothChat code, nothing happens when I click the button. I've tried to step through the debugger with the phone but with no luck. It doesn't seem to step to the code containing the button click. There are no errors showing. Why won't the alertdialog pop up on button click? Here's the BluetoothChat.java code I've modified :
public class BluetoothChat extends Activity implements OnClickListener{
final Context context = this;
private Button rButton;
View rScreen;
private EditText mAlertDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(D) Log.e(TAG, "+++ ON CREATE +++");
// Set up the window layout
setContentView(R.layout.main);
// Get local Bluetooth adapter
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// If the adapter is null, then Bluetooth is not supported
if (mBluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
finish();
return;
}
//components from main.xml
//When button is clicked, the alert dialog is pulled up
rButton = (Button)findViewById(R.id.buttonr);
mAlertDialog = (EditText)findViewById(R.id.edittextresultm);
//add button listener
rButton.setOnClickListener(new OnClickListener() {
//#Override
public void onClick_register(View view) {
String title = "title";
String buttonOk = "OK";
String buttonCancel = "Cancel";
String madd, name;
//get review.xml view
LayoutInflater li = LayoutInflater.from(context);
View rView = li.inflate(R.layout.review, null);
//AlertDialog dialog;
AlertDialog.Builder adRegister = new AlertDialog.Builder(context);
//set review.xml to adRegister builder
adRegister.setView(rView);
//set title
adRegister.setTitle(title);
//Set EditText views to get user input
final EditText mField = (EditText)rView.findViewById(R.id.editTextm);
final EditText nField = (EditText)rView.findViewById(R.id.editTextn);
//set dialog message
adRegister.setMessage("Message")
.setCancelable(false)
.setPositiveButton(buttonOk, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String madd = mField.getText().toString();
String name = nField.getText().toString();
//get user input and set it to result on main activity
mAlertDialog.setText(mField.getText());
}
})
.setNegativeButton(buttonCancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
//if this button is clicked, close current activity
dialog.cancel();
}
});
//Create alert dialog
AlertDialog alertDialog = adRegister.create();
//dialog= adRegister.create();
//show it
adRegister.show();
//dialog.show();
}
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
});
}
}
Write your inputDialog code in OnClick Method.
Enjoy!!

Android Dialog return String?

Hi I am popping up dialog to take comments from user. And returning a value according to that. That "rcomment" is a global variable. And it returns null. This is not working. What am I doing wrong ?
public String getDoNotBoardDialog(final int groupposition)
{
final Dialog dia = new Dialog(this);
dia.requestWindowFeature(Window.FEATURE_NO_TITLE);
dia.setContentView(R.layout.donotboard);
final EditText donotedit = (EditText) dia.findViewById(R.id.donotboardcomment);
donotedit.setText("");
Button button1 = (Button) dia.findViewById(R.id.donotboardbutton);
button1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
r = donotedit.getText().toString();
String boardingComment = getString(R.string.donotboard) + " " + r;
PostCommentForAC(groupposition, boardingComment);
Intent intent = new Intent(getBaseContext(), TestExList.class);
intent.putExtra("EmpID", empid);
startActivity(intent);
rcomment = "true";
dia.cancel();
}
});
Button button2 = (Button) dia.findViewById(R.id.boardbutton);
button2.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
rcomment = "false";
dia.cancel();
}
});
dia.show();
return rcomment;
}
The getDoNotBoardDialog will initial return rcomment as null. rcomment will only be changed to "true" or "false" when the onClickListeners are fired. They are fired not when getDoNotBoardDialog is run, but after that, whenever the onClickListeners are fired.
Whatever you want to happen when rcomment is changed to "true" or "false" should be placed in the onClick methods. So if you want to check what rcomment is after a user clicks, do it there.
Edit: dont use below code. It will kill your app (ANR).
You would have to wait before you can return something. A quick (but really dirty) solution would be to add some wait/notify mechanism like so: (written blind so might contain some errors).
public String getDoNotBoardDialog(final int groupposition) {
// some Object to wait on
final Object waitOnMe = new Object();
final Dialog dia = new Dialog(this);
dia.requestWindowFeature(Window.FEATURE_NO_TITLE);
dia.setContentView(R.layout.donotboard);
final EditText donotedit = (EditText) dia.findViewById(R.id.donotboardcomment);
donotedit.setText("");
Button button1 = (Button) dia.findViewById(R.id.donotboardbutton);
button1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
r = donotedit.getText().toString();
String boardingComment = getString(R.string.donotboard) + " " + r;
PostCommentForAC(groupposition, boardingComment);
Intent intent = new Intent(getBaseContext(), TestExList.class);
intent.putExtra("EmpID", empid);
startActivity(intent);
rcomment = "true";
dia.cancel();
// stop waiting.
synchronized(waitOnMe) {
waitOnMe.notify();
}
}
});
Button button2 = (Button) dia.findViewById(R.id.boardbutton);
button2.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
rcomment = "false";
dia.cancel();
// stop waiting.
synchronized(waitOnMe) {
waitOnMe.notify();
}
}
});
dia.show();
// this wait's until someone calls notify
synchronized (waitOnMe) {
try {
waitOnMe.wait();
} catch (InterruptedException e) {}
}
return rcomment;
}
It's problematic though. You could miss the notify() and thus never stop waiting (e.g. when you close the dialog via the "back" button). A much cleaner and safer solution would be to use some Callback mechanism (you call some method in your program from each onClick) to get a value from the dialog.
In you application
the program flows to
return rcomment;
directly after going to
dia.show();
Remember it does not wait for the button to be clicked before it goes to the return statement!!! It goes to return statement directly after the dialog is shown (before the button is clicked)
Try using this string.equals(data) it should find out if the string is the same. Since rcomment is a string. Also like Soham said it will not update only until it is clicked.
I suggest that in the future you should change to Boolean rcomment. Since it only looks like you are doing either true or false status.

Categories

Resources