my onAttach() method assigns the context to the listener, however, my listener is null somehow. How can I fix this problem properly? I hope you can provide me the code with some instructions?
ChooseScreen class which initializes the dialog (In this case nameDialog):
public class ChooseScreen extends AppCompatActivity {
private Button vsFriend;
private Button vsAndroid;
private NameDialog.NameDialogListener listener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choose_screen);
vsFriend = findViewById(R.id.vsF);
vsAndroid = findViewById(R.id.vsA);
vsFriend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openDialog();
}
});
}
public void openDialog() {
NameDialog nameDialog = new NameDialog();
nameDialog.show(getSupportFragmentManager(), "example");
}
}
NameDialog class with getTexts interface:
public class NameDialog extends AppCompatDialogFragment {
private EditText firstPlayer;
private EditText secondPlayer;
private NameDialogListener listener;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
final View view = inflater.inflate(R.layout.layout_dialog, null);
firstPlayer = view.findViewById(R.id.edit_player1);
secondPlayer = view.findViewById(R.id.edit_player2);
builder.setView(view)
.setTitle("Names")
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
})
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String player1 = firstPlayer.getText().toString();
String player2 = secondPlayer.getText().toString();
listener.getTexts(player1, player2);
// Intent intent = new Intent(NameDialog.this.getActivity(), Game.class);
// startActivity(intent);
}
});
return builder.create();
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try{
listener = (NameDialogListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString() + "must implement");
}
}
public interface NameDialogListener {
void getTexts(String player1, String player2);
}
}
Game class which implements NameDialogListener and overrides the interface method(getTexts):
public class Game extends AppCompatActivity implements
NameDialog.NameDialogListener {
private TextView player1Name;
private TextView player2Name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
player1Name = findViewById(R.id.player1TextView);
player2Name = findViewById(R.id.player2TextView);
}
#Override
public void getTexts(String player1, String player2) {
player1Name.setText(player1);
player2Name.setText(player2);
}
}
Error: If I don't use try-catch block, the error will be NullPointerException because listener is null!
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.user.tictactoe, PID: 30462
java.lang.ClassCastException: com.example.user.tictactoe.ChooseScreen#1a0a489must implement
at com.example.user.tictactoe.NameDialog.onAttach(NameDialog.java:62)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1372)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1759)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1827)
at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:797)
at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2596)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2383)
at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2338)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2245)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:703)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6776)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1518)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)
When you attach your Fragment you attempt to get a Listener from your ChoooseScreen Activity. That Activity does not implement NameDialogListener, so you get a ClassCastException. In your examples you show another Activity, Game that does implement the listener, however any activity you add your Fragment in will need to implement the listener to work with your onAttach() code.
Short answer: if you want to show the Fragment in ChooseScreen, your code requires ChooseScreen to implement NameDialogListener.
onAttach will get the context of your parent activity. when you open your Dialog from ChooseScreen activity, the parent is ChooseScreen. The interface callback will be given to ChooseScreen itself. Then what you need to do is to call Intent with player1Name and player2Name.
Anyways I will share the code for you.
Your ChooseScreen
public class ChooseScreen extends AppCompatActivity implements NameDialog.NameDialogListener {
private Button vsFriend;
private Button vsAndroid;
private NameDialog.NameDialogListener listener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choose_screen);
vsFriend = findViewById(R.id.vsF);
vsAndroid = findViewById(R.id.vsA);
vsFriend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openDialog();
}
});
}
public void openDialog() {
NameDialog nameDialog = new NameDialog();
nameDialog.show(getSupportFragmentManager(), "example");
}
#Override
public void getTexts(String player1, String player2) {
Intent intent = new Intent(this, Game.class);
intent.putExtra("PLAYER_ONE", player1);
intent.putExtra("PLAYER_TWO", player2);
startActivity(intent);
}
}
Your NameDialog
public class NameDialog extends AppCompatDialogFragment {
private EditText firstPlayer;
private EditText secondPlayer;
private NameDialogListener listener;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
final View view = inflater.inflate(R.layout.layout_dialog, null);
firstPlayer = view.findViewById(R.id.edit_player1);
secondPlayer = view.findViewById(R.id.edit_player2);
builder.setView(view)
.setTitle("Names")
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
})
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String player1 = firstPlayer.getText().toString();
String player2 = secondPlayer.getText().toString();
listener.getTexts(player1, player2);
//TODO you can simply use below code and comment listener.getTexts();
// Intent intent = new Intent(NameDialog.this.getActivity(), Game.class);
// intent.putExtra("PLAYER_ONE", player1);
// intent.putExtra("PLAYER_TWO", player2);
// startActivity(intent);
}
});
return builder.create();
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
listener = (NameDialogListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString() + "must implement");
}
}
public interface NameDialogListener {
void getTexts(String player1, String player2);
}
}
Your Game
public class Game extends AppCompatActivity
/* implements NameDialog.NameDialogListener*/ {
private TextView player1Name;
private TextView player2Name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
player1Name = findViewById(R.id.player1TextView);
player2Name = findViewById(R.id.player2TextView);
player1Name.setText(
getIntent().getStringExtra("PLAYER_ONE"));
player2Name.setText(
getIntent().getStringExtra("PLAYER_TWO"));
}
// #Override
// public void getTexts(String player1, String player2) {
// }
}
Try this and let me know...
Related
I am working on an app and I am using a custom dialog which extends DialogFragment. This dialog will contain certain field that I want to pass to the parent activity. I tried implementing OnDismissListener but the parameter is a Dialog Interface.
Any Idea?
parent Activity:
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
BreakCreator mDialog = new BreakCreator();
mDialog.show(getSupportFragmentManager(), "start break Creator");
}
});
listener:
#Override
public void onDismiss(DialogInterface dialog) {
Log.d("debug", "in onDismiss");
BreakCreator mBreakCreator = BreakCreator.class.cast(dialog);// This MIGHT not work
//TODO cast and shit
if(!mBreakCreator.isCancelled() ){
int startMinute = mBreakCreator.getStartMinute();
int startHour = mBreakCreator.getStartHour();
int endMinute = mBreakCreator.getEndMinute();
int endHour = mBreakCreator.getEndHour();
String day = mBreakCreator.getDay();
Break mBreak = new Break(new ultramirinc.champs_mood.Time(startHour, startMinute),
new ultramirinc.champs_mood.Time(endHour, endMinute), day);
breakList.add(mBreak);
Log.d("created", "break added");
recyclerView.invalidate();
}else{
Log.d("debug", "is not cancelled");
}
}
Dialog Class:
public void onDismiss(final DialogInterface dialog) {
super.onDismiss(dialog);
final Activity activity = getActivity();
if (activity instanceof DialogInterface.OnDismissListener) {
((DialogInterface.OnDismissListener) activity).onDismiss(dialog);
}
}
Use a custom listener, below is an example on how this could be implemented. This is also explained in the Android Developer Guide.
public class CustomDialog extends DialogFragment {
public interface CustomListener{
void onMyCustomAction(CustomObject co);
}
private CustomListener mListener;
public void setMyCustomListener(CustomListener listener){
mListener = listener;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
...
Code to create dialog
...
}
#Override
public void onDismiss(DialogInterface dialog) {
if(mListener != null){
CustomObject o = new CustomObject();
mListener.onMyCustomAction(o);
}
super.onDismiss();
}
}
And when the custom dialog is created, set the listener.
CustomDialog awesomeDialog = new CustomDialog();
awesomeDialog.setMyCustomListener(new CustomDialog.CustomListener() {
#Override
public void onMyCustomAction(CustomObject o){
Log.i("TAG",o.toString());
}
});
I am trying to create a custom dialog using dialogFragment, here I am not be able to display the dialog. The main problem is overriden code is not getting called. Can anyone fix this issue. Here is my code:
BaseDialogFragment.java
public class BaseDialogFragment extends DialogFragment {
private int layoutId;
protected Activity mActivity;
public void setLayoutId(int layoutId){
this.layoutId = layoutId;
}
public BaseDialogFragment(){
}
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setStyle(BaseDialogFragment.STYLE_NO_TITLE, R.style.share_dialog);
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState){
View v = inflater.inflate(layoutId, container, false);
return v;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mActivity = activity;
}
public void initViews(View v){
getDialog().setCanceledOnTouchOutside(true);
}
}
CustomDialog.java:
#SuppressLint("ValidFragment")
public class CustomDialog extends BaseDialogFragment {
private String message;
private btnOkClick okClickListerner;
private TextView simpleMsg;
private WebView termsConditionWeb;
private Button okBtn;
Boolean isNormalDialog = false;
private Typeface fontClanProBold;
private View v;
private Context context;
public interface btnOkClick{
void clicked();
}
public CustomDialog(String message, btnOkClick okClickListerner, Boolean isNormalDialog){
this.message = message;
this.okClickListerner = okClickListerner;
this.isNormalDialog = isNormalDialog;
this.mActivity = null;
setLayoutId(R.layout.activity_custom_dialog);
initViews(v);
}
#Override
public void initViews(View v) {
super.initViews(v);
this.simpleMsg = (TextView) v.findViewById(R.id.simpleMsg);
this.termsConditionWeb= (WebView) v.findViewById(R.id.termsConditionWeb);
this.okBtn = (Button) v.findViewById(R.id.okBtn);
fontClanProBold = Typeface.createFromAsset(context.getAssets(), "fonts/ufonts.com_clanpro-bold.ttf");
Log.e("isNormal", isNormalDialog.toString());
if(isNormalDialog){
this.simpleMsg.setVisibility(View.VISIBLE);
this.simpleMsg.setText(message);
this.simpleMsg.setTypeface(fontClanProBold);
} else {
this.termsConditionWeb.setVisibility(View.VISIBLE);
this.termsConditionWeb.loadData(message, "text/html", "UTF-8");
}
setCancelable(false);
initEvent(v);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.mActivity = activity;
}
private void initEvent(View v){
okBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(okClickListerner != null){
okClickListerner.clicked();
}
dismiss();
}
});
}
public static void ShowDialog(FragmentManager fm, String message, btnOkClick okClickListerner, Boolean isNormalDialog){
CustomDialog dialog = new CustomDialog(message, okClickListerner, isNormalDialog);
dialog.show(fm, "");
}
}
MainActivity.java
inside a onClickListener
CustomDialog.ShowDialog(getSupportFragmentManager(), getResources().getString(R.string.message_register), new CustomDialog.btnOkClick() {
#Override
public void clicked() {
finish();
}
}, isNormalDialog);
It is bad practice to set values inside your Dialog constructor. Instead pass your values as arguments and initialize them on onCreate callback. Furthermore, you shall avoid saving instances of your activity on your fragment, it may lead to memory leaks. Instead I recomend you to create an interface on your CustomDialog or in your BaseDialogFragment that all activitys that uses them must implement. Then you need to implemnt onClickListener interface on your Dialog and inside it you can call mListener.onButtonClickListener(). See the example DialogFragment.
Your CustomDialog would look something like:
public class CustomDialog extends BaseDialogFragment {
private myFragmentInterface mListener;
public static CustomDialog newInstance(String message, Boolean isNormalDialog){
Bundle args = new Bundle();
args.putString(MESSAGE_ARG_KEY, message);
args.putBoolean(TYPE_ARG_KEY, isNormalDialog);
CustomDialog instance = new CustomDialog();
instance.setArguments(args);
}
#override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
message = getArguments().getStirng(MESSAGE_ARG_KEY);
isNormalDialog = getArguments().getBoolean(TYPE_ARG_KEY);
}
#override
public void onAttach(Activity activity){
super.onAttach();
try{
mListener = (myFragmentInterface) activity;
}catch(ClassCastException e){
throw new ClassCastException("activiy must implement myFragmentInterface");
}
}
public void onDetach(){
super.onDetach();
mListener = null;
}
public interface myFragmentInterface{
onButtonClickListener(String... params);
}
}
I created an AlertDialog :
public class MessageDialogView extends AlertDialog {
private Context ctxt;
private View contenu, titleBar;
#SuppressLint("NewApi")
public MessageDialogView(Context context, LayoutInflater inflater) {
super(context);
ctxt = context;
contenu = inflater.inflate(R.layout.msg_dialog, null);
titleBar = inflater.inflate(R.layout.custom_dialog_title, null);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setCustomTitle(titleBar);
setView(contenu, 0, 0, 0, 0);
setButton(DialogInterface.BUTTON_POSITIVE, ctxt.getResources().getString(R.string.button_ok), new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
}
public void setTitre(String titre) {
if (titre != null)
((TextView)titleBar.findViewById(R.id.titre)).setText(titre);
}
public void setMsg(String text){
if (text != null)
((TextView)contenu.findViewById(R.id.msgText)).setText(text);
}
}
The xml layout are very simple ( not necessary to copy their code here :) )
When I try to show the AlertDialog then nothing is showing : just the screen is darkened !
public class SyncActivity extends Activity {
private RadioButton webVersMobile = null;
private MessageDialogView dlg = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.syncro);
webVersMobile = (RadioButton) findViewById(R.id.webMobile);
dlg = new MessageDialogView(SyncActivity.this, getLayoutInflater());
}
...
public void displayError(String msg) {
dlg.setTitre(getString(R.string.titreErrMsgBox));
dlg.setMsg(msg);
dlg.show();
}
...
}
I call the dialog like this :
private class RequestTask extends AsyncTask<String, Void, String> {
...
#Override
protected String doInBackground(String... s_url) {
...
}
#Override
protected void onPostExecute(String result) {
if (error) {
displayError(result);
} else {
}
}
private void displayError(String msg) {
dlg.setTitre(getString(R.string.titreErrMsgBox));
dlg.setMsg(msg);
dlg.show();
}
}
So what is wrong in my code ?
You forgot to call show() method to display the dialog.
dlg = new MessageDialogView(SyncActivity.this, getLayoutInflater());
After this line write dlg.show(); in onCreate() method.
Ok , I found that the reason of my error is that I implemented the onCreate method. When I removed the implementation then the Dialog is shown :)
public class MessageDialogView extends AlertDialog {
private View contenu, titleBar;
#SuppressLint("InlinedApi")
public MessageDialogView(Context context, LayoutInflater inflater) {
super(context, AlertDialog.THEME_HOLO_DARK);
contenu = inflater.inflate(R.layout.msg_dialog, null);
titleBar = inflater.inflate(R.layout.custom_dialog_title, null);
setCustomTitle(titleBar);
setView(contenu, 0, 0, 0, 0);
setButton(DialogInterface.BUTTON_POSITIVE, context.getResources().getString(R.string.button_ok), new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
}
public void setTitre(String titre) {
if (titre != null)
((TextView)titleBar.findViewById(R.id.titre)).setText(titre);
}
public void setMsg(String text){
if (text != null)
((TextView)contenu.findViewById(R.id.msgText)).setText(text);
}
}
I got a method in which server-client communication is done "onClick" therefor i create a anonymous OnClickListener, and I want to publish a toast if the communication was successfull or not.
To do this I need the Acitivity in which context to publish the toast, and as I externalized the method, it must be given as a "this" argument to the Activity. But as I am inside an anonymous inner class I cannot access the this pointer of the Acitivity, and even though I stored it in a local final variable
private final Activity activity = this;
#Override
public void onCreate(Bundle savedInstanceState) {
lastResult = null;
super.onCreate(savedInstanceState);
setLayout(R.layout.main);
qrscan = (Button) findViewById(R.id.qrcodescan);
qrscan.setOnClickListener( new View.OnClickListener() {
public void onClick(View view) {
initiateScan(activity);
}
}
);
}
private AlertDialog initiateSend(Activity activity) {
if(lastResult != null) {
String[] arr = lastResult.content.split("/");
AlertDialog.Builder downloadDialog = new AlertDialog.Builder(activity);
String[] args = Util.filterString(arr,this);
downloadDialog.setTitle(args[0]);
downloadDialog.setMessage("Auftragsnummer:" + args[1]);
downloadDialog.setPositiveButton(getString(R.string.ja), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
try {
String send = lastResult.content;
send += "/uid/" + R.id.username + "/cid/" + R.id.password;
String result = Util.send(send);
//toaster(send);
Util.toaster(result,activity);
if(!(result.equals("OK") || result.equals("ok") || result.equals("Ok")))
throw new Exception("Bad Server Answer");
Util.toaster("Communication erfolgreich",activity);
} catch(Exception ex) {
ex.printStackTrace();
Util.toaster("Communication nicht erfolgreich",activity);
}
}
});
downloadDialog.setNegativeButton(getString(R.string.nein), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {}
});
return downloadDialog.show();
}
return null;
}
Any clue what i messed up?
declare variable before onCreate() like this
public class HelloAndroid extends Activity {
Activity activity = this; // declare here
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
EDITED
Activity mainActivity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setLayout(R.layout.main);
mainActivity = this;
lastResult = null;
qrscan = (Button) findViewById(R.id.qrcodescan);
qrscan.setOnClickListener( new View.OnClickListener() {
public void onClick(View view) {
initiateScan(mainActivity);
}
}
);
}
private AlertDialog initiateSend(final Activity activity) {
if(lastResult != null) {
String[] arr = lastResult.content.split("/");
AlertDialog.Builder downloadDialog = new AlertDialog.Builder(activity);
String[] args = Util.filterString(arr,this);
downloadDialog.setTitle(args[0]);
downloadDialog.setMessage("Auftragsnummer:" + args[1]);
downloadDialog.setPositiveButton(getString(R.string.ja), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
try {
String send = lastResult.content;
send += "/uid/" + R.id.username + "/cid/" + R.id.password;
String result = Util.send(send);
//toaster(send);
Util.toaster(result,activity);
if(!(result.equals("OK") || result.equals("ok") || result.equals("Ok")))
throw new Exception("Bad Server Answer");
Util.toaster("Communication erfolgreich",activity);
} catch(Exception ex) {
ex.printStackTrace();
Util.toaster("Communication nicht erfolgreich",activity);
}
}
});
downloadDialog.setNegativeButton(getString(R.string.nein), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {}
});
return downloadDialog.show();
}
return null;
}
On the event invocation of an activity, I opened an AlertDialog.Builder which lists an array of single choice items. When the user clicks any item, I want to set the same to a text view in the activity.
I tried this:
Activity class:
public MyActivity extends Activity implements onClickListener {
TextView item;
public void onCreate(Bundle state) {
super.onCreate(savedState);
setContentView(R.layout.main);
item = (TextView) findViewById(R.id.id_item);
item .setOnClickListener(this);
}
public void onClick(View v) {
new MyBuilder(this).show();
updateUI();
}
private void updateUI() {
item.setText(ItemMap.item);
}
}
Builder class:
public class MyBuilder extends AlertDialog.Builder implements OnClickListener{
Context context;
String[] items = {"pen", "pencil", "ruler"};
public MyBuilder(Context context) {
super(context);
super.setTitle("Select Item");
this.context = context;
super.setSingleChoiceItems(items, 0, this);
}
#Override
public void onClick(DialogInterface dialog, int position) {
ItemMap.item = items[position];
dialog.dismiss();
}
}
Mapping class:
public class ItemMap {
public static String item;
}
Here, MyBuilder is a subclass extending AlertDialog.Builder
updateUI() tries to set the value which user chooses from the list of items. But it did not work! updateUI() is called soon after the dialog is shown.
Could anyone help me out?
Thanks in advance!
With updateUI() in the current location, you are trying to access ItemMap.item before it is set in the AlertDialog.Builder. You're going to need some way to call back from the onClick in the AlertDialog.Builder to your main class - I would do it by adding an interface and then passing that in to your builder - like this:
Activity class:
public MyActivity extends Activity implements onClickListener, AlertBuilderCallback {
TextView item;
public void onCreate(Bundle state) {
super.onCreate(savedState);
setContentView(R.layout.main);
item = (TextView) findViewById(R.id.id_item);
item .setOnClickListener(this);
}
public void onClick(View v) {
new MyBuilder(this).addCallback(this).show();
updateUI();
}
public void updateUI() {
item.setText(ItemMap.item);
}
}
AlertBuilderCallback interface:
public interface AlertBuilderCallback {
public void updateUI();
}
Builder class:
public class MyBuilder extends AlertDialog.Builder implements OnClickListener{
Context context;
String[] items = {"pen", "pencil", "ruler"};
public MyBuilder(Context context) {
super(context);
super.setTitle("Select Item");
this.context = context;
super.setSingleChoiceItems(items, 0, this);
}
public MyBuilder addCallback(AlertBuilderCallback callBack) {
this.callBack = callBack;
return this;
}
#Override
public void onClick(DialogInterface dialog, int position) {
ItemMap.item = items[position];
if(this.callBack != null) {
this.callBack.updateUI();
}
dialog.dismiss();
}
}
Mapping class:
public class ItemMap {
public static String item;
}
move the updateUI() from MyActivity onClick(), to onClick for Dialog.
#Override
public void onClick(DialogInterface dialog, int position) {
ItemMap.item = items[position];
updateUI();
dialog.dismiss();
}
You're doing a load of things wrong here. You could move the updateUI() in to the onClick in your Activity, which should work, but here's another few things to think about:
Why is your AlertDialog.Builder in a different class? this is alright if you are going to extend it with some extra behaviour and use it in other places in your application - if if you are only using it here then you should declare it inside your activity.
Why is your ItemMap.item static? Is that a design decision?