Question

I have a very basic doubt. I have a MainActivity from which, on a button click, I create a custom dialog which has four to five options. On clicking a value, I want to store it (say string value) such that the chosen option can be accessed from MainActivity when that dialog closes.

For this I am using the following method - I am declaring some static string values in MainActivity, which I will set inside the dialog, according to the text value option selected by the user in the dialog. For example, in MainActivity, I declare:

public static String strval = "";

and in the dialog, I set it using

MainActivity.strval = options[which];

where options is a String array containing string values of all options.

Is there a better way of doing this? I realize that using static variables in this way is not a good practice when making apps with multiple activities, but since I only have a single MainActivity in this app, is this method OK?

Was it helpful?

Solution

Setting a static variable of a particular activity is not advisable as this adds a dependency in your fragment. Fragments are supposed to be isolated and should be cohesive. So that it can be used by any activity.

Better way would be to have an interface DialogAction:

interface DialogAction{
 void onDialogAction(String option);
}

Let your activity implement this and write an implementation of the onDialogAction

void onDialogAction(String option){
//set an instance variable
}

and in DialogFragment declare an object of DialogAction:

private DialogAction listener;
public void setListener(DialogAction listener){
    this.listener=listener;
}

now on action just call

listener.onDialogAction(options[which]);

Don't forget to set Listener in you activity on fragment.

inside activity when you create new fragment also call:

fragment.setListener(this);//'this' here the is a reference to the Activity implementing DialogAction 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top