2

I am a newbie when it comes to sharedPreference. I have asked lots of questions concerning this, and have decided to start creating something while I ask question for further direction.

I have created sharedPrefernce. I have placed the fav_buttons for like/unlike. But when I click an item to be added to be added to favorites it will select but will not send the list to FavoriteActivity. How do I implement this sharedPreference to memorise my actions and save it in a list in the FavoriteActivity?

This is sharedPreference

public class PreferenceUtils {
    private static final PreferenceUtils ourInstance = new PreferenceUtils();
    private static SharedPreferences sharedPreferences;
    private static Context context;

    private static String APP_DATA_NAME = "SONGS";

    static PreferenceUtils getInstance() {
        return ourInstance;
    }

    private PreferenceUtils() {
    }

    public static void initialize(Context c) {
        sharedPreferences = c.getSharedPreferences(APP_DATA_NAME, Context.MODE_PRIVATE);
        context = c;
    }

    public static String getPreference(String key, String defaultValue) {
        if (sharedPreferences == null) return null;
        return sharedPreferences.getString(key, defaultValue);
    }

    public static boolean getPreference(String key, boolean defaultValue) {
        if (sharedPreferences == null) return false;
        return sharedPreferences.getBoolean(key, defaultValue);
    }

    public static Set<String> getPreference(String key) {
        if (sharedPreferences == null) return null;
        return sharedPreferences.getStringSet(key,null);
    }

    public static void setPreference(String key, String value) {
        if (sharedPreferences == null) return;
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(key, value);
        editor.commit();
    }

    public static void setPreference(String key, boolean value) {
        if (sharedPreferences == null) return;
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putBoolean(key, value);
        editor.commit();
    }
    public static void setPreference(String key, Set<String> value) {
        if (sharedPreferences == null) return;
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putStringSet(key, value);
        editor.apply();
    }

}

This is ListViewAdapter

public class ListViewAdapter extends BaseAdapter {

    //Variables
    Context mContext;
    LayoutInflater inflater;
    List<Model> modellist;
    ArrayList<Model> arrayList;
    int[] soundfile;

    //Constructor
    public ListViewAdapter(Context context, List<Model> modellist) {
        mContext = context;
        this.modellist = modellist;
        inflater = LayoutInflater.from(mContext);
        this.arrayList = new ArrayList<Model>();
        this.arrayList.addAll(modellist);
    }

    public class ViewHolder {
        TextView mTitleTv, mDescTv;
        ImageView mIconTv, favorite;
    }

    @Override
    public int getCount() {
        return modellist.size();
    }

    @Override
    public Object getItem(int i) {
        return modellist.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(final int i, View view, ViewGroup parent) {
        final ViewHolder holder;
        if (view == null) {
            holder = new ViewHolder();
            view = inflater.inflate(R.layout.row, null);

            //locate the views in row.xml
            holder.mTitleTv = (TextView) view.findViewById(R.id.mainTitle);
            holder.mDescTv = (TextView) view.findViewById(R.id.mainDesc);
            holder.mIconTv = view.findViewById(R.id.mainIcon);
            //initialize the favorite image view
            holder.favorite = view.findViewById(R.id.favorite);

            view.setTag(holder);
        } else {
            holder = (ViewHolder) view.getTag();
        }
        //set the result into textview
        holder.mTitleTv.setText(modellist.get(i).getTitle());
        holder.mDescTv.setText(modellist.get(i).getDesc());
        //Set the result in imagview
        holder.mIconTv.setImageResource(modellist.get(i).getIcon());

        if (modellist.get(i).isFavorite())
            holder.favorite.setImageDrawable(mContext.getResources().getDrawable(R.drawable.ic_heart));
        else
            holder.favorite.setImageDrawable(mContext.getResources().getDrawable(R.drawable.ic_heart_o));

        //listview soundfile file for songs in position
        soundfile = new int[]{R.raw.song_1, R.raw.song_2, R.raw.song_3, R.raw.song_4, R.raw.song_5, R.raw.song_6, R.raw.song_7, R.raw.song_8,};

        //fovarite/unfavorite

        holder.favorite.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (modellist.get(i).isFavorite())
                    holder.favorite.setImageDrawable(mContext.getResources().getDrawable(R.drawable.ic_heart_o));
                else
                    holder.favorite.setImageDrawable(mContext.getResources().getDrawable(R.drawable.ic_heart));

                modellist.get(i).setFavorite();
            }
        });

        //listview item clicks
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //code later
                if (modellist.get(i).getTitle().equals("Song 001 | This song lyrics 1")) {
                    //start NewActivity with title for actionbar and text for textview
                    Intent intent = new Intent(mContext, NewActivity.class);
                    intent.putExtra("actionBarTitle", "Song 001");
                    intent.putExtra("position", 1);
                    intent.putExtra("contentTv", "1. O THOU to whose all-searching sight\n" +
                            "The darkness shineth as the light,\n" +
                            "Search, prove my heart, it pants for thee;\n" +
                            "O burst these bonds and set it free!\n" +
                            "\n" +
                            "2. Wash out its stain, refine its dross,\n" +
                            "Nail my affections to the cross:\n" +
                            "Hallow each thought, let all within\n" +
                            "Be clean, as thou, my Lord, art clean.\n\n\n\n");
                    mContext.startActivity(intent);
                }
                if (modellist.get(i).getTitle().equals("Song 002 | This song lyrics 2")) {
                    //start NewActivity with title for actionbar and text for textview
                    Intent intent = new Intent(mContext, NewActivity.class);
                    intent.putExtra("position", 2);
                    intent.putExtra("actionBarTitle", "Song 002");
                    intent.putExtra("contentTv", "3 Saviour, where’er thy steps I see,\n" +
                            "Dauntless, untired, I’ll follow thee;\n" +
                            "O let thy hand support me still\n" +
                            "And lead me to thy holy hill!\n" +
                            "\n" +
                            "4 If rough and thorny be the way,\n" +
                            "My strength proportion to my day,\n" +
                            "Till toil and grief and pain shall cease,\n" +
                            "Where all is calm and joy and peace.\n\n\n\n");
                    mContext.startActivity(intent);
                }
                if (modellist.get(i).getTitle().equals("Song 003 | This song lyrics 3")) {
                    //start NewActivity with title for actionbar and text for textview
                    Intent intent = new Intent(mContext, NewActivity.class);
                    intent.putExtra("position", 3);
                    intent.putExtra("actionBarTitle", "Song 003");
                    intent.putExtra("contentTv", "1. O THOU to whose all-searching sight\n" +
                            "The darkness shineth as the light,\n" +
                            "Search, prove my heart, it pants for thee;\n" +
                            "O burst these bonds and set it free!\n" +
                            "\n" +
                            "2. Wash out its stain, refine its dross,\n" +
                            "Nail my affections to the cross:\n" +
                            "Hallow each thought, let all within\n" +
                            "Be clean, as thou, my Lord, art clean.\n\n\n\n");
                    mContext.startActivity(intent);
                }
                if (modellist.get(i).getTitle().equals("Song 004 | This song lyrics 4")) {
                    //start NewActivity with title for actionbar and text for textview
                    Intent intent = new Intent(mContext, NewActivity.class);
                    intent.putExtra("position", 4);
                    intent.putExtra("actionBarTitle", "Song 004");
                    intent.putExtra("contentTv", "This is song lyrics detail\n\n\n\n");
                    mContext.startActivity(intent);
                }
                if (modellist.get(i).getTitle().equals("Song 005 | This song lyrics 5")) {
                    //start NewActivity with title for actionbar and text for textview
                    Intent intent = new Intent(mContext, NewActivity.class);
                    intent.putExtra("position", 5);
                    intent.putExtra("actionBarTitle", "Song 005");
                    intent.putExtra("contentTv", "This is song lyrics detail\n\n\n\n");
                    mContext.startActivity(intent);
                }
                if (modellist.get(i).getTitle().equals("Song 006 | This song lyrics 6")) {
                    //start NewActivity with title for actionbar and text for textview
                    Intent intent = new Intent(mContext, NewActivity.class);
                    intent.putExtra("position", 6);
                    intent.putExtra("actionBarTitle", "Song 006");
                    intent.putExtra("contentTv", "This is song lyrics detail\n\n\n\n");
                    mContext.startActivity(intent);
                }
                if (modellist.get(i).getTitle().equals("Song 007 | This song lyrics 7")) {
                    //start NewActivity with title for actionbar and text for textview
                    Intent intent = new Intent(mContext, NewActivity.class);
                    intent.putExtra("position", 7);
                    intent.putExtra("actionBarTitle", "Song 007");
                    intent.putExtra("contentTv", "This is song lyrics detail\n\n\n\n");
                    mContext.startActivity(intent);
                }

            }
        });


        return view;
    }

    //filter
    public void filter(String charText) {
        charText = charText.toLowerCase(Locale.getDefault());
        modellist.clear();
        if (charText.length() == 0) {
            modellist.addAll(arrayList);
        } else {
            for (Model model : arrayList) {
                if (model.getTitle().toLowerCase(Locale.getDefault()).contains(charText)) {
                    modellist.add(model);
                }
            }
        }
        notifyDataSetChanged();
    }


}

This is row.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:gravity="center"
    android:padding="10dp">

    <ImageView
        android:id="@+id/mainIcon"
        android:src="@drawable/song"
        android:layout_width="0dp"
        android:layout_height="40dp"
        android:layout_weight="0.1"/>
    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:gravity="center"
        android:layout_weight="0.8"
        android:layout_marginLeft="5dp"
        android:layout_marginStart="5dp">

        <TextView
            android:id="@+id/mainTitle"
            android:textStyle="bold"
            android:textColor="#740303"
            android:text="Title"
            android:textSize="15sp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
        <TextView
            android:id="@+id/mainDesc"
            android:text="Description"
            android:textColor="#262626"
            android:textSize="12sp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />


    </LinearLayout>
<ImageView
    android:id="@+id/favorite"
    android:layout_width="0dp"
    android:layout_height="30dp"
    android:layout_weight="0.1"
    android:src="@drawable/ic_heart_o"/>
</LinearLayout>

This is MainActivity.java

public class MainActivity extends AppCompatActivity implements SearchView.OnQueryTextListener {
    private String TAG = "MainActivity ----- ; " ;
    // Store instance variables

    private int page;
    private ConsentForm form;

    ListView listView;
    ListViewAdapter adapter;
    String[] title;
    String[] description;
    int[] icon;
    ArrayList<Model> arrayList = new ArrayList<Model>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //initialize preferences
        PreferenceUtils.initialize(getApplicationContext());

        ActionBar actionBar = getSupportActionBar();
        actionBar.setTitle("Redeemed Songs");

        title = new String[]{"Song 001 | This song lyrics 1","Song 002 | This song lyrics 2","Song 003 | This song lyrics 3","Song 004 | This song lyrics 4","Song 005 | This song lyrics 5","Song 006 | This song lyrics 6","Song 007 | This song lyrics 7"};

        description = new String[]{"MORNING song", "MORNING song", "MORNING song", "MORNING song", "MORNING song", "MORNING song", "MORNING song",};

        icon = new int[]{ R.drawable.song, R.drawable.song, R.drawable.song, R.drawable.song,R.drawable.song,R.drawable.song, R.drawable.song,};

        listView = findViewById(R.id.list);

        for (int i =0; i<title.length; i++){
            Model model =new Model(title[i], description[i], icon[i]);
            //let's simply say, the song identifier is just the order of the song in the list
            model.id = i;
            //bind all strings in an array
            arrayList.add(model);
        }

        //pass result to listview class
        adapter = new ListViewAdapter(this, arrayList);

        //bind the adapter to the listview class
        listView.setAdapter(adapter);



    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);

        MenuItem myActionMenuItem = menu.findItem(R.id.action_search);
        SearchView searchView = (SearchView)myActionMenuItem.getActionView();
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String s) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String s) {
                if (TextUtils.isEmpty(s)){
                    adapter.filter("");
                    listView.clearTextFilter();
                }
                else {
                    adapter.filter(s);
                }
                return true;
            }
        });

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id==R.id.action_settings){
            Toast.makeText(this, "Settings Selected", Toast.LENGTH_SHORT).show();
            startActivity(new Intent(this, Main2Activity.class));
            return true;
            //do your funtionality here

        }
        else if (id==R.id.action_howtouse){
                Toast.makeText(this, "How-To", Toast.LENGTH_SHORT).show();
            startActivity(new Intent(this, Main3Activity.class));
            return true;
                //do your funtionality here


        }else if (id==R.id.action_favorites){
                Toast.makeText(this, "Favorites Selected", Toast.LENGTH_SHORT).show();
            startActivity(new Intent(this, Main3Activity.class));
            return true;
                //do your funtionality here


        }
        else if (id==R.id.action_developers){
            Toast.makeText(this, "About", Toast.LENGTH_SHORT).show();
            startActivity(new Intent(this, Main4Activity.class));
            return true;
            //do your funtionality here

        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onQueryTextSubmit(String query) {
        return false;
    }

    @Override
    public boolean onQueryTextChange(String newText) {
        return false;
    }
}

This is what I'm aiming to create. Below pictures is what I look unto while creating this favorite using sharedPreference.

Saved List as FavoriteList List of Item The Fav_button placed on the detail page

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Joseph
  • 400
  • 4
  • 19
  • Does this answer your question? [Storing Array List Object in SharedPreferences](https://stackoverflow.com/questions/22984696/storing-array-list-object-in-sharedpreferences) – EraftYps Jun 15 '20 at 01:46
  • The snippet blocks are only for JavaScript/CSS/HTML related questions, please don't use them for other languages. – Mark Rotteveel Jun 16 '20 at 15:20
  • Mine is different from his. I stored data in the string. And i want to reference it in the SharedPreference to save and retrieve data from populated from string.xml – Joseph Jun 18 '20 at 11:28
  • Please give me correction from my own code. The link provided is does not answer my question – Joseph Jun 18 '20 at 13:12
  • Hello Sir, I'm humbly waiting for your correction? – Joseph Sep 17 '20 at 12:37

0 Answers0