Reputation: 531
Is it a good practice to use Bundle
to retrieve a dialog results or it is better to define an object as its output?
As an example consider there is an input form dialog with different fields. Which kind of snippets should I use:
Bundle extras = new Bundle();
extras.putString("EXTRA_USERNAME","my_username");
extras.putString("EXTRA_PASSWORD","my_password");
mListener.onDialogConfirmClick(extras)
or
CustomResult custom = new CustomResult();
custom.setUserName="my_username"
custom.setPassword="my_password"
mListener.onDialogConfirmClick(custom)
Upvotes: 0
Views: 736
Reputation: 627
Usually you want to use your Activity to process your DialogFragment result.
So, according to this article, you should define an interface, implement it into Activity, and use it to return result into Activity.
Interface, assuming your dialog serves for login purposes.
public interface OnLoginListener {
void login(String username, String password);
}
DialogFragment:
String login = mLoginEditText.getText().toString();
String password = mPasswordEditText.getText().toString();
mButton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
mOnLoginListener.login(login, password);
}
});
Activity:
public class LoginActivity extends AppCompatActivity implements OnLoginListener {
//other methods
@Override
public void login(String login, String password) {
//Just example.
MyRestApi.preformLoginRequest(login, password);
}
}
EDIT If you want to call the DialogFragment from the Fragment and return result to the Fragment you should use this
dialogFragment.setTargetFragment(this); //assuming this is the pointer to the fragment.
And when you want to return result from DialogFragment you can use Bundle and onActivityResult method:
Intent i = new Intent();
i.putStringArrayListExtra(HuddlePresenter.BUNDLE_FILTER_STRING, result);
getTargetFragment().onActivityResult(code, Activity.RESULT_OK, i);
dismiss();
ALTERNATIVELY
getParentFragment().onActivityResult(....);
Upvotes: 1