I need to make a math quiz. Here is workflow:
On button click(Start) i need to show a question e.g. 5+5, which stays on screen for 2 seconds after which a dialog i shown asking for result of previous operation. And i need to repeat that for e.g. 5 times. At the end I need to show to user number of correct answers.
I have Java experience but I'm new to Android. I have read various articles and examples regarding Android threading but haven't found solution to this workflow.
As far as I know I cannot block or pause main/UI thread, but the problem is that i should repeat questions for e.g. 5 times and after each one(after 2 sec.) I should pause activity to show Dialog and then go back to showing another question.
Thanks in advance!
EDIT:
Here is my code for now. The number is shown on screen and after 2 seconds alert dialog is shown asking to enter that number. But the problem is that the application doesn't wait for user input but continues to show new random number an opens new alert dialog every 2 seconds.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_questions);
tv = (TextView) findViewById(R.id.questionText);
handler = new Handler();
Runnable r = new Runnable() {
public void run() {
tv.setText(String.valueOf(rand.nextInt(50) + 1));
createDialog();
handler.postDelayed(this, 2000);
}
};
handler.postDelayed(r, 2000);
}
protected void createDialog() {
LayoutInflater li = LayoutInflater.from(context);
View promptsView = li.inflate(R.layout.activity_answer_dialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
final EditText userInput = (EditText) promptsView.findViewById(R.id.editTextDialogUserInput);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// get user input and set it to result
// edit text
result.setText(userInput.getText());
}
})
.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();
}
PS. Also I tried to create separate Activity for dialog and added this line to Manifest:
android:theme="#android:style/Theme.Dialog"
but the same thing happens.
You use event driven programming and timers. To show the dialog after 2 seconds, the easiest way is to post a runnable to a handler using postDelayed, which will call your runnable in N milliseconds. Then display the dialog box.
You don't need to pause the activity to show the dialog box, just show it. Any code that you want to run after the dialog is finished with should be put in the handler for the dialog's ok button. In other words, your code is called in response to the event of a button being pressed.
Related
In my app I need multiple dialogs or multiple views which will be updated after clicking positive and negative dialog buttons.
How should it looks in example:
1) Call first Dialog1
2) Inside Dialog1 I have some data and 2 buttons (positive and negative) onClick possitive Button I go to next Dialog2 on negative I exit dialogs.
3) Inside Dialog2 similar situation click on possitive button provides me to next dialog or dialog view but negative button leeds back to Dialog1
for now my code looks like :
public class DialogChoiceActivity extends DialogFragment {
LayoutInflater inflater;
View v;
public Dialog onCreateDialog(Bundle savedInstanceState) {
inflater = getActivity().getLayoutInflater();
v = inflater.inflate(R.layout.dialog_email,null);
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
final Dialog dialog2 = builder.create();
builder.setTitle("Email " + " 1/10");
builder.setView(v).setPositiveButton("NEXT", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
}).setNegativeButton("Exit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
return builder.create();
}
First of all I'm not sure which way is better create multiple dialogs or one Dialog with multiple Views. Which way is better if I want easily move from one dialog to another (or view). There are some problems because I cant update builder object or dissmiss it so how shold all this looks like ? what is best way to do that
Sorry for chaotic and weak language.
Create DialogFragment as you needed.
Make clicking on the positiveButton to show next dialog and dismiss current dialog.
From next dialog, clicking on negativeButton to show previous dialog and dismiss current one.
when I press on a Button in my App, I am directed to a new Activity, but this takes a little time and the user might think the App is idle. So I want to have a progressbar or this little circle spinning while the new Activity is loading. The question now, how can I set such a progressbar to the Intent task, so that it fills accordingly to the loading progress?
Thank you!
You can give some predefined delay and use any of the UI elements like I used alert dialog for my application, you can use any other element and set the timer appropriately.
final AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity()).setMessage("Please wait you are being redirected");
final AlertDialog alert = dialog.create();
alert.show();
alert.setCancelable(false);
new Handler().postDelayed(new Runnable() {
#Override
public void run()
{
Intent i = new Intent(ctx, MyAccount.class);
startActivity(i);
if (alert.isShowing()) {
alert.dismiss();
}
}
}, 3000);
Initially in my app I am creating an AlertDialog which has three buttons, in which the middle button opens up another AlertDialog. The problem is that when the second AlertDialog closes after a button is pressed, the first one closes with it. I think both AlertDialogs get closed after I press a button on the second AlertDialog.
What I want is for the first AlertDialog to open another AlertDialog that has its own buttons, and when second AlertDialog presses a button, it only closes itself and goes back to the first one. Is there any way to achieve this?
Here is the code for the button used to open the AlertDialog:
final ImageButton fabgroup = (ImageButton) findViewById(R.id.groupButton);
Here's the code for a button that opens an AlertDialog that contains another button that opens another AlertDialog using the middle button (create button) on itself, but closes them both when a button on the second one is pressed (either the yes or no button, which is not what I want as I only want the second one to close itself and go back to the first AlertDialog, and yea this sounds pretty confusing in theory so I can try to clarify if needed):
fabgroup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final AlertDialog.Builder helpBuilder = new AlertDialog.Builder(CreateNote.this);
helpBuilder.setTitle("Select a group");
helpBuilder.setMessage("Add to group?");
final TextView input = new TextView(mainactiv.this);
input.setSingleLine();
input.setText("");
helpBuilder.setView(input);
helpBuilder.setNegativeButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Do nothing but close the dialog
Toast.makeText(CreateNote.this, "Page has been added to group", Toast.LENGTH_SHORT).show();
}
});
helpBuilder.setNeutralButton("Create", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//open another alertbox
AlertDialog.Builder helpBuilder2 = new AlertDialog.Builder(CreateNote.this);
helpBuilder2.setTitle("Assign a new group");
helpBuilder2.setMessage("Create group?");
final EditText input = new EditText(CreateNote.this);
input.setSingleLine();
input.setText("");
helpBuilder2.setView(input);
helpBuilder2.setNegativeButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Create Group
Toast.makeText(CreateNote.this, "Group has been created", Toast.LENGTH_SHORT).show();
}
});
helpBuilder2.setPositiveButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Do nothing
}
});
// Remember, create doesn't show the dialog
AlertDialog helpDialog2 = helpBuilder2.create();
helpDialog2.show();
}
});
helpBuilder.setPositiveButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Do nothing
}
});
// Remember, create doesn't show the dialog
AlertDialog helpDialog = helpBuilder.create();
helpDialog.show();
}
});
Help would be greatly appreciated.
I eventually managed to solve this problem by creating two separate functions to generate each dialog box, and when one closes it calls the function to create the other one, kinda like recycling (or maybe closer to looping functions). Although, I'm not entirely sure how performance heavy this is, but it seems to do the job without any issues from what I'm testing. If anyone would like to chime in on how this could be an issue, then I'm open to hearing what others have to say about the negative points of using alert dialog boxes this way.
You can show an activity as dialog. Put this in your manifest file.
<activity android:theme="#android:style/Theme.Dialog" android:excludeFromRecents="true"/>
From this answer: Android Activity as a dialog
#Override
public void run() {
//Create thread that can alter the UI
AlarmPage.this.runOnUiThread(new Runnable() {
public void run() {
cal = Calendar.getInstance();
//See if current time matches set alarm time
if((cal.get(Calendar.HOUR_OF_DAY) == alarmTime.getCurrentHour())
&& (cal.get(Calendar.MINUTE) == alarmTime.getCurrentMinute())){
//If the sound is playing, stop it and rewind
if(sound.isPlaying()){
ShowDialog();
alarmTimer.cancel();
alarmTask.cancel();
alarmTask = new PlaySoundTask();
alarmTimer = new Timer();
alarmTimer.schedule(alarmTask, sound.getDuration(), sound.getDuration());
}
sound.start();
}
}
});
}
public void ShowDialog() {
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("REMINDER!");
alertDialog.setMessage("Turn off alarm by pressing off");
alertDialog.setNegativeButton("Off", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "OFF", Toast.LENGTH_SHORT);
}
});
alertDialog.show();
}
I am making a simple alarm clock app that notifies the user. I want to make a alert box that gives the user the option to turn off the alarm when it goes off. I was able to make the alert box, but it only appears in the app not outside of the app. I understand the app has to be in the background running. If I need to show more code or be more specific, just ask please.
Add a line as:
public void ShowDialog() {
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("REMINDER!");
alertDialog.setMessage("Turn off alarm by pressing off");
alertDialog.setNegativeButton("Off", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "OFF", Toast.LENGTH_SHORT).show();
}
});
alertDialog.show();
// line you have to add
alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_TOAST);
}
check now.
Do not accept answers if they don't address your question, it is misleading.
The accepted answer is not correct, as it will never work outside your application.
Reason:
It requires an activity context not application context.
If you provide application context, your app will crash with IllegalArgumentException- you need to use Theme.AppCompat or their decendents...
If you need functionality as actually stated in the question you have to have a separate activity themed as a Dialog like here
or you can add a custom view to your window using window manager and making it system level alert like here.
Do this create an Activity without ContentView or a View associated with it and call your alertDialog method in your onCreate also remember to set the background of the Activity to Transparent using ColourDrawable
And that activity will look like a dialog or will suit your preference, you can also fall back to Themes so you can set an Activity as Dialog and treat it like Dialog also use DialogFragment
I am trying to have a dialog pop up on screen when case 2 is selected from the Action bar, preferably without clicking on a button. As of right now, I can only get it to work onClick and not when the page opens. How can I get rid of the button and only have it show on open for a few seconds, then dismiss? Thanks.
case 2:
// get button
Button btnShow = (Button)findViewById(R.id.btn_show);
btnShow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
builder.setTitle("Auto-closing Dialog");
builder.setMessage("After 2 second, this dialog will be closed automatically!");
builder.setCancelable(true);
final AlertDialog dlg = builder.create();
dlg.show();
final Timer t = new Timer();
t.schedule(new TimerTask() {
public void run() {
dlg.dismiss(); // when the task active then close the dialog
t.cancel(); // also just top the timer thread, otherwise, you may receive a crash report
}
}, 2000); // after 2 second (or 2000 miliseconds), the task will be active.
}
});
You can use Handle for your requirement :
case 2:
// get button
Button btnShow = (Button)findViewById(R.id.btn_show);
btnShow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
builder.setTitle("Auto-closing Dialog");
builder.setMessage("After 2 second, this dialog will be closed automatically!");
builder.setCancelable(true);
final AlertDialog dlg = builder.create();
dlg.show();
Handler mHandler = new handler();
Runnable mRunnable = new Runnable () {
public void run() {
if(dlg != null && dlg.isShowing()) dlg.dismiss();
}
};
mHandler.postDelayed(mRunnable,2000);
}
});
UPDATE :
I have updated code for removing errors
This code will dismiss the alert dialog after 2 seconds user clicks on button.
Is this what you want to do ?
If you want to hide the Button and want to have click functionalty use :
Button btnShow = (Button)findViewById(R.id.btn_show);
btnShow.setVisibility(View.GONE);
btnShow.performClick();
I really do not understand what you are trying to say.Your following statement is making confusion
I am trying to have a dialog pop up on screen when case 2 is selected
from the Activity bar,
I do not know what do you meant by case 2 and activity bar. but in case if it is actionbar and you are using spinner in it then you can override the following method
android.support.v7.app.ActionBar.OnNavigationListener navigationListener = new android.support.v7.app.ActionBar.OnNavigationListener() {
#Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
//Here you can implement the case
so when you are able to show the dialog box, You can start timer with the start of dialog box and you can then on finish of timer you can close the dialog box.
I hope this make sense to you. Please reply back if you need help I can provide source code.
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
Runnable hideDialog = new Runnable() {
public void run() {
dialog.dismiss();
}
};
executor.schedule(hideDialog, 2, TimeUnit.SECONDS);
}