I have created an app which includes popups of different dialogs.
Here is my code:
if (lDiffFromToday >= 0 && lDiffFromToday <= DeclareVariable.CYCLE_MAX_LENGTH)
{
AlertDialog.Builder alrtStartMonitoring = new AlertDialog.Builder(this);
alrtStartMonitoring.setTitle(" Start Monitoring");
alrtStartMonitoring.setMessage("Set start date of cycle as"+" "+sdFormatter.format(dtSelDate));
alrtStartMonitoring.setPositiveButton("Yes", this);
AlertDialog alert = alrtStartMonitoring.create();
alert.show();
}
else if (dtSelDate.getTime()> dtStartDate.getTime() && dtSelDate.getTime() <= currentDate.getTime() && !bCycleStopped)
{
long lDiffFromStart =dtSelDate.getTime()-dtStartDate.getTime();
lDiffFromStart=lDiffFromStart/(1000 * 60 * 60 * 24);
if (lDiffFromStart >= DeclareVariable.CYCLE_MIN_LENGTH)
{
bActionOk = true;
AlertDialog.Builder alrtStartMonitoring = new AlertDialog.Builder(this);
alrtStartMonitoring.setTitle(" Confirm New Cycle");
alrtStartMonitoring.setMessage("Set start date of cycle as" + " " + sdFormatter.format(dtSelDate));
alrtStartMonitoring.setPositiveButton("Yes", this);
AlertDialog alert = alrtStartMonitoring.create();
alert.show();
}
}
// ...
public void onClick(DialogInterface dialog, int id)
{
CycleManager.getSingletonObject().setHistoryDate(dtSelDate);
int iStopStartCount = CycleManager.getSingletonObject().getStopStartCount();
if(iStopStartCount>0)
CycleManager.getSingletonObject().setStopStartDate(dtSelDate, iStopStartCount);
displayDay();
}
Now my question is that for each dialog I need different onClick functions but in my case when I write another onClick function then there will be conflict. I know by writing the onClick function inside each dialog may solve the problem but in that case, I have to declare my variables as final so how can I do it by writing onClick function outside for every dialog I used.
Another solution will be to make the AlertDialog instances members of your class. Then in the OnClick method:
public void onClick(DialogInterface dialog, int id)
{
if (dialog == m_Dialog1)
{
// server dialog 1
}
}
I can see that you've made the your class to implement the DialogInterface.OnClickListener
instead of
alrtStartMonitoring.setPositiveButton("Yes", this);
You can make it this way
alrtStartMonitoring.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick (DialogInterface dialog, int which) {
}
});
and for each one of the setPositiveButton you can define the different onClick listener
Hope this helps
Why not create your own DialogInterface.OnClickListener classes and instantiate them with the appropriate variables from your main class that you don't want to mark as final, but do want them to have access to (inject them effectively). Then you can do
FooDialogOnClickListener l1 = new FooDialogOnClickListener(dtSelData, ...);
BarDialogOnClickListener l2 = new BarDialogOnClickListener(iStopStartCount, ...);
if (...) {
// ...
alrtStartMonitoring.setPositiveButton("Yes", l1);
} else {
// ...
alrtStartMonitoring.setPositiveButton("Yes", l2);
}
Related
I've managed to successfully implement Facebook login into my Android app.The issue I'm facing is,on my logout,whenever I click the logout button,I would like to capture the click of "Cancel / Logout" options.How do I go about doing this?Below are images attached for a much clearer illustration.
As shown in the images,how do I go about capturing the clicks in the highlighted red circles?
Below attached are my codes for the login/logout activity as well.Thank you :)
View view = inflater.inflate(R.layout.splash, container, false);
LoginButton authButton = (LoginButton) view
.findViewById(R.id.login_button);
authButton.setFragment(this);
// Get more permissions
authButton.setPublishPermissions(Arrays
.asList("publish_actions,read_stream"));
authButton.setFragment(getParentFragment());
I now this post is very old but...
I had the same problem as you, what I did was:
(only sure for facebook sdk v2.0)
1. Go to package com.facebook.widget;
2. Open the file LoginButton.java;
3. Go to line 819 inside the public void onClick(View v);
4. See the allert Dialog? I just comented the code as follows:
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(message)
.setCancelable(true)
.setPositiveButton(logout, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
openSession.closeAndClearTokenInformation();
}
});
/*.setNegativeButton(cancel, null);*/
builder.create().show();
And it is done!, no more annoying cancel button on dialog.
(You can also remove the whole dialog)
I got the same problem and searched some many answers,but they doesnot work,so I just write some new codes in LoginButton.java in facebook sdk,my frist step:
public interface LogoutListener{
public void afterLogin();
}
private LogoutListener mLoginoutListener;
public void setLogoutListener(LogoutListener loginoutListener){
this.mLoginoutListener = loginoutListener;
}
second step:find 811 lines in LoginButton.java and you will see the code just like this:
private class LoginClickListener implements OnClickListener {
#Override
public void onClick(View v) {
Context context = getContext();
final Session openSession = sessionTracker.getOpenSession();
if (openSession != null) {
// If the Session is currently open, it must mean we need to log out
if (confirmLogout) {
// Create a confirmation dialog
String logout = getResources().getString(R.string.com_facebook_loginview_log_out_action);
String cancel = getResources().getString(R.string.com_facebook_loginview_cancel_action);
String message;
if (user != null && user.getName() != null) {
message = String.format(getResources().getString(R.string.com_facebook_loginview_logged_in_as), user.getName());
} else {
message = getResources().getString(R.string.com_facebook_loginview_logged_in_using_facebook);
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(message)
.setCancelable(true)
.setPositiveButton(logout, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
openSession.closeAndClearTokenInformation();
// here is what I added
if(mLoginoutListener != null){
mLoginoutListener.afterLogin();
}
}
})
.setNegativeButton(cancel, null);
builder.create().show();
} else {
openSession.closeAndClearTokenInformation();
}
third step,and this is how I use :
LoginButton floginButton = (LoginButton)findViewById(R.id.flogin_button);
floginButton.setLogoutListener(new LogoutListener() {
#Override
public void afterLogin() {
// do what you want ,when user click the "OK" button.
}
});
I changed a little bit codes in facebook sdk,and it worked for me,I hope this can help you.
In my app i have a function that checks the entered text from a displayed AlertDialog with an input text. If the text is equal to a string variable, return True, else return False, and catch this resulting value to continue conditional code.
But it seems its a little difficult to do this as i've read in other posts asking how to solve the same problem.
I've already done this:
private boolean checkAdministratorPassword() {
final enterPasswordResult[0] = false;
AlertDialog.Builder alert = new AlertDialog.Builder(mContext);
alert.setTitle("Confirm action");
alert.setIcon(R.drawable.ic_launcher);
alert.setMessage("Enter administrator pass to continue");
final EditText input = new EditText(mContext);
input.setPadding(5, 0, 5, 0);
alert.setView(input);
alert.setPositiveButton("Accept", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String strPass = input.getEditableText().toString();
if (strPass.length() == 0) {
dialog.cancel();
}
if (strPass.equalsIgnoreCase(Constantes.ADMIN_PASS)) {
enterPasswordResult[0] = true;
dialog.cancel();
} else {
Toast.makeText(mContext, "Invalid pass..!!", Toast.LENGTH_LONG).show();
dialog.cancel();
}
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
});
AlertDialog alertDialog = alert.create();
alertDialog.show();
return enterPasswordResult[0];
}
And i call the function this way:
If ( checkAdministratorPassword() == True ){
//true conditions
}
But the problem is that the check function doesnt wait for the result to continue with the code, it just continue by itself and i dont get the appropiate behavior.
The issue is you're trying to handle an async event in the logcal flow of your program. You can do this if you make the Dialog it's own class and use an Interface to callback to your host activity. Check out the documentation on DialogFragment.
public interface PasswordCheckListener{
public void valid(boolean check);
}
private static class PasswordDialog extends DialogFragment {
private PasswordCheckListener listener;
public static PaswordDialog newInstance(PasswordCheckListener listener){
this.listener = listener;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
//Put your dialog creation code here
}
private checkAdminPassword(){
//Whatever your check passowrd code is
listener.valid(result);
}
}
I realize I didn't implement all the code for you but that's the general idea. By using an interface you can call back to your host Activity or Fragment when the user enters the password and presses submit. You can then handle the event as it happens, rather than having to deal with it in your program flow.
Thank you all for your answers!! i've found the right way to achieve this problem by creating an Activity whith theme "Theme.Dialog", an input text and two buttons (Accept, Cancel), i start this activity for result asking the user to enter the administrator pass to continue, checking the string and then returning again to onActivityResult() from previous activity with the correct information to proceed.
I have an activity (Main) and I inserted a button in it.
When button the user press it, a dialog box with 2 Radio boxes appear. I want to set "1" or "0" value to "ntv", based on which radiobutton is selected, and then use "ntv" value in Main activity, but it seems that this doesnot transfer "ntv" value to Main activity, what is wrong with my code?
final CharSequence[] chan = {"Minutes", "Seconds"};
builder = new AlertDialog.Builder(Main.this);
builder.setTitle("Please Select:");
builder.setSingleChoiceItems(chan, 0, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if(chan[item]=="Minutes")
{
Toast.makeText(getApplicationContext(), "Minutes", Toast.LENGTH_SHORT).show();
ntv="1";
}
else if (chan[item]=="Seconds")
{
Toast.makeText(getApplicationContext(), "Seconds", Toast.LENGTH_SHORT).show();
ntv="0";
}
}
});
AlertDialog alert = builder.create();
alert.show();
I defined "ntv" as string and this is part of code when "ntv" is compared to check if it is "0" or "1"
ImageView set1= (ImageView) findViewById(R.id.set1);
ImageView set2= (ImageView) findViewById(R.id.set2);
if (ntv.equals("0")) {
set1.setVisibility(View.INVISIBLE);
}
if (ntv.equals("1")) {
set2.setVisibility(View.INVISIBLE);
}
and because neither (set1) nor (set2) doesnot go invisible I realize that "ntv" have no value.
This all looks OK (except the suggestion to use equals() instead of == for the string compares, although, as you say, it does work (it just isn't good practice).
The only thing I can think of (without seeing all the code) is that the scope of variable ntv is wrong. Have you declared the variable inside a method? It needs to be defined as an instance variable in your class (ie: not within a method).
you should be doing .equals on the string comparison NOT ==
It is unlikely that your if statements will trigger because of this.
if(chan[item].equals("Minutes"))
{
Toast.makeText(getApplicationContext(), "Minutes", Toast.LENGTH_SHORT).show();
ntv="1";
}
else if (chan[item].equals("Seconds"))
{
Toast.makeText(getApplicationContext(), "Seconds", Toast.LENGTH_SHORT).show();
ntv="0";
}
it's not clear the complete code you use and how you call the code that change visibility. Below an example
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AlertDialog.Builder builder;
final CharSequence[] chan = {"Minutes", "Seconds"};
builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Please Select:");
builder.setSingleChoiceItems(chan, 0, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if(chan[item].equals("Minutes")) {
showToast("Minutes");
} else if (chan[item].equals("Seconds")) {
showToast("Seconds");
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
private void showToast(String s){
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
}
instead of showToast function you can use a your function to change visibility
I am working on an android project where I am trying to show a AlertDialog in a separate normal java class and return the result that the user enters. I can display the dialog fine but the problem I am having is it always returns the value before the dialog has had one of the buttons pressed.
Below is the code that calls the function in the standard java class to show the dialog
private void showDiagreeError()
{
Common common = new Common(this);
boolean dialogResult = common.showYesNoDialog();
Toast.makeText(getApplicationContext(), "Result: " + dialogResult, Toast.LENGTH_LONG).show();
}
And below is the code that shows the actual dialogue
public boolean showYesNoDialog()
{
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage("Are you sure you do not want to agree to the terms, if you choose not to, you cannot use Boardies Password Manager")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialogResult = true;
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialogResult = false;
}
});
AlertDialog alert = builder.create();
alert.show();
return dialogResult;
}
dialogResult is a global variable visible throughout the class and being set to false. As soon as the dialog is shown the toast message is shown showing the result is false, but I was expecting the return statement to block until the user has pressed one of the buttons too set the variable to the correct value.
How can I get this to work.
After many hours hunting through the inner depths of google pages, I found this Dialogs / AlertDialogs: How to "block execution" while dialog is up (.NET-style).
It does exactly the job I was after and tested to make sure there are no ANR errors, which there isn't
I have a usecase like repeatedly calling the same dialog box with different values. I am using the same dialog creating code for that. First time the sent data is populated to dialog box. but next time the dialog box not getting rebuilt with different values when i call the same for next time.
Code is here
dialog.setContentView(R.layout.orderdialog);
dialog.setTitle("Selected Item");
dialog.setCanceledOnTouchOutside(true);
System.out.println(selected); // here i am sending different values eachtime. But not updating in dialog.
TextView selectedItem = (TextView)dialog.findViewById(R.id.itemName);
selectedItem.setText(selected);
You can use the android alert builder to show dynamic data:
new AlertDialog.Builder(this)
.setTitle("your title name")
.setMessage("here you can write your dynamic data as string or integer")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(/* don't remember the signature by heart... */) {
// continue with delete
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(/* don't remember the signature by heart... */) {
// do nothing
}
})
.show();
Instead of calling
showDialog(id);
and creating dialog in oncreatDialog function
create the dialog and show it in you on click function itself:
like this:
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("State");
builder.setItems(m_arrStateNames, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
m_nSelStateIdx = which;
showState();
dialog.dismiss();
}
});
builder.show();
}
});