tienow tienow - 6 months ago 34
Android Question

Android - Update TextView on dialog dimiss listener

I show a dialog where the user can enter a String value in an edittext and I want to display this value in an textview in the main layout after the dialog is dismissed. When the user clicks on the button "Ok" of the dialog, the textview is well refreshed, but I tried to do the same from the dismiss listener on the dialog it isn't, but I know the rest of the code is run. I tried to make it run on the mainthread but it didn't solve the problem. Here is the code, thanks for your help.

final Dialog dialogStatus = new Dialog(Activity.this);
dialogStatus.setContentView(R.layout.dialog_layout);

Button Bok = (Button) dialogStatus.findViewById(R.id.bt_dialog_ok);
final EditText ETname = (EditText) dialogStatus.findViewById(R.id.et_dialog);

Bok.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
update(String.valueOf(ETname.getText()));
dialogStatus.dismiss();
}
});
dialogStatus.setOnDismissListener(new DialogInterface.OnDismissListener() {

@Override
public void onDismiss(DialogInterface dialog) {
// TODO Auto-generated method stub
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
update(String.valueOf(ETname.getText()));
}
});
}
});
dialogStatus.show();
}

public void update(String etValue){
final SharedPreferences sharedPrefUnit = getSharedPreferences(SHARED_PREFS, 0);
SharedPreferences.Editor settings = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE).edit();
settings.putString(STRING_VALUE, etValue);
TextView.setText(sharedPrefUnitScore.getString(STRING_VALUE, etValue, ""));

settings.commit();
}

Answer
public void update(String etValue){
    final SharedPreferences sharedPrefUnit = getSharedPreferences(SHARED_PREFS, 0);
    SharedPreferences.Editor settings = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE).edit();
    settings.putString(STRING_VALUE, etValue);
    settings.commit();
    TextView.setText(etValue);
}

Because you were trying to get the value from shared preference before committing it. If you won't commit it then it won't save.