I have a Button
that creates EditText
s dynamically. I'm not having any problems creating them when I run the app but none of the created EditText
s are being saved when I close the app and reopen it. Here's my code:
public class app extends ActionBarActivity {
Button add;
LinearLayout linearLayout1;
static int createEditText;
public static final String TAG = "MyPrefs" ;
public static final String key1 = "numberOfEditTexts"; //Added this
SharedPreferences sharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_app);
linearLayout1 = (LinearLayout)findViewById(R.id.linearLayout1);
add = (Button) findViewById(R.id.add);
add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
createEditText();
}
});
}
public void createEditText() {
Log.i("ET", "ET created");
createEditText++;
if(createEditText > 6) {
Toast.makeText(this, "You have reached the maximum fields",
Toast.LENGTH_LONG).show();
return;
}
LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayout1);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
params.setMargins(0, 12, 0, 0);
EditText edtTxt = new EditText(this);
int maxLength = 8;
edtTxt.setHint("New ET1");
edtTxt.setLayoutParams(params);
edtTxt.setBackgroundColor(Color.WHITE);
edtTxt.setInputType(InputType.TYPE_CLASS_DATETIME);
edtTxt.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
InputFilter[] fArray = new InputFilter[1];
fArray[0] = new InputFilter.LengthFilter(maxLength);
edtTxt.setFilters(fArray);
edtTxt.setGravity(Gravity.CENTER);
layout.addView(edtTxt);
edtTxt.setId(createEditText);
}
@Override //Added this
protected void onPause() {
super.onPause();
Log.i("Pause", "onPause()");
System.out.println("EditText = " + createEditText);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(key1, createEditText);
editor.commit();
}
@Override //Added this
protected void onResume(){
super.onResume();
Log.i("Resume", "onResume()");
System.out.println("EditText = " + createEditText);
sharedPreferences.getInt(key1, createEditText);
}
You should keep these two in your class first. Next, create a
SharedPreference
object in the class.In your
onCreate()
method, initialize this:And you can add the value to this either on your button press or on your
onPause
method.To retrieve this value at the beginning of the next time when you want to display the number of
EditText
s that you left the program with, do this:Similarly, if you want to store the contents of the
EditText
s, you could store them in the sameSharedPreference
object.Edit
The
for
loop you added (running from 0 to 1) is not necessary.