Search code examples
androidsaving-data

Saving list data composed of individual buttons


I've made a list made of TextViews and Buttons, made that when a person clicks on a button, a fragment opens and there is a list of values he can select. The problem is when i press on another button to select a value again for a different field, the previous value disappears. So the question would be how to save the fragments values, and keep it saved until the app is closed ?

    priceButton.setOnClickListener(new OnClickListener() {
  @Override
  public void onClick(View view) {
    PriceFragment priceFragment = new PriceFragment();
    getSupportFragmentManager().beginTransaction().replace(R.id.fragmentContainer, priceFragment).commit();
    setToHideElements();
  }
});

yearButton.setOnClickListener(new OnClickListener() {
  @Override
  public void onClick(View view) {
    YearFragment yearFragment = new YearFragment();
    getSupportFragmentManager().beginTransaction().replace(R.id.fragmentContainer, yearFragment).commit();
    setToHideElements();

  }
});

this is the year fragment

    yearEndListView.setOnItemClickListener(new OnItemClickListener() {
  @Override
  public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
    Intent intent = new Intent(getActivity().getBaseContext(), MainMenuActivity.class);
    String yearTo = yearList[i].toString();
    int yearTint = Integer.valueOf(yearTo);

    if (combinedYear != null) {
      combinedYear = combinedYear + " " + yearTo;
      intent.putExtra("Years", combinedYear);
      getActivity().startActivity(intent);

    } else {
      combinedYear = null;
      combinedYear = yearTo;
    }


    }
});

this is the method to retrive data

  private void retriveDataFromFragment(){
Intent intent = getIntent();
String fragmentDataPrice = intent.getStringExtra("PriceData");
String fragmentDataYear = intent.getStringExtra("Years");

if(fragmentDataPrice != null){
  priceButton.setText(fragmentDataPrice);
} else {}
if (fragmentDataYear != null){
  yearButton.setText(fragmentDataYear);
} else {}


}

I use RetriveDataFromFragment method in OnResume method.

Thank you, for your time.


Solution

  • I got the anwser if someone else needs a similar menu, all you have to do is create a class that extends Application, and include into your manifest (the part with application tags). From there you just use getters and setters and all is well.