Pass value from activity to CustomDialog class - android

Hi i want to pass a value "username" which i saved through SharedPreferences in my activity to a EditText in a CustomDialog class.
Meaning i want to use EditText.settext (username) in my CustomDialog class.
Can somebody help me to achieve this?
Thank you.
SharedPreference code in Main activity:
public class AndroidLogin extends Activity implements OnClickListener {
public SharedPreferences mPrefs;
...
#Override
protected void onPause() {
super.onPause();
Editor e = mPrefs.edit();
e.putString(USERNM, username);
e.commit();
}
}
Now i want to set the value "USERNM" to the EditText in my CustomDialog class:
public class MyCustomForm extends Dialog {
public SharedPreferences mPrefs;
...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(com.sencide.R.layout.inlogdialog);
EditText userTest = (EditText)findViewById(R.id.txtUserName);
mPrefs = getSharedPreferences("PREFS_NAME", this.MODE_PRIVATE); // does not work
String text = mPrefs.getString("USERNM", "");
userTest.setText(text);
}
}
CustomDialog:
import android.app.Dialog;
...
public class MyCustomForm extends Dialog {
String mTextChange;
public SharedPreferences mPrefs;
public interface ReadyListener {
public void ready(String user, String pass, boolean save);
}
private String usernm;
private String passwd;
private ReadyListener readyListener;
public MyCustomForm(Context context, String user, String pass, ReadyListener readyListener) {
super(context);
this.usernm = user;
this.passwd = pass;
this.readyListener = readyListener;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(com.sencide.R.layout.inlogdialog);
setTitle("Login:");
EditText userTest = (EditText)findViewById(R.id.txtUserName);
//mPrefs = getSharedPreferences("PREFS_NAME", this.MODE_PRIVATE);
//String text = mPrefs.getString("USERNM", "");
userTest.setText();
Button buttonConfrim = (Button) findViewById(R.id.btnConfirm);
buttonConfrim.setOnClickListener(new OKListener());
Button buttonCancel = (Button) findViewById(R.id.btnCancel);
buttonCancel.setOnClickListener(new CancelListener());
}
private class OKListener implements android.view.View.OnClickListener {
public void onClick(View v) {
EditText user = (EditText) findViewById(R.id.txtUserName);
EditText pass = (EditText) findViewById(R.id.txtpass);
CheckBox saveuser = (CheckBox) findViewById(R.id.saveuser);
readyListener.ready(user.getText().toString(),pass.getText().toString(), saveuser.isChecked());
MyCustomForm.this.dismiss();
}
}
private class CancelListener implements android.view.View.OnClickListener {
public void onClick(View v) {
MyCustomForm.this.dismiss();
}
}
}
Edit, in my main activity:
public void createDialog(Context context) {
SharedPreferences prefs = context.getSharedPreferences("mPrefs", Context.MODE_PRIVATE);
String user = prefs.getString("USERNM", "");
new MyCustomForm(context, user, user, null); // where the class that is calling this is aa OnTextChangeListener
}
This is how i show the Dialog:
public void getLoginData() throws Exception {
if (checkInternetConnection() == true){
MyCustomForm dialog = new MyCustomForm (this, "", "", new OnReadyListener());
dialog.setContentView(R.layout.inlogdialog);
dialog.show();
}

It's not recommended to pass context around (and by extension views). I would suggest creating a listener for your dialog, maybe something like an OnTextChangedListener#onChange(String).
Create the listener in your activity and pass it to your dialog. Then when the dialog is done, call the listeners onChange(String) method which will be set to fire an event to a UI thread handler to update the edit text. Conversely, you could just pass the handler.
public class MyDialog exteds Dialog implements Dialog.OnClickListener {
OnTextChangeListener mListener;
String mTextChange;
public MyDialog(OnTextChangeListener listener) {
mListener = listener;
// set up your stuff
setOnClickListener(this);
}
...
public void onClick(DialogInterface dialog) {
// Do what ever you need to do to get set mTextChange
mListener.onChange(mTextChange);
}
public static interface OnTextChangeListener {
void onChange(String textChange);
}
Here is how you pass it:
public void createDialog(Context context) {
SharedPreferences prefs = context.getSharedPreferences("MyPreferencesName", Context.MODE_PRIVATE);
String user = prefs.getString("what_ever_string_you_want", "fall_back_user_name");
new MyDialog(user, this); // where the class that is calling this is aa OnTextChangeListener
}

Related

How to set up a custom listener in a custom dialog for android?

I'm currently having trouble setting up my custom listener. I just want to pass a string from my dialog to my fragment (where I set up the dialog). I was trying to follow this tutorial: https://www.youtube.com/watch?v=ARezg1D9Zd0.
At minute 10:38, he sets up the listener.
This only problem is that in this, he uses DialogFragment, but I'm extending dialog and I don't know how to attach the context to the listener.
I've tried to set it up in onAttachedToWindow() and in the dialog constructor but it crashes.
What should I actually do?
I'd also appreciate it if someone could explain what the difference is between:
onAttachedToWindow() vs. onAttach(Context context).
Thanks!
MY CUSTOM DIALOG BOX:
public class NewListDialog extends Dialog implements View.OnClickListener {
private Activity c;
private TextInputLayout textInputLayout;
private TextInputEditText editText;
private LinearLayout dialog_root_view;
private Animation fade_out;
private String list_name;
private NewListDialogListener listener;
NewListDialog(Activity a) {
super(a);
this.c = a;
//ANOTHER ATTEMPT TO ATTACH CONTEXT TO LISTENER
//listener = (NewListDialogListener) a.getApplicationContext();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.new_list_dialog);
MaterialButton cancel = findViewById(R.id.dialog_new_list_cancel_button);
MaterialButton create = findViewById(R.id.dialog_new_list_create_button);
textInputLayout = findViewById(R.id.dialog_text_input_layout);
editText = findViewById(R.id.dialog_edit_text);
dialog_root_view = findViewById(R.id.dialog_root);
fade_out = AnimationUtils.loadAnimation(c, R.anim.fade_out_dialog);
editText.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View view, int i, KeyEvent keyEvent) {
if (isTextValid(editText.getText())) {
textInputLayout.setError(null);
return true;
}
return false;
}
});
cancel.setOnClickListener(this);
create.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
//Cancel Button
case R.id.dialog_new_list_cancel_button:
dialog_root_view.startAnimation(fade_out);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
dismiss();
}
}, 200);
break;
//Create Button
case R.id.dialog_new_list_create_button:
if (!isTextValid(editText.getText())) {
textInputLayout.setError(c.getString(R.string.dialog_error));
} else {
textInputLayout.setError(null);
//record input string
list_name = editText.getText().toString();
//send information to parent activity
//What to put here?
listener.createListName(list_name);
dismiss();
}
break;
default:
break;
}
}
private boolean isTextValid(#Nullable Editable text) {
return text != null && text.length() > 0;
}
//ATTEMPT TO ATTACH CONTEXT TO LISTENER
#Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
try {
listener = (NewListDialogListener) c.getBaseContext();
} catch (ClassCastException e) {
throw new ClassCastException(c.getBaseContext().toString() + "must implement ExampleDialogListener");
}
}
public interface NewListDialogListener {
void createListName(String listname);
}
}
In case you define a custom dialog then you can declare a method to allow other components call it or listen events on this dialog. Add this method to you custom dialog.
public void setNewListDialogListener(NewListDialogListener listener){
this.listener = listener;
}
NewListDialog.java
public class NewListDialog extends Dialog implements View.OnClickListener {
private Activity c;
private TextInputLayout textInputLayout;
private TextInputEditText editText;
private LinearLayout dialog_root_view;
private Animation fade_out;
private String list_name;
private NewListDialogListener listener;
NewListDialog(Activity a) {
super(a);
this.c = a;
}
public void setNewListDialogListener(NewListDialogListener listener) {
this.listener = listener;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.new_list_dialog);
MaterialButton cancel = findViewById(R.id.dialog_new_list_cancel_button);
MaterialButton create = findViewById(R.id.dialog_new_list_create_button);
textInputLayout = findViewById(R.id.dialog_text_input_layout);
editText = findViewById(R.id.dialog_edit_text);
dialog_root_view = findViewById(R.id.dialog_root);
fade_out = AnimationUtils.loadAnimation(c, R.anim.fade_out_dialog);
editText.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View view, int i, KeyEvent keyEvent) {
if (isTextValid(editText.getText())) {
textInputLayout.setError(null);
return true;
}
return false;
}
});
cancel.setOnClickListener(this);
create.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
//Cancel Button
case R.id.dialog_new_list_cancel_button:
dialog_root_view.startAnimation(fade_out);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
dismiss();
}
}, 200);
break;
//Create Button
case R.id.dialog_new_list_create_button:
if (!isTextValid(editText.getText())) {
textInputLayout.setError(c.getString(R.string.dialog_error));
} else {
textInputLayout.setError(null);
//record input string
list_name = editText.getText().toString();
//send information to parent activity
//What to put here?
if (listener != null) {
listener.createListName(list_name);
}
dismiss();
}
break;
default:
break;
}
}
private boolean isTextValid(#Nullable Editable text) {
return text != null && text.length() > 0;
}
public interface NewListDialogListener {
void createListName(String listname);
}
}
In other components such as an activity which must implements NewListDialogListener.
NewListDialog dialog = new NewListDialog(this);
dialog.setNewListDialogListener(this);
If you don't want the activity implements NewListDialogListener then you can pass a listener instead.
NewListDialog dialog = new NewListDialog(this);
dialog.setNewListDialogListener(new NewListDialog.NewListDialogListener() {
#Override
public void createListName(String listname) {
// TODO: Your code here
}
});
In android Fragments and Activity has lifecycles. Fragments are hosted inside Activity and get the context of host activity via onattach method.
On the other hand Dialog is extended from Object (God class) without any lifecycle and should be treaded as an object.
If your activity is implementing NewListDialogListener then you can do
listener = (NewListDialogListener) a;
onAttachedToWindow : mean the dialog will be drawn on screen soon
and
getApplicationContext() will give you the context object of the application (one per app) which is surely not related with your listener and hence won't work
Reference :
Android DialogFragment vs Dialog
Difference between getContext() , getApplicationContext() , getBaseContext() and “this”
You can use RxAndroid instead of using listener, in this situation I use RxAndroid to get data from dialogs to activities or fragments.
Just need to create a PublishSubject and get the observed data. on activity or fragment :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PublishSubject<String > objectPublishSubject = PublishSubject.create();
objectPublishSubject.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.newThread())
.subscribe(this::onNext);
CustomDialog customDialog = new CustomDialog(this, objectPublishSubject);
customDialog.show();
}
private void onNext(String data) {
Log.i("DIALOG_DATA", data);
}
and you can create dialog like this :
public class CustomDialog extends Dialog implements View.OnClickListener {
private PublishSubject<String> subject;
public CustomDialog(#NonNull Context context, PublishSubject<String> subject) {
super(context);
this.subject = subject;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.custom_dialog);
findViewById(R.id.button).setOnClickListener(this);
}
#Override
public void onClick(View v) {
subject.onNext("Data");
dismiss();
}

Don't read sharedPreferences from another class

I'm trying to get my app to look first if shared preferences is set. If not it must open a page where you type them in, and then hopefully save them which I will use later. It looks like it either finds some shared preferences or my code is wrong because the main activity opens (the else statement executes).
Here is my Mainactivity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
boolean check = sharedPreferences.getBoolean("Check",false);
if(check){
//Intent intent;
Intent SharedPrefsIntent = new Intent(MainActivity.this, SharedPrefs.class);
startActivity(SharedPrefsIntent); }
else {
setContentView(R.layout.activity_main);
TextView brands = (TextView) findViewById(R.id.brands);
And here is the SharedPrefs:
public class SharedPrefs extends MainActivity {
//public static Context context;
EditText ed1,ed2,ed3;
Button b1;
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String Name = "nameKey";
public static final String Phone = "phoneKey";
public static final String Email = "emailKey";
SharedPreferences sharedpreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.shared_prefs);
ed1=(EditText)findViewById(R.id.editText);
ed2=(EditText)findViewById(R.id.editText2);
ed3=(EditText)findViewById(R.id.editText3);
b1=(Button)findViewById(R.id.button);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String n = ed1.getText().toString();
String ph = ed2.getText().toString();
String e = ed3.getText().toString();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, n);
editor.putString(Phone, ph);
editor.putString(Email, e);
editor.commit();
Toast.makeText(SharedPrefs.this,"Thanks",Toast.LENGTH_LONG).show();
}
});
}
}
I must be honest I'm not quite sure where I want Java to look for Shared preferences, "this makes the app run at least.
Inside the SharedPrefs{} class, declare the variable
public static boolean CHECK_VALUE = false;
In the same class inside onClick(View v) method after editor.commit();, set
CHECK_VALUE = true;
And in MainActivity{} class inside OnCreate() method
if(!SharedPrefs.CHECK_VALUE){
//SharedPreferences was not used before
Intent SharedPrefsIntent = new Intent(MainActivity.this, SharedPrefs.class);
startActivity(SharedPrefsIntent);
}
else {
//SharedPreference are already set
//Do your stuffs
}
Actually you don't need a SharedPreference to check here. If you really do, then put
editor.putBoolean("check", true);
insideOnClick() method of SharedPrefs{} class and to get it from or to use it in MainActivity
SharedPreferences sharedPreferences = getSharedPreferences(SharedPrefs.MyPREFERENCES, Context.MODE_PRIVATE);
Boolean Check = sharedPreferences.getBoolean("check", false);
if(!check){
//SharedPreferences was not used before
Intent SharedPrefsIntent = new Intent(MainActivity.this, SharedPrefs.class);
startActivity(SharedPrefsIntent);
}
else {
//SharedPreference are already set
//Do your stuffs
}

Starting activity with button

I'm trying to configure the button1 to change activity, but although I do not detect errors with eclipse, the button does not work, someone can tell me what is wrong thanks.
After the lprimo button there is' another button for data backup, I would not think the problem is caused by the presence of another button.
public class Aggiungi extends Activity implements OnClickListener {
private Button btn_save;
private EditText edit_turno,edit_ore;
private TextView edit_mese,edit_anno;
private DbHelper mHelper;
private SQLiteDatabase dataBase;
private String idturno,anno,mese,turno,ore;
private boolean isUpdate;
Spinner selectedMesi,selectedGiorni;
private final static String MY_PREFERENCES = "MyPref";
private final static String ANNO = "anno";
public void cambia (View view){
final Intent cambioTermini;
cambioTermini = new Intent (this, Cambio.class);
Button button=(Button)findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startActivity(cambioTermini);
}
});
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_activity);
SharedPreferences prefs = getSharedPreferences(MY_PREFERENCES, Context.MODE_PRIVATE);
Intent intent=getIntent();
String anno = prefs.getString(ANNO, "2014");
btn_save=(Button)findViewById(R.id.save_btn);
edit_mese=(TextView)findViewById(R.id.txtmese);
edit_anno=(TextView)findViewById(R.id.txtanno);
edit_turno=(EditText)findViewById(R.id.turno_editTxt);
edit_ore=(EditText)findViewById(R.id.ore_editTxt);
isUpdate=getIntent().getExtras().getBoolean("update");
if(isUpdate)
{
idturno=getIntent().getExtras().getString("ID");
mese=getIntent().getExtras().getString("Mese");
anno=getIntent().getExtras().getString("Anno");
turno=getIntent().getExtras().getString("Turno");
ore=getIntent().getExtras().getString("Ore");
edit_mese.setText(mese);
edit_anno.setText(anno);
edit_turno.setText(turno);
edit_ore.setText(ore);
}
btn_save.setOnClickListener(this);
mHelper=new DbHelper(this);
}
// saveButton click event
public void onClick(View v) {
mese=edit_mese.getText().toString().trim();
anno=edit_anno.getText().toString().trim();
turno=edit_turno.getText().toString().trim();
ore=edit_ore.getText().toString().trim();
if(anno.length()>0&& mese.length()>0 && turno.length()>0 &&ore.length()>0)
{
saveData();
}
else
As per my understanding, you want to launch 'Cambio' activity on button1 click. Try this.
public class Aggiungi extends Activity implements OnClickListener {
private Button btn_save;
private EditText edit_turno,edit_ore;
private TextView edit_mese,edit_anno;
private DbHelper mHelper;
private SQLiteDatabase dataBase;
private String idturno,anno,mese,turno,ore;
private boolean isUpdate;
Spinner selectedMesi,selectedGiorni;
private final static String MY_PREFERENCES = "MyPref";
private final static String ANNO = "anno";
public void cambia(){
final Intent cambioTermini;
cambioTermini = new Intent (this, Cambio.class);
// Start cambioTermini activity
startActivity(cambioTermini);
// close this activity
finish();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_activity);
SharedPreferences prefs = getSharedPreferences(MY_PREFERENCES, Context.MODE_PRIVATE);
Intent intent=getIntent();
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.button1:
cambia();
break;
}
}
}
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
public class Contact extends Activity
{
public ImageView btnlog1;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnlog1=(ImageView)findViewById(R.id.imageView2);
btnlog1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent l = new Intent(Contact.this,
AndroidDashboardDesignActivity.class);
startActivity(l);
Contact.this.finish();
}
});
}
}
Use this code and try like this.. This is simple code for intent changing for one activity to another.. let me know your ans..
I was expecting something like:
public void cambia (View view){
final Intent cambioTermini;
cambioTermini = new Intent (this, Cambio.class);
startActivity(cambioTermini);
}
since you have
<Button
android:id="#+id/button1"
//.. other paramters
android:onClick="cambia"
android:text="cambia" />

How to create a login page as always be logged in if once logged in?

I have a login page for my project.Here my requirement is,that login page always want to be logged-in,if once i log in.I have got some ideas through Google,ie., it recommended me to use shared-preference concept,right now i am following this concept and i have tried some code.
In my project the problem is after giving the proper username and password,it does not switch to another screen,at the same i am getting nothing on my log-cat too.How to achieve this concept?
Suggestions please..
please find my sources for reference
class SaveSharedPreferece
public class SaveSharedPreference
{
static final String PREF_USER_NAME= "username";
static SharedPreferences getSharedPreferences(Context ctx) {
return PreferenceManager.getDefaultSharedPreferences(ctx);
}
public static void setUserName(Context ctx, boolean userName)
{
Editor editor = getSharedPreferences(ctx).edit();
editor.putBoolean(PREF_USER_NAME, userName);
editor.commit();
}
public static String getUserName(Context ctx)
{
return getSharedPreferences(ctx).getString(PREF_USER_NAME, "");
}}
MainActivity.java
public class MainActivity extends Activity
{
Button btn;
EditText edt1,edt2;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void loginpage()
{
edt1 = (EditText)findViewById(R.id.editText_username);
edt2 = (EditText)findViewById(R.id.editText_password);
btn = (Button)findViewById(R.id.button_login);
btn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(edt1.getText().toString().length()!=0 && edt1.getText().toString().length()!=0)
{
Intent intvar = new Intent(v.getContext(), ResultActivity.class);
startActivity(intvar);
}
else
{
Toast.makeText(getApplicationContext(), "oops! empty..", Toast.LENGTH_SHORT).show();
}
}
});
if(SaveSharedPreference.getUserName(MainActivity.this).length() == 0)
{
// call Login Activity
loginpage();
}
else
{
// Call Next Activity
}
if (getIntent().getBooleanExtra("EXIT", false))
{
finish();
}
}
}
ResultActivity.java
public class ResultActivity extends Activity
{
Button btn_exit;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main1);
btn_exit = (Button)findViewById(R.id.button_exit);
btn_exit.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent(ResultActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);
}
});
}}
thanks for your precious time!..
You are saving boolean to SharedPreferences and getting String. How that is possible.
Better to save and get either boolean or String.
Change your setUserName() code in SaveSharedPreference class as below and it works
public static void setUserName(Context ctx, String userName)
{
Editor editor = getSharedPreferences(ctx).edit();
editor.putString(PREF_USER_NAME, userName);
editor.commit();
}
First add another field in SharedPrefernce file as password. Do same whatever you have done foe username(make it string instead of boolean in setter method) like setter and getter methods.
Create one method which will fetch values from sharedPrefernce like this :
private void validateUser(){
String username = SaveSharedPreference.getUserName(MainActivity.this);
String password = SaveSharedPreference.getPassword(MainActivity.this);
if (check_for_any_condition){
Intent intvar = new Intent(v.getContext(), ResultActivity.class);
startActivity(intvar);
}
}
Call this method in your oncreate method.
Hope it will help you.

Set value to a textview in the activity

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?

Categories

Resources