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
Related
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()
}
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.
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();
I'm having some trouble with displaying multiple popups. Right now I have an AlertDialog that pops up with an EditView for the user to put in the name of the file they want to make, which I would then pass into a File object and then a Writer and a new Dialog is supposed to pop up asking the user if they want to launch the music player.
However, as things are now, after I press 'Ok' on the first AlertDialog, absolutely nothing happens. I'm not sure what I'm doing wrong. Any help? Here is my code.
//naming the playlist
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Exporting Playlist");
alert.setMessage("Enter the name of the playlist!");
// Set an EditText view to get user input
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
name = input.getText().toString() + ".m3u";
popup = true;
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();
//after the playlist is named, put songs into file
if (popup){
popup = false;
final File list = new File(mp3folderPath + name);
FileWriter writer;
BufferedWriter write;
ArrayList<String> playlist = new ArrayList<String>();
Log.d("poo", "mAdapter count: "+mAdapter.getCount());
for (int i=0; i < mAdapter.getCount(); i++) {
playlist.add(mAdapter.getItem(i));
}
Log.d("poo", playlist.toString());
//write the songs to the m3u playlist
writer = new FileWriter(list);
write = new BufferedWriter(writer);
for (int i = 0; i<playlist.size(); i++){
String[] name = playlist.get(i).split(" : ");
Log.d("poo", name[0]);
write.append(name[0]+"\n");
}
write.close();
//popup window
CharSequence choices[] = new CharSequence[] {"Launch Music Player", "Quit"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Exported playlist!");
builder.setItems(choices, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (which == 0) {
Intent intent = new Intent(MediaStore.INTENT_ACTION_MUSIC_PLAYER);
startActivity(intent);
finish();
}
else {
finish();
}
}
});
builder.show();
}
}
To show sequential popup, the conditions and code for consecutive popup(s) would have to be reachable from one to the other.
AlertDialog1 has to contain the code which would show AlertDialog2...
Try something like this:
//naming the playlist
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Exporting Playlist");
alert.setMessage("Enter the name of the playlist!");
// Set an EditText view to get user input
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//check if the name is not null
name = input.getText().toString() + ".m3u";
//Now instead of popup = true;
//call func to name the playlist and next dialog
callNextDialog();
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();
//after the playlist is named, put songs into file
// if (popup){
// popup = false;
// }
public void callNextDialog(){
final File list = new File(mp3folderPath + name);
FileWriter writer;
BufferedWriter write;
ArrayList<String> playlist = new ArrayList<String>();
Log.d("poo", "mAdapter count: "+mAdapter.getCount());
for (int i=0; i < mAdapter.getCount(); i++) {
playlist.add(mAdapter.getItem(i));
}
Log.d("poo", playlist.toString());
//write the songs to the m3u playlist
writer = new FileWriter(list);
write = new BufferedWriter(writer);
for (int i = 0; i<playlist.size(); i++){
String[] name = playlist.get(i).split(" : ");
Log.d("poo", name[0]);
write.append(name[0]+"\n");
write.close();
//popup window
CharSequence choices[] = new CharSequence[] {"Launch Music Player", "Quit"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Exported playlist!");
builder.setItems(choices, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (which == 0) {
Intent intent = new Intent(MediaStore.INTENT_ACTION_MUSIC_PLAYER);
startActivity(intent);
finish();
}
else {
finish();
}
}
});
builder.show();
}
}
AlertDialog.show() doesn't wait for the dialog to go away. It returns immediately. That means ALL of the logic of what to do after the user makes a choice has to go in the onClick function of the dialog's positive button.
Basically, everything in your if(popup) code needs to be in the onClick handler
I am using this tutorial to learn how to connect to Facebook via Android app. I am particularly interested in the section where he shows how to post something on the wall / status of the user.
The tutorial is fairly straightforward however my requirement is that I need to let the app append things along with what the user posts.
How can that be achieved ?
You can do something like this:
private void publishToFacebook(String message)
{
long songId = MusicUtils.getCurrentAudioId();
long albumId = MusicUtils.getCurrentAlbumId();
String albumartUrl = MusicUtils.getArtworkUrlFromExtrasCache(getApplicationContext(),albumId);
Bitmap bm = MusicUtils.getArtworkFromExtrasCache(getApplicationContext(),albumId,false,false);
if(bm == null)
bm = MusicUtils.getDefaultArtwork(getApplicationContext());
shareFacebookConnector = new ShareConnector(MediaPlaybackActivity.this, getApplicationContext());
shareFacebookConnector.setCurrentAlbum(MusicUtils.getCurrentAlbumName());
shareFacebookConnector.setCurrentArtist(MusicUtils.getCurrentArtistName());
shareFacebookConnector.setCurrentTrack(MusicUtils.getCurrentTrackName());
shareFacebookConnector.setCurrentCoverArt(bm);
if(albumartUrl != null)
{
shareFacebookConnector.setCurrentCoverUrl(albumartUrl);
}
LayoutInflater inflater = this.getLayoutInflater();
final View dialoglayout = inflater.inflate(R.layout.facebook_share, (ViewGroup) findViewById(R.id.facebook_share_root));
final ImageView image = (ImageView) dialoglayout.findViewById(R.id.facebook_cover_view);
input = (EditText) dialoglayout.findViewById(R.id.facebook_share_content);
ContextThemeWrapper ctw = new ContextThemeWrapper(this, R.style.AlertDialogCustom);
AlertDialog.Builder alert = new AlertDialog.Builder(ctw);
if(message != null)
{
shareFacebookConnector.publishToFacebook(alert, input, message);
}
else
{
shareFacebookConnector.publishToFacebook(alert, input, null);
}
alert.setView(dialoglayout);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
bAlertInProgress = false;
String messageToPost = input.getText().toString();
shareFacebookConnector.postMessageToWall(messageToPost, false);
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
bAlertInProgress = false;
Toast.makeText(MediaPlaybackActivity.this, "Wall post cancelled !", Toast.LENGTH_SHORT).show();
//finish();
}
});
bAlertInProgress = true;
mShareKey = "********";
alertDialog = alert.create();
alertDialog.show();
}
You have to open the session as session.openForPublish(); and you required permission "publish_action"