简体   繁体   中英

How do I iteratively add to a List on button click in java?

I want to add values to an array/list and then store these in shared preferences, to then display on another activity.

When I try my code it only seems to save the first value, and if I add more it just overwrites the value.

I do not want to create the List each time I click the button so I have put it at the very beginning.

If there isn't an existing value then the message should be added to the List and stored in shared preferences as Status_0, if there is an existing value then it should be added as Status_1 - but it's not. I think it is because it is not saving properly in the List but I'm not sure how to do that.

Here's my code:

public class EnterReadingsActivity extends AppCompatActivity implements     View.OnClickListener {
private EditText erTemperatureEditText;
private Button erSubmitBtn;
public List<String> values = new ArrayList<String>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Utils.onActivityCreateSetTheme(this);
    setContentView(R.layout.activity_enterreadings);
    init();

}

private void init() {
    erTemperatureEditText = (EditText) findViewById(R.id.erTemperatureEditText);
    erSubmitBtn = (Button) findViewById(R.id.erSubmitBtn);
    erSubmitBtn.setOnClickListener(this);
}

@Override
public void onClick(View view) {
    if (view.getId()==R.id.erSubmitBtn) {
        SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
        SharedPreferences.Editor editor = pref.edit();

        String message = erTemperatureEditText.getText().toString();

        editor.putInt("Status_size", values.size());
        int status_size = values.size();

        for (int i = status_size; i < status_size + 1; i++) {
            editor.putString("Status_" + i, message);
            values.add(message);
            editor.commit();
            }
        }
    }
}

Edit:

int status_size = values.size();
    for(int i = 0; i < status_size + 1; i++)
    {
        String value = values.get(i);
        if (value != null) {
            values.add(value);
            status_size++;

            String textView_i = "textView" + i;
            TextView textView_i = new TextView(this);
            textView_i.setLayoutParams(new ActionBar.LayoutParams(ActionBar.LayoutParams.WRAP_CONTENT,
                    ActionBar.LayoutParams.WRAP_CONTENT));
            textView_i.setText(value);
            historyBackgroundInside.addView(textView_i);

        }
    }

It is incorrect to use the sharedPreferences to pass data from one activity to another. The data are usually entered into an object (Bundle) which will be passed in the intent and then taken up in the next activity.

another way is to use the extras that works like Bundle

public class EnterReadingsActivity extends AppCompatActivity implements View.OnClickListener {
    private EditText erTemperatureEditText;
    private Button erSubmitBtn;
    public List<String> values = new ArrayList<String>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Utils.onActivityCreateSetTheme(this);
        setContentView(R.layout.activity_enterreadings);
        init();
    }

    private void init() {
        erTemperatureEditText = (EditText) findViewById(R.id.erTemperatureEditText);
        erSubmitBtn = (Button) findViewById(R.id.erSubmitBtn);
        erSubmitBtn.setOnClickListener(this);
     }

    @Override
    public void onClick(View view) {
           if (view.getId()==R.id.erSubmitBtn) {
               String message = erTemperatureEditText.getText().toString();
               values.add(message);
           }

           //Here you should enter the condition that allows you to
           //call the method to go to the next activity 
           //ex: click of a button, I have the list reaches a size
           //Add a example code
           if (values.size() == 10) {
               passDataAndGoInAnotherActivity();
           }
    }

    public void passDataAndGoInAnotherActivity () {
         Intent i = new Intent (this, NameOfYouNextActivity.class);

         i.putExtra("status_list", values);
         // Or use Bundle
         // Bundle bundle = new Bundle();
         // bundle.putSerializable("status_list", values);
         // i.putExtra("bundle", values)
         startActivity(i)
     }
}

to take in the other activity values using this code

 public class NameOfYourNextActivity extends AppCompatActivity {
     public List<String> values;
     public ListView listView;

     @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         Utils.onActivityCreateSetTheme(this);
         setContentView(R.layout.activity_nameoflayout);

         listview = (ListView) findViewById(R.id.listView);

         Intent intent = getIntent();

         //If you first method
         if (intent != null && intent.hasExtra("status_list")) {
              List<String> values = (List<String>)intent.getSerializableExtra("status_list")
         }
         //If you second method (Bundle)
         // if (intent != null && intent.hasExtra("Bundle")) {
         // Bundle bundle = intent. getBundleExtra("Bundle")
         // if (bundle != null && bundle.containsKey("status_list")) {
         // List<String> values = (List<String>)intent.getSerializableExtra(String name)
         // }

         if (values != null) {
             ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
    android.R.layout.simple_list_item_1, android.R.id.text1, values);
             listview.setAdapter(adapter);
         }
       }
    }

I did the update of the code to give you a solution that comes close to what you need..

Remember to create the next activity and insert it in the manifest.

Change the name of the class based on your activity and enter the correct layout name.

Remember to include in your layout a list view (change id in my code) that will allow you to print your values.

In this example it uses a simple adapter with a layout provided by Android, but you can create something custom.

Here you will find an excellent guide

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM