I am using a dialog as a form for the user to input data. When they click the "OK" button, the dialog is closed, and I need to use the data that was entered. How can I reference this data in the activity once the dialog has closed?
Get it when the user presses the "OK" button
final EditText input = new EditText(this); // This could also come from an xml resource, in which case you would use findViewById() to access the input
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String value = input.getText().toString();
mItem.setValue(value); // mItem is a member variable in your Activity
dialog.dismiss();
}
});
Assign an OnDismissListener to the dialog and pass the data to the activity there.
Alternatively, you can create a dialog activity and return the data as the activity result. See the following link for more info about starting activities and gettings results:
http://developer.android.com/reference/android/app/Activity.html#StartingActivities
Related
I need to reload an activity from another activity in android application. That 2nd activity is a dialog window, and based on the dialog window base activity should refresh the contents. (By click button of dialog activity)
Reload your activity.
context.startActivity(context.getIntent());
context.finish();
Consider A is an activity you want to reload and B is another activity.
In this case, just call finish()
when you are moving from A to B. When you call A from B it will load the activity A again.
Dialog Window and activity is completely deferent things.
It is possible to refresh First Activity from it's dialog. You can do it using interface.
Here is simple solution. In your First Activity implements a Interface name IRefreshInteface. It's definition is like bellow:
public interface IRefreshInteface(){
public void doRefreshValue(String commandValue);
}
Now if you implement IRefreshInteface in your activity you will get method doRefreshValue(String commandValue) and write refresh code here.
#Override
void doRefreshValue(String commandValue){
// Write refresh code here
}
Now in your dialog you have Context of your Activity. Using that context object you can call this doRefreshValue(String commandValue) method easily. Here is the sample code :
public AlertDialog displayMessage(Context context, String title, String message){
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(title);
builder.setMessage(message);
LayoutInflater inflater = LayoutInflater.from(context);
final View v = inflater.inflate(R.layout.custom_view, null);
builder.setView(v);
shipText = (EditText)v.findViewById(R.id.shipNameEditText);
scientistNameText = (EditText)v.findViewById(R.id.scientistEditText);
scientistEmailText = (EditText)v.findViewById(R.id.emailEditText);
volumeText = (EditText)v.findViewById(R.id.volumeEditText);
colourText = (EditText)v.findViewById(R.id.colourEditText);
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
((IRefreshInteface) context).doRefreshValue("YOUR_COMMAND");
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog dialog= builder.create();
dialog.show();
Button tb = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
tb.setOnClickListener(new CustomListener(dialog));
return dialog;
}
here, pass Context of Activity todisplayMessage() method and call activity method doRefreshValue using this way:
((IRefreshInteface) context).doRefreshValue("YOUR_COMMAND");
For more info visit here and here
Hope this will solve your problem. Sorry for bad english :)
I'm working on an android app and my requirement is that, I need to display the cursor values into alertdialog and let the user choose an item from the list and the value selected should be returned to the calling Activity.In my app, based on the student info, the cursor holds the values of courses he is taking. So the user should be able to choose one of the courses and then that value should be returned to the Activity that called alertdialog. Can you please let me know how to proceed on this.I've looked at multiple examples and none seems to work exactly.
Here is my sample code
final AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
final Cursor courses=dbConnector.getCourses(student);
builder.setTitle("Enter Course");
builder.setCursor(courses, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int itemSelected) {
if (courses.moveToPosition(itemSelected)) {
String text=courses.getString(0);
Toast.makeText(getApplicationContext(),
"You selected: "+text,
Toast.LENGTH_SHORT);
builder.show();
}
courses.moveToFirst();
}
},"course");
builder.create();
createRow(sview, student, pass,text);
Now I want to return the text variable to the Calling Activity but, here it is local to the onClick() method. How can we do that without having to extend any DialogFragment class.
I suggest you calling a method of the class inside overridden onClick method and do whatever you like with that because the method will be in the Activity like here
#Override
public void onClick(DialogInterface dialogInterface, int itemSelected) {
myMethod(itemSelected);
}
private void myMethod(int selectedItem){
//Do whatever with that selected item
}
I'm building an Android application and that aplication have an open part and some actions that need authentication.
What I do is to when the user click on an action that needs authentication a login dialog is show, the user can login and the login will be valid for 30 minutes.
So I have 3 buttons in an fragment that when clicked check if the user is logged in, an if not calls a login dialog.
The problem is: How can I identify what button was clicked, because when the user click the button and is not authenticated I just create the login dialog and set the setTargetFragment to the caller fragment, that was the same for the 3 buttons.
Is there a way to pass a parameter to the login dialog to identify that?
The code are as following:
When the user click the button:
final DialogFragment loginDialog = new LoginDialogFragment();
loginDialog.setTargetFragment(this, 0);
btnAprovar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!LoginService.getInstance().isLoggedOn()) {
loginDialog.show(getFragmentManager(), "Login");
}
}
});
And In the dialog:
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View v = inflater.inflate(R.layout.fragment_login_dialog, null);
final EditText txtUser = (EditText) v.findViewById(R.id.txtUsername);
final EditText txtPwd = (EditText) v.findViewById(R.id.txtPassword);
builder.setView(v)
.setPositiveButton(R.string.signin, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
DoLogin dl = new DoLogin();
dl.execute(txtUser.getText().toString(), txtPwd.getText().toString());
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
LoginDialogFragment.this.getDialog().cancel();
}
});
return builder.create();
}
private void DoPost(Boolean _result) {
if (_result.equals(true)) {
((PublicacaoDetailFragment) this.getTargetFragment()).onAuthTrue();
} else {
((PublicacaoDetailFragment) this.getTargetFragment()).onAuthFalse();
}
}
What is the best Practice to do that?
Thanks
To extend #Rodolfo's answer, you should probably use the decorator/wrapper pattern here.
Instead of extending DialogFragment, in your LoginDialogFragment you should just have an instance variable of a DialogFragment. This way, you can have a method called show(String buttonDescription), for example. Inside your own show(...) method, you can call the show() method of the DialogFragment.
Since you are extending DialogFragment in a class of your own, you have two choices:
Define a variable (with getter and/or setter) inside your custom Dialog class. In your login button onClick method, before calling show() of your Dialog, call the setter for this variable and pass v.getId(). In this case, v is the View associated with the component that you've added the OnClickListener.
Pass your button View id within a Bundle to your DialogFragment.
protected Dialog onCreateDialog(int id) {
switch (id) {
case Dialog_alert:
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
final LayoutInflater li = LayoutInflater.from(this);
builder.setTitle("Choose any option: ");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
setContentView(R.layout.tkentry);
// what to do after this..???
This is a dialog which asks the user to choose one of the following.
'items' is the String array which has "Update" and "Delete" options.
How to set separate onClick methods for them ?
"Update" and "Delete" are not BUTTONS!
You don't need two separate onClick method. You have to use int which to know which item is being selected.
If you want to know what item is selected you must add AdapterView.OnItemSelectedListener listener to your AlertDialog.Builder object.
builder.setOnItemSelectedListener (...);
You'll be notified when an item is selected so you'll be able to save it and when the confirm button is pressed you can take any action you want depending on the selected option.
I'm using and ArrayAdapter to populate a ListView. After selecting and item, it displays a confirmation Y/N dialog. If the user's choice is negative, then he should be able to select another item showing the same dialog. And so on.
Here's my code:
lView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(final AdapterView<?> parent, final View v, final int index, final long id) {
Toast.makeText("Selected file"+ mFiles.get(index).getfileName(),
Toast.LENGTH_SHORT).show();
SelectedFile = mFiles.get(index);
showDialog(DIALOG_CONFIRMIMPORT_ID);
}
});
The weird thing is that while the "Toast" shows the clicked item every time, only the first selected item since the Activity is initiated is being passed to "SelectedFile". No matter how many times you click a diferent item, "SelectedFile" always assumes the same value, the value of the first clicked item, outside of this code.
Heres's my Dialog code:
Protected Dialog onCreateDialog(int id) {
switch(id) {
case DIALOG_CONFIRMIMPORT_ID:
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
String message = String.format(getString(R.string.importstudentfileconfirm),SelectedFile.getfileName());
builder.setMessage(message)
.setCancelable(false)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Activity.this.finish();
// startActivity(new Intent(Activity.this, LOL.class));
}
})
.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
SelectedFile = null;
dismissDialog(DIALOG_CONFIRMIMPORT_ID);
mFiles.notifyAll();
}
});
AlertDialog alert = builder.create();
return alert;
}
}
return null;
}
Thank you very much for any help!
I'm guessing this has something to do with the fact that the onCreateDialog method is only called the first time the dialog is created. So the first time you see the dialog it will have the correct filename.
After onCreateDialog is called, onPrepareDialog(...) is called. onPrepareDialog, allows you to change the dialog after it has been created, but before it gets displayed.
Remember that underneath everything, Android isn't creating a new Dialog for you every time you want to show the DIALOG_CONFIRMIMPORT_ID dialog. It is too computationally expensive to instantiate a new dialog every time. Instead, it creates it once, which causes onCreatDialog to be called, followed by the onPrepareDialog. Every other time the dialog is shown, it only calls onPrepareDialog.
Check out the following article on the Android Developer site. It explains things pretty clearly.
http://developer.android.com/guide/topics/ui/dialogs.html#ShowingADialog
So try using onCreateDialog just for initialization of stuff that won't change between showings of the dialog, then use the onPrepareDialog method to dynamically update the contents of the dialog (i.e. getting the new filename)
Cheers!