Search code examples
androidcardview

Saving a cardview programmatically even after closing the activity


I am very new to android and I am trying to make CardView by programmatically, I am using Fragment. By setting an OnClick on the button I am able to create cards in my layout. The issue is after closing the activity cards are not showing.

How can I save the cards, so after closing the activity cards should be there?

public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  getActivity().setTitle("Okhlee");
}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
  view = inflater.inflate(R.layout.hawker_jobs_fragment_layout, container, false);
  context = getContext();
  button = (Button) view.findViewById(R.id.hawker_job_add_card_view_button);
  button.setOnClickListener(this);
  relativeLayout = (RelativeLayout) view.findViewById(R.id.hawker_job_relative_layout);

  return view;
}

@Override
public void onClick(View v) {
  createCardView();
}

/*Adding cardview programmatically function */
private void createCardView() {
  CardView addedCardView = new CardView(context);
  layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, height);
  addedCardView.setLayoutParams(layoutParams);
  addedCardView.setPadding(10 ,10, 10, 10);
  addedCardView.setRadius(15);
  addedCardView.setCardBackgroundColor(Color.BLUE);
  addedCardView.setMaxCardElevation(30);
  addedCardView.setMaxCardElevation(6);

  relativeLayout.addView(addedCardView);
}

Sorry for my bad English.


Solution

  • You can use SharedPreferences in order to know whether you should display the card.

    Here's a sample code using your original one -

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.hawker_jobs_fragment_layout, container, false);
        context = getContext();
        button = (Button) view.findViewById(R.id.hawker_job_add_card_view_button);
        button.setOnClickListener(this);
        relativeLayout = (RelativeLayout) view.findViewById(R.id.hawker_job_relative_layout);
    
        SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
        boolean shouldDisplayCard = sharedPref.getBoolean("should_display_card", false);
    
        if(shouldDisplayCard)
            createCardView();
    
        return view;
    }
    
    @Override
    public void onClick(View v) {
    
        SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putBoolean("should_display_card", true);
        editor.apply();
    
        createCardView();
    }