Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I save values of editText that are dynamically created in a dialog Window within an xml file? - Android

Tags:

android

I have created 2 classes and one Interface. One Interface that handles dialog clicks,a MainActivity class that hold a button and a textView. The MainActiviy class instantiates my second class(FireMissilesFragment) which contains an AlertDialog as a fragment. In the FireMisslesFragment I have dynamically created EditText. The problem with my app is that when I call (onsavenstancestate) in my mainActivity class in which FireMissilesFragment is instantiated in, i try to save my editText values so that when the popup closes and I restart it, the values of editText will maintain it's values once the popup opens again.

I have tried (onSaveInstanceState) method and the values hold;however, it is yet possible for me to recreate what was destroyed once the dialog is initiated again.Can Someone please shed some light on this matter.

Here is my code:

//===============================Interface=====================================//

        public interface NoticeDialogListener {
public void onDialogPositiveClick(DialogFragment dialog,EditText[] editText);
public void onDialogNegativeClick(DialogFragment dialog);
     }

//==========================MainActivity Class=============================//

    import android.os.Bundle;
    import android.support.v4.app.DialogFragment;
    import android.support.v4.app.FragmentActivity;
    import android.util.Log;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;


          public class MainActivity extends FragmentActivity implements   `               NoticeDialogListener{ 

     private  EditText[] _edText;
     private TextView _tv;

     private Multiplication multi;
     private Double[] s;
     private String s1;
     public static final String _SCORE1 = "score1";
     public static final String _SCORE2 = "score2";


     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);

         setContentView(R.layout.activity_main);
                _tv = (TextView)findViewById(R.id.textView1);
               Button dAction = (Button)findViewById(R.id.button1);

                  s = new Double[2];


             dAction.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {//open();
        confirmFireMissiles();


        }

              });//ssetOnclickLi...
    ///success thank god.

            //===================================================//


              }
      public void confirmFireMissiles() {

    DialogFragment newFragment = new FireMissilesDialogFragment();
    newFragment.show(getSupportFragmentManager(),"ff");

         }//confirmFireMisslesClosing brace

         // The below is what happens when the Button "multiply" in 
             Dialog window pops up.
@Override
public void onDialogPositiveClick(DialogFragment dialog,EditText[] 
                     editText) {    


    _edText = editText; // is this association

         multi = new Multiplication();
       try{ 
      // gets the text and stores to string array.

          s[0]=Double.parseDouble(_edText[0].getText().toString());
     s[1]=Double.parseDouble(_edText[0].getText().toString());
     Log.d("hello", String.valueOf(s[0]));


    }catch(NumberFormatException e){
              _tv.setText("please Insert an Number and calculate  again"); // 
        Log.d("Error", "place in numbers please");
    } 
        s1 = String.valueOf(multi.multiply(s[0],s[1]));
        //set Textview to s1.
                 _tv.setText(s1);
             }
@Override
public void onDialogNegativeClick(DialogFragment dialog) {}

}

//================================================================================// public class FireMissilesDialogFragment extends DialogFragment { private AlertDialog.Builder builder; private EditText[] _edText; // enable when ready private NoticeDialogListener _mListener; public static final String _SCORE1 = "score1"; public static final String _SCORE2 = "score2"; private Double[] s;

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the Builder class for convenient dialog construction
        builder = new AlertDialog.Builder(getActivity());
           //shows added content to dialog.
     //  d = new String[2];
             s = new Double[2];




    if(savedInstanceState !=null){


   s[0] =  Double.parseDouble(savedInstanceState.getString(_SCORE1));
  s[1] = Double.parseDouble(savedInstanceState.getString(_SCORE2));
       Log.d("Hey",String.valueOf(s[0]));

     _edText[0].setText(String.valueOf(s[0]));
        showIt();



    }else{
         showIt();

    }
          //sets the characterisitcs of  the dialogue.
        builder.setTitle("We are all stars of the show.");
        builder.setMessage( "we are strong")

             .setPositiveButton("Multiply", new  
               DialogInterface.OnClickListener(){
         public void onClick(DialogInterface dialog, int id) {

                    // enable when ready


   _mListener.onDialogPositiveClick(FireMissilesDialogFragment.this,_edText); 

                   }
               });

        // Create the AlertDialog object and return it

             return builder.create();
    }

 public  void showIt(){

// This piece of code creates a Linear layout that is suppose to show in a dialogue popup. LayoutParams param = new
LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1.0f); LinearLayout layout= new LinearLayout(getActivity()); layout.setLayoutParams(param); layout.setOrientation(LinearLayout.VERTICAL); layout.setBackgroundColor(Color.BLACK);

          // Dynamically place EditText efficiently Inside Linear Layout.
          _edText = new EditText[4];
           for (int i = 0;i< _edText.length;i++) {

         _edText[i] = new EditText(getActivity());
         _edText[i].setInputType(InputType.TYPE_CLASS_NUMBER | 
              InputType.TYPE_NUMBER_FLAG_DECIMAL); 
         _edText[i].setTextSize(20)
        try{
         s[i] =Double.parseDouble(   
                                  _edText[i].getText().toString());
        }catch(NumberFormatException e){
        //  Log.d("hello", "wrong input");
        }
         layout.addView(_edText[i]);
            }
         builder.setView(layout);
            }
   //============================================== Look over this code======////////////
   @Override
    public void onAttach(Activity activity) {
       super.onAttach(activity);
         //Verify that the host activity implements the callback interface
        try {
          //   Instantiate the NoticeDialogListener so we can send events to the host
            _mListener = (NoticeDialogListener) activity;
        } catch (ClassCastException e) {
            // The activity doesn't implement the interface, throw exception
            throw new ClassCastException(activity.toString()
                   + " must implement NoticeDialogListener");
        }
    }


       @Override
   public void onSaveInstanceState(Bundle savedInstanceState) {
        // Save the user's current game state

            savedInstanceState.putDouble(_SCORE1,s[0]);
        savedInstanceState.putDouble(_SCORE2,s[1]);
        super.onSaveInstanceState(savedInstanceState);
    }

}
like image 836
HRo Avatar asked Nov 29 '25 06:11

HRo


1 Answers

You could probably use SharedPreferences and store the information there, and then set the text of the text edit to the result of the shared preferences? or did I get the whole idea wrong?

here is an example of a simple save function:

  SharedPrefrences scores = getSharedPreferences("key_name_here", Context.MODE_PRIVATE);
  SharedPreferences.Editor editor = scores.edit();
  editor.putInt("key1", key1Var);
  editor.putInt("key2", key2Var);
  editor.commit();

and to retrive:

  Var = getPrefrences(Context.MODE_PRIVATE).getInt("key1",default value);

That should probably do the trick

like image 150
Baruch Avatar answered Nov 30 '25 18:11

Baruch