Search code examples
androidsharedpreferencesandroid-sharedpreferences

SharedPreference saving just one value


I'm trying to make favorites module in my app. If user click favorite button for a radio, this radio must displayed in Favorites screen. But just last clicked radio shown in Favorites screen. I want to save more than one radios in Favorites. Where I'm doing wrong? thanks in advance.

This is favorite button in RadioFragment

add_favorites_button= (Button) view.findViewById(R.id.add_favorites_button);
        add_favorites_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                SharedPreferences settings = getActivity().getSharedPreferences("PREFS", 0);
                SharedPreferences.Editor editor = settings.edit();
                editor.putString("radio_link", radio_play_link);
                editor.putString("radio_namee", radio_name);
                editor.commit();
            }
        });

And I'm trying to get these values and put in ArrayList in FavoritesFragment. To display received values, I sent them in textview to try.

public class FavoritesFragment extends Fragment {

    public FavoritesFragment() {
        // Required empty public constructor
    }

    TextView radio_name_txt, radio_link_txt;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view=  inflater.inflate(R.layout.fragment_favorites, container, false);

        List<String> radio_name_list = new ArrayList<>();
        List<String> radio_link_list = new ArrayList<>();
        SharedPreferences settings = getActivity().getSharedPreferences("PREFS",0);
        radio_name_list.add(settings.getString("radio_namee", ""));
        radio_link_list.add(settings.getString("radio_link", ""));


        radio_name_txt = (TextView) view.findViewById(R.id.radio_name_txt);
        radio_link_txt = (TextView) view.findViewById(R.id.radio_link_txt);
        String a= "";
        String b= "";

        for (int i =0; i<radio_name_list.size(); i++) {
            a = a +radio_name_list.get(i);
            b = b +radio_link_list.get(i);
        }

        radio_name_txt.setText(a);
        radio_link_txt.setText(b);

        return view;
    }


}

Solution

  • You have a lot of data and Shared Preferences is not the write option to store your data for 7000 items. Shared preference is good for easy and less frequent data storage, For your case you need to make a SQLite Database. If its totally new to your then pay a visit in Androids only Documentation Training in this link.