Return values from DialogFragment - android

I am doing task in which I need to show a dialog after clicking on EditText. In that dialog I show contents with RadioButtons using RecyclerView.
Now, what I want to do is, after selecting RadioButton (content which is in the RecyclerView) from dialog, it should return value of that content and then dialog should be dismissed.
To generate a dialog I've used a DialogFragment.
As I'm new in android development, I am totally confused and unable to find the solution.

Because your dialog is a DialogFragment you can use two things
If you are starting the dialog from a Activity, you can use an interface
create an interface
public interface ISelectedData {
void onSelectedData(String string);
}
implement an interface in your Activity
public class MyActivity implements ISelectedData {
.....
#Override
public void onSelectedData(String myValue) {
// Use the returned value
}
}
in your Dialog, attach the interface to your Activity
private ISelectedData mCallback;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallback = (ISelectedData) activity;
}
catch (ClassCastException e) {
Log.d("MyDialog", "Activity doesn't implement the ISelectedData interface");
}
}
when returning the value to Activity, just call in your Dialog
mCallback.onSelectedData("myValue");
Check the example on the Android developer site.
If you are starting the dialog from a Fragment, you can use setTargetFragment(...)
starting the Dialog
MyDialog dialog = new MyDialog();
dialog.setTargetFragment(this, Constants.DIALOG_REQUEST_CODE);
dialog.show(fragmentManager, Constants.DIALOG);
returning the value from the Dialog
Bundle bundle = new Bundle();
bundle.putString(Constants.MY_VALUE, "MyValue");
Intent intent = new Intent().putExtras(bundle);
getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, intent);
dismiss();
getting the value in Fragment
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Constants.DIALOG_REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
if (data.getExtras().containsKey(Constants.MY_VALUE)) {
String myValue = data.getExtras().getString(Constants.MY_VALUE);
// Use the returned value
}
}
}
}

Related

Unable to get the data from one Activity to Another Activity

I have created two Activities.
Main Activity.java(This is the activity that application launches with, user click on a button called "Show timer" which takes the user to the next activity)
displayTimer.java(This is the second activity which has a ListView, with data in each row. on item click users comes back to the main activity)
I'm trying to pass the string stored in that row to the main activity.
This is the main code from display timer activity
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_list_view);
listView = (ListView) findViewById(R.id.customtimer_listview);
customTimerAdapter = new CustomTimerAdapter(this, R.layout.row);
BackGroundTask backGroundTask = new BackGroundTask(this);
backGroundTask.execute("Get_info");
registerForContextMenu(listView);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView textView = (TextView) view.findViewById(R.id.time_entered);
String timeRetrevied = textView.getText().toString();
//System.out.println(timeRetrevied);
Intent intentExtras = new Intent(displayTimer.this,MainActivity.class);
intentExtras.putExtra("TIME_DATA",timeRetrevied);
setResult(RESULT_OK, intentExtras);
//startActivityForResult(intentExtras,SECOND_ACTIVITY_REQUEST_CODE,null);
finish();
}
});
}
This is the code from the Main activity where i'm calling the method onActivityResult to get the data through intent from displaytimer. But i'm not able to get the data. Dont know what i'm doing wrong. Any input with be fine.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SECOND_ACTIVITY_REQUEST_CODE){
if (resultCode == RESULT_OK) {
int setTimer = Integer.parseInt(data.getDataString());
System.out.println(setTimer);
seekbar.setProgress(setTimer * 60);
updateTimer(setTimer);
}
else{
System.out.println("Not Ok");
}
}
System.out.println("RequestCode failed");
}
}
Instead of
data.getDataString()
use
data.getStringExtra("TIME_DATA")
getDataString returns the URI in the encoded String format, which is not what you require as you are not passing in the data.
As you are passing in the Sting text with ID=TIME_DATA, use the same ID to get the string back using the getStringExtra("TIME_DATA");

incompatible types: AccessControlContext cannot be converted to ECartHomeActivity(MainActivity)

I'm getting the error in this part of the Activtiy(SearchActivity.java):
// Whenever a view in your cart is clicked
shoppinListAdapter.SetOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Utils.switchFragmentWithAnimation(
R.id.frag_container,
new ProductDetailsFragment("", position, true),
((ECartHomeActivity) (getContext())), null,
Utils.AnimationType.SLIDE_LEFT);
// ECartHomeActivity is the MainActivity
}
});
and this is the method of Utils class which is used in the Activity:
public static void switchFragmentWithAnimation(int id, Fragment fragment,
FragmentActivity activity, String TAG, AnimationType transitionStyle) {
FragmentManager fragmentManager = activity.getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
if (transitionStyle != null) {
switch (transitionStyle) {
case SLIDE_UP:
// Enter from Up
fragmentTransaction.setCustomAnimations(R.anim.slide_in_up,
R.anim.slide_out_up);
break;
case SLIDE_LEFT:
// Enter from left
fragmentTransaction.setCustomAnimations(R.anim.slide_left,
R.anim.slide_out_left);
break;
default:
break;
}
}
CURRENT_TAG = TAG;
fragmentTransaction.replace(id, fragment);
fragmentTransaction.addToBackStack(TAG);
fragmentTransaction.commit();
}
This code I have Copy pasted from one of my fragments into this Searched_Product_Activtiy.java. It works fine in the fragments.
The problem is you're trying to convert ECartHomeActivity as a context with ((ECartHomeActivity) (getContext()) which will not work because it's a class not an Activity instance.
You can use SearchActivity.this as the Activity for the Utils but change the activity parameter to Activity like this:
public static void switchFragmentWithAnimation(int id, Fragment fragment,
Activity activity, String TAG, AnimationType transitionStyle) {
}
But that's probably not you want, I guess you want to switch the Fragment in MainActivity. If this what you intended, you should use startActivityForResult() from the MainActivity. To do that, first you need to start the ActivitySearch from your MainActivity:
public static final int REQUEST_CODE = 1;
...
public void startSearch() {
Intent intent=new Intent(MainActivity.this, ActivitySearch.class);
startActivityForResult(intent, REQUEST_CODE);
}
Second, override onActivityResult() in MainActivity to receive the result from ActivitySearch:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == REQUEST_CODE) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
// Call your util here
Utils.switchFragmentWithAnimation(
R.id.frag_container,
new ProductDetailsFragment("", position, true),
MainActivity.this, null,
Utils.AnimationType.SLIDE_LEFT);
}
}
}
Last, in ActivitySearch, whenever you click the item on search you need to send the result to MainActivity:
shoppinListAdapter.SetOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Intent intent=new Intent();
// send data if you want
//intent.putExtra("DATA", yourdata);
setResult(MainActivity.REQUEST_CODE, intent);
finish(); // close the SearchActivity
}

Android use ActivityForResult in ArrayAdapter with AlertDialog

In my ArrayAdapter I have an AlertDialog with a button. Now I want to use ActivityForResult for that. In this simple code I can use an Intent to view the other Activity but I can not get passed data from it in ArrayAdapter.
public class AdapterReceiveSMS extends ArrayAdapter<ReceivedItemStructure> {
private myDialog dialog;
public AdapterReceiveSMS(ArrayList<ReceivedItemStructure> array) {
super(G.context, R.layout.rsms, array);
}
/* ----- Clicking on Forward Button ----- */
forward_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(
G.activityDialogContext);
View vForward = G.inflater.inflate(R.layout.forward, null);
builder.setView(vForward);
final AlertDialog sms_dialog = builder.create();
sms_dialog.show();
from_file.setOnClickListener ( new View.OnClickListener () {
#Override
public void onClick (View v) {
Intent fileBrowser = new Intent(G.activity,ActivityFileBrwoser.class);
G.activity.startActivityForResult ( fileBrowser, 1 );
}
} );
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
}
}
onActivityResult in an overridden method of Activity class and called when an activity you launched exits, giving you the requestCode you started it with, the resultCode it returned, and any additional data from it.”
you started the activity using this code
G.activity.startActivityForResult ( fileBrowser, 1 );
you must put your onActivityResult method in your calling activity ( I mean activity in which you are creating the object of AdapterReceiveSMS class. )
You can't add a callback method to a class and hope that the system calls it. onActivityResult belongs to your Activity which then can pass the information to your adapter.

DialogFragment is dismissed right after show

I created a DialogFragment which should be shown after onActivityResult is called.
But right after dialog.show() is called, the Dialog dismissed automatically for no reason.
I am using the BarcodeScanner lib to scan a QR-Code, in onActivityResult I just save the Data (I also tried to show the Dialog at this point, but it didn't worked.)
if ((requestCode == REQUEST_BARCODESCANNER) && (resultCode == RESULT_OK)) {
mBarcodeScanned = true;
mBarcodeScanResult = getBarcodeScannerResult(data.getExtras());
}
in onResume I am checking now for this variables:
if(mBarcodeScanResult == null && mBarcodeScanned){
mBarcodeScanned = false;
showDialog(MyDialogFragment.getInvalidQrCodeDialog(this));
} else if(mBarcodeScanResult != null && mBarcodeScanned){
showDialog(MyDialogFragment.getSomeDialog(this, v1, v2));
}
in showDialog() I just call show:
dialog.show(getSupportFragmentManager(), MyDialogFragment.class.getSimpleName());
Now it should show the Dialog, if a QR-Code was scanned.
For some reason right after dialog.show() I checked onDismiss() inside of the MyDialogFragment class, and it was called as well, but I really don't know why?
The MyDialogFragment is using the onCreateDialog methode, which creates AlertDialogs to return. The methode getSomeDialog() and getInvalidQrCodeDialog() are just instanciate the Fragment.
EDIT: the MyDialogClass
public class MyDialogFragment extends DialogFragment {
private static final String BUNDLE_DIALOG_TYPE = "bundle_dialog_type";
private DialogType mDialogType;
public enum DialogType{
QR_CODE_INVALID, SOME_DIALOG
}
public static Fragment getInvalidQrCodeDialog(final Context context) {
Bundle args = new Bundle();
args.putString(BUNDLE_DIALOG_TYPE, DialogType.QR_CODE_INVALID.name());
return MyDialogFragment.instantiate(context, MyDialogFragment.class.getName(), args);
}
public static Fragment getSomeDialog(final Context context) {
Bundle args = new Bundle();
args.putString(BUNDLE_DIALOG_TYPE, DialogType.SOME_DIALOG.name());
return MyDialogFragment.instantiate(context, MyDialogFragment.class.getName(), args);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
handleArguments();
}
private void handleArguments() {
final Bundle arguments = getArguments();
if(arguments != null) {
mDialogType = DialogType.valueOf(arguments.getString(BUNDLE_DIALOG_TYPE, DialogType.SOME_DIALOG.name()));
}
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
switch(mDialogType){
case QR_CODE_INVALID: return DialogHelper.showQRCodeInvalidDialog(getActivity());
case SOME_DIALOG: return DialogHelper.showSomeDialog(getActivity());
default: return null;
}
}
}
and the DialogHelper does something like this:
public static AlertDialog showQRCodeInvalidDialog(final Context context){
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(R.string.barcode_invalid);
builder.setTitle(R.string.barcode_invalid_title);
builder.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
return builder.create();
}
The problem seems to be the support-package DialogFragment.
I just changed it from support to the original DialogFragment and everything worked like expected.

Android: startActivityForResult & setResult for a view class and an activity class

I am confused and have no idea on how to use the startActivityResults and setResults to get data from previous activity. I have a view class and a activity class.
Basically in my view class i have this dialog and it will actually start the activity class called the colorActivity class. When user selects yes also it will pass the name of the selected circle to the colorActivity class. At the colorActivity class, users are allowed to enter color code for a particular circle and i would like to pass the color code back to the view class. I have problems passing values from activity back to view using the startActivityForResult and setResult method. Adding on, how to make use of the fetched data afterthat?
my code are as follows
Ontouchevent code from my view class:
#Override
public boolean onTouchEvent(MotionEvent event) {
x = event.getX();
y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
for (int i = 0; i < circles.size(); i++) {
if (circles.get(i).contains(x, y)) {
circleID = i;
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
AlertDialog.Builder builder = new Builder(
getContext());
final EditText text = new EditText(getContext());
builder.setTitle("Adding colors to circles").setMessage(
"Proceed to Enter color");
builder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface di,
int i) {
Intent intent = new Intent(
getContext(),
colorActivity.class);
intent.putExtra("circlename", circleNameList.get(circleID));
startActivityForResults(intent, 1); // error incurred here : The method startActivityForResult(Intent, int) is undefined for the type new DialogInterface.OnClickListener(){}
}
});
builder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface di,
int i) {
}
});
builder.create().show();
}
}, 3000);
break;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) { // Please, use a final int instead of hardcoded
// int value
if (resultCode == RESULT_OK) {
ccode = (String) data.getExtras().getString("colorcode");
}
}
}
public static String getColorCode() {
return ccode;
}
In the colorActivity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_ecolor);
circlenametextview = (TextView)findViewById(R.id.circlenametextview);
String circlename = super.getIntent().getStringExtra("circlename");
circlenametextview.setText(circlename);//get the circle name
savebutton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(colorActivity.this, ?????);//how to return back to the view class?
colorcode = colorEditText.getText().toString();// I am able to get value right up till this point
Intent resultIntent = new Intent();
resultIntent.putExtra("colorcode", colorcode );
setResult(Activity.RESULT_OK, resultIntent);
finish();
}// onclick
});
}
After correcting the other code so that you can run the program, you can retrieve parameters back from your activity colorActivity in this way:
Step1: return some value from colorActivity
Intent resultIntent = new Intent();
resultIntent.putExtra("NAME OF THE PARAMETER", valueOfParameter);
...
setResult(Activity.RESULT_OK, resultIntent);
finish();
Step 2: collect data from the Main Activity
Overriding #onActivityResult(...).
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) { // Please, use a final int instead of hardcoded int value
if (resultCode == RESULT_OK) {
String value = (String) data.getExtras().getString("NAME OF THE PARAMETER");
References
http://developer.android.com/training/basics/intents/result.html
How to manage `startActivityForResult` on Android?
http://steveliles.github.io/returning_a_result_from_an_android_activity.html
STARTACTIVITYFORRESULT IS NOW DEPRECATED
Alternative to it and recommended solution is to use Activity Result API
You can use this code, written in Kotlin language:
Create ResultLauncher:
private var resultLauncher =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == Activity.RESULT_OK) {
val data: Intent? = result.data
if (null != data && data.getBooleanExtra("REFRESH_PAGE", false)) {
//do your code here
}
}
}
start Activity by using above result launcher:
val intent = Intent(this, XYZActivity::class.java)
resultLauncher.launch(intent)
Return result from XYZActivity by
val resultIntent = Intent()
resultIntent.putExtra("REFRESH_PAGE", true)
setResult(Activity.RESULT_OK, resultIntent)
finish()
try using
ActivityName.this.startActivityForResult(intent,int)
Oh, and 1 small thing, in your code you have used
startActivityForResults(intent,int) ..replace that with
startActivityForResult(intent,int)

Categories

Resources