Properly setting up an alertdialog on Activity closing? - android

I have an activity with two score numbers. I want the user to choose a winner if they're the same when it closes (i.e. player 1 or player2). As a .NET person, I'm trying to basically do the MessageBox.
Unfortunately, from what I've read, android doesn't do UI threads the same way. And that the activity has "a leaked window". I looked on SO and I saw the idea was to put "dismiss" in "onPause". However, I didn't see a "onPause" function and was confused to how to implement it. So I tried what I have below, but got the same error.
What can I do to this guy in order to make sure this works properly?
public void onFinish(View v) {
//get scores
TextView score1tv = (TextView) findViewById(R.id.tvScore1);
score1 = score1tv.getText().toString();
TextView score2tv = (TextView) findViewById(R.id.tvScore2);
score2 = score2tv.getText().toString();
//Make sure they aren't the same
int i_Score1 = Integer.parseInt(score1);
int i_Score2 = Integer.parseInt(score2);
if (i_Score1 == i_Score2){
//alert user
new AlertDialog.Builder(this)
.setTitle("Duplicate score")
.setMessage("Whose score won the bout?")
.setPositiveButton(boutData[1], new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//fencer 1 won
score1 = "V" + score1;
dialog.dismiss();
}
})
.setNegativeButton(boutData[3], new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
score2 = "V" + score2;
dialog.dismiss();
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.create()
.show();
}
Intent intent = new Intent();
intent.putExtra("edittextvalue","value_here");
setResult(RESULT_OK, intent);
finish();
}
Edit: Here's the solution I came to thanks to the help I received:
public void onFinish(View v) {
//get scores
TextView score1tv = (TextView) findViewById(R.id.tvScore1);
score1 = score1tv.getText().toString();
TextView score2tv = (TextView) findViewById(R.id.tvScore2);
score2 = score2tv.getText().toString();
//Make sure they aren't the same
int i_Score1 = Integer.parseInt(score1);
int i_Score2 = Integer.parseInt(score2);
if (score1 == score2){
//alert user
new AlertDialog.Builder(this)
.setTitle("Duplicate score")
.setMessage("Whose score won the bout?")
.setPositiveButton(boutData[1], new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//fencer 1 won
score1 = "V" + score1;
//close out
Intent intent = new Intent();
intent.putExtra("edittextvalue","value_here");
setResult(RESULT_OK, intent);
finish();
}
})
.setNegativeButton(boutData[3], new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
score2 = "V" + score2;
//close out
Intent intent = new Intent();
intent.putExtra("edittextvalue","value_here");
setResult(RESULT_OK, intent);
finish();
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.create()
.show();
}
else{
Intent intent = new Intent();
intent.putExtra("edittextvalue","value_here");
setResult(RESULT_OK, intent);
finish();
}
}

Put the last four lines into an else clause and do something similar in your onClick methods.
Also you shouldn't have to call dialog.dismiss() manually.

Related

Iterate through arraylist and show alert dialog for each item in array list and then move to next item when click positive button

I am creating an auto caller app in which i have used a button which takes data from arrayList, iterate through the arraylist and ask user on each element if want to do next call or pause on that for this i have used alert dialog, but the loop is not getting pause on each element it went to the last element and show alert dialog for that contact number.
private List<ContactEntity> mContactsList = new ArrayList<>();
private ContactEntity c;
private int i = 0;
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.start_call) {
Toast.makeText(this, "Call Started" + mContactsList.size(), Toast.LENGTH_LONG).show();
startAutoCall();
}
return super.onOptionsItemSelected(item);
}
private void startAutoCall() {
if (mContactsList.isEmpty()) {
Toast.makeText(this, "Import Contacts ", Toast.LENGTH_LONG).show();
} else {
c = mContactsList.get(i);
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" + c.getPersonContactNumber()));
startActivity(intent);
while(i < mContactsList.size()){
c = mContactsList.get(i);
Log.d(TAG, "startAutoCall: " + c.getId());
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Auto Dialer Start");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "hello", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" + c.getPersonContactNumber()));
startActivity(intent);
}
});
AlertDialog dialog = builder.create();
dialog.show();
i++;
}
}
}
It's not a good idea to build alert dialog inside a loop. Instead, create one and update the value for each element in the list on button click. Override onClickListener for the dialog so that you can control the flow better.
Here's a snippet in kotlin.
if(mContactList.isNotEmpty()){
c = mContactList.get(i)
val builder = AlertDialog.Builder(this)
builder.setTitle("Auto Dialer Start")
builder.setMessage("Your message here...")
builder.setPositiveButton("OK", null)
val dialog = builder.create()
dialog.setOnShowListener{ dialogInterface->
val btnOk = dialog.getButton(AlertDialog.BUTTON_POSITIVE)
btnOk.setOnClickListener{
//Your code here...
if(i == mContactList.size-1){
dialogInterface.dismiss()
}else {
i++
c = mContactList.get(i)
}
}
}
dialog.show()
}

How to access alertDialog information from new activity?

I have an app that asks the user to input Heads or Tails:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Heads or Tails?")
.setSingleChoiceItems(coinOptions, 0, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
//start coin toss
startPlay(which, coins);
}
});
AlertDialog ad = builder.create();
ad.show();
I'm just not sure exactly what it is passing to the new page? Is it an integer, 0 or 1 or something else? I am passing it as follows:
private void startPlay(int coinOption, int coins)
{
//start cointoss
Intent playIntent = new Intent(this, CoinToss.class);
playIntent.putExtra("bet", coinOption);
playIntent.putExtra("coins", coins);
this.startActivity(playIntent);
}
and recieving it:
Bundle extras = getIntent().getExtras();
int totalCoins = extras.getInt("coins", -1);
int bet = extras.getInt("bet", -1);
The information I want telling me heads or tails should be under the variable 'bet'.
Your Implementation should be like this
String [] coinOptions = {"Heads", "Tails"}; // adding your coin options
Your alert dailog should be like this
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Heads or Tails?")
.setSingleChoiceItems(coinOptions, -1, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
//start coin toss
int selectedPosition = ((AlertDialog)dialog).getListView().getCheckedItemPosition();
// Do something useful withe the position of the selected option
startPlay(selectedPosition , coins);
}
});
AlertDialog ad = builder.create();
ad.show();
Then your start play should be like this
private void startPlay(int coinOptionSelected, int coins)
{
//start cointoss
Intent playIntent = new Intent(this, CoinToss.class);
String selectedValue =null;
if(coinOptionSelected != -1) // if -1 means no option seletced do your rest handlings with else block
{
selectedValue = coinOptions[coinOptionSelected]; // if coinOptionSelected =1 then it will give Heads and if coinOptionSelected = 1 then it will give Tails
}
playIntent.putExtra("bet", selectedValue);
playIntent.putExtra("coins", coins); // i dont know what this value you have
this.startActivity(playIntent);
}
Finally your receiving should be like this
Bundle extras = getIntent().getExtras();
String selectedValue = extras.getString("bet"); // it will return Heads or Tails
int bet = extras.getInt("coins", -1); // i dont know what this value you have

alertdialog redirection to url

I used the android alertdialog in order to redirect to a url, the redirection should go according to user choice, here is the code:
final CharSequence[]stringArray = {"1" ,"2" , "3"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Press selected name");
builder.setItems(stringArray, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
String st = "https://www.youtube.com/watch?v=x9QyKNQ0uVc";
String st2 = "https://www.youtube.com/";
if (stringArray.toString().equals("1")) {
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse(st));
startActivity(intent);
}
else if (stringArray.toString().contains("2")) {
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse(st2));
startActivity(intent);
}
}
});
AlertDialog alert = builder.create();
alert.show();
but when I click 1 or 2 there is no redirection to the url
what is wrong with the code?
You are checking your arrays items which is not valid way to implement. You need to check for selected item's id which you can get from onclick method only.
As the array count starts from "0" so can check your selected item with "0 to 2" where your 0 will be considered as "1" selected and so on.
Check out below code:
final CharSequence[] stringArray = { "1", "2", "3" };
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Press selected name");
builder.setItems(stringArray, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
String st = "https://www.youtube.com/watch?v=x9QyKNQ0uVc";
String st2 = "https://www.youtube.com/";
if (item == 0)
// if (stringArray.toString().equals("1"))
{
Intent intent = new Intent(Intent.ACTION_VIEW, Uri
.parse(st));
startActivity(intent);
} else if (item == 1)
// else if (stringArray.toString().contains("2"))
{
Intent intent = new Intent(Intent.ACTION_VIEW, Uri
.parse(st2));
startActivity(intent);
}
}
});
AlertDialog alert = builder.create();
alert.show();
Please use following code:-
final CharSequence[] stringArray = { "1", "2", "3" };
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Press selected name");
builder.setItems(stringArray, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int position) {
String st = "https://www.youtube.com/watch?v=x9QyKNQ0uVc";
String st2 = "https://www.youtube.com/";
if (position == 0) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(st));
startActivity(intent);
}
else if (position == 1) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(st2));
startActivity(intent);
}
else if (position == 2) {
// write some code
}
}
});
AlertDialog alert = builder.create();
alert.show();

making phone call from DialogBox in Android

I have one DialogBox with 2 buttons. If we click the +ve button, it attempts to open the Dialing Pad; else if we click the -ve button it closes the dialog. When I click the +ve button it shows the null exception. If the same code executes without the DialogBox, it is fine.
Here is my code:
callDialog.setPositiveButton("Call Now", new android.DialogInterface.
OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent dial = new Intent();
dial.setAction("android.intent.action.DIAL");
try {
dial.setData(Uri.parse("tel:9951037343"));
startActivity(dial);
} catch (Exception e) {
Log.e("Calling", "" + e.getMessage());
}
}
}
I've given permissions in the manifest file as <uses-permission android:name="android.permission.CALL_PHONE"/>
Try this..
Intent call = new Intent(Intent.ACTION_DIAL);
call.setData(Uri.parse("tel:phonenumber");
startActivity(call);
Remove the #Overrride line.
Like this:
callDialog.setPositiveButton("Call Now", new android.DialogInterface.
OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent dial = new Intent();
dial.setAction("android.intent.action.DIAL");
try {
dial.setData(Uri.parse("tel:9951037343"));
startActivity(dial);
} catch (Exception e) {
Log.e("Calling", "" + e.getMessage());
}
}
}
----UPDATE-----
Since you havent posted any logcat, its hard to know where it crashes. Try this block:
AlertDialog.Builder callDialog = new AlertDialog.Builder(this);
callDialog.setTitle("My title");
callDialog.setMessage("My message");
callDialog.setPositiveButton("Call", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent dial = new Intent();
dial.setAction("android.intent.action.DIAL");
try {
dial.setData(Uri.parse("tel:9951037343"));
startActivity(dial);
} catch (Exception e) {
Log.e("Calling", "" + e.getMessage());
}
}
});
callDialog.setNegativeButton("Cancel", null);
callDialog.show();
Try the following---
Intent dial = new Intent(Intent.ACTION_DIAL);
//dial.setAction("android.intent.action.DIAL");
try {
dial.setData(Uri.parse("tel:9951037343"));
startActivity(dial);
} catch (Exception e) {
Log.e("Calling", "" + e.getMessage());
}
startActivity(dial);
Use
Intent callIntent = new Intent(Intent.ACTION_CALL);
instead of this
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setAction("android.intent.action.DIAL"); // but this line is an optional one
callIntent.setData(Uri.parse("tel:044 6000 6000"));
startActivity(callIntent);
use this code......
String number = "tel:" + phonenumber;
Intent intent = new Intent(Intent.ACTION_CALL, Uri
.parse(number));
startActivity(intent);
give permission in manifest: <uses-permission android:name="android.permission.CALL_PHONE" />
updated.....
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.menu_icon_pager).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new AlertDialog.Builder(MainActivity.this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Exit")
.setMessage(
"Texting from dialog")
.setNegativeButton(android.R.string.cancel, null)
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// Exit the activity
String number = "tel:"+phonenumber ;
Intent intent = new Intent(Intent.ACTION_CALL, Uri
.parse(number));
startActivity(intent);
}
})
.show();
}
});
}
Actually I called the AlertDialog from another Activity,so I need the context of called
Activity's Context reference.So I passed the Context as a parameter to Called Activity
Here is Called Activity's code
if(position == 1)new CalledByActivity().dailingDialogBox(param1,
param2,context);//Here I'm passing the context as param
Here CalledBy activity's implemented function
public void dailingDialogBox(final String param1,String param2,final Context context){
Here I implemented in +ve button click
Intent dail = new Intent(Intent.ACTION_DIAL);
dail.setData(Uri.parse("tel:"+station_Number));
context.startActivity(dail);//Here the "context" is reference of called Activity's context

How to get the context in the marked position?

I am trying to use parse.com in an android application of mine, how to get the context at the place of *** in the code AlertDialog.Builder(*******)? I tried using getApplicationcontext which doesn't work.Can anyone with experience in the android help me with respect to this?
mSignInButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
mVibrator.vibrate(100);
//Checking for internet connection...
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
//internet connection inactive... show alert...
if (!(netInfo != null && netInfo.isConnectedOrConnecting())) {
AlertDialog.Builder adb = new AlertDialog.Builder(arg0.getContext());
adb.setTitle("ALERT");
adb.setMessage("Please turn on Internet.");
adb.setPositiveButton("Ok", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
// Action for 'Ok' Button
}
});
adb.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
// Action for 'Cancel' Button
dialog.cancel();
}
});
adb.setIcon(R.drawable.ic_launcher);
adb.show();
}else{
ParseQuery<ParseObject> query = ParseQuery.getQuery("Admin");
query.whereEqualTo("password", mUserNameEditText.getText().toString());
query.whereEqualTo("userName", mPasswordEditText.getText().toString());
query.countInBackground(new CountCallback() {
public void done(int count, ParseException e) {
if (e == null) {
// The count request succeeded. Log the count
Log.d("test", "Sean has played " + count + " games");
if(count>0){
// save the login status... loggedIn/notloggedIn...
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(LoginScreenActivity.this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("isLoggedIn", true);
editor.commit();
// if user name password is correct, navigate to next activity...
Intent intent = new Intent(LoginScreenActivity.this,OptionScreenActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivityForResult(intent, 0);
overridePendingTransition(R.layout.fade_in, R.layout.fade_out);
}else{
AlertDialog.Builder adb = new AlertDialog.Builder(*********************);
adb.setTitle("ALERT");
adb.setMessage("Wrong username or password.");
adb.setPositiveButton("Ok", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
// Action for 'Ok' Button
}
});
adb.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
// Action for 'Cancel' Button
dialog.cancel();
}
});
adb.setIcon(R.drawable.ic_launcher);
adb.show();
}
} else {
// The request failed
}
}
});
Try out as below:
AlertDialog.Builder adb = new AlertDialog.Builder(getApplicationContext());
OR
AlertDialog.Builder adb = new AlertDialog.Builder(<YourActivity>.this);

Categories

Resources