user5524159
user5524159

Reputation: 553

Adding favorites of listvview using shared preferences

I have a list view which uses baseadapter . Each list item when long pressed should make the list item add to favorites which are displayed in another activity. When the list item is long pressed the star image at the end of the list item should become dark indicating the list item is added to favorites. This does happen but when I quit the list view activity and reopen it again the star image is no more dark By the way I use parse. Com to receive the information in the list

My code

ssharedpreference.java

public class SharedPreference
{

public static final String PREFS_NAME = "POCKTCODE_APP";
public static final String FAVORITES = "code_Favorite";

public SharedPreference(){
    super();
}

public void saveFavorites(Context context, List<CodeList> favorites){
    SharedPreferences settings;
    Editor editor;

    settings = context.getSharedPreferences(PREFS_NAME,
                                            Context.MODE_PRIVATE);
    editor = settings.edit();

    Gson gson = new Gson();
    String jsonFavorites = gson.toJson(favorites);

    editor.putString(FAVORITES, jsonFavorites);

    editor.commit();
}

public void addFavorite(Context context, CodeList code){
    List<CodeList> favorites = getFavorites(context);

    if(favorites == null)
        favorites = new ArrayList<CodeList>();
    favorites.add(code);
    saveFavorites(context,favorites);
}

public void removeFavorite(Context context, CodeList code) {
    ArrayList<CodeList> favorites = getFavorites(context);
    if (favorites != null) {
        favorites.remove(code);
        saveFavorites(context, favorites);
    }
}


public ArrayList<CodeList> getFavorites(Context context) {
    SharedPreferences settings;
    List<CodeList> favorites;

    settings = context.getSharedPreferences(PREFS_NAME,
                                            Context.MODE_PRIVATE);

    if (settings.contains(FAVORITES)) {
        String jsonFavorites = settings.getString(FAVORITES, null);
        Gson gson = new Gson();
        CodeList[] favoriteItems = gson.fromJson(jsonFavorites,
                                                 CodeList[].class);

        favorites = Arrays.asList(favoriteItems);
        favorites = new ArrayList<CodeList>(favorites);
    } else
        return null;

    return (ArrayList<CodeList>) favorites;
}

}

required part of my baseadapter

@Override
public View getView(final int position, View view, ViewGroup parent)
{
    final ViewHolder holder;
    if(view == null){
        holder = new ViewHolder();
        view = inflater.inflate(R.layout.beg_list_item,null);
        holder.listHeading = (TextView) view.findViewById(R.id.beg_list_itemTextView);

        //holder.listHash = (TextView) view.findViewById(R.id.listview_hashtags);
        holder.alphabetList = (ImageView) view.findViewById(R.id.beg_list_itemImageView);
        view.setTag(holder);
        holder.favariteImage = (ImageView) view.findViewById(R.id.favbtn);

    }else{
        holder = (ViewHolder) view.getTag();
    }
    CodeList codes = (CodeList) getItem(position);
    holder.listHeading.setText(codeList.get(position).getListHeading());
    imageLoader.DisplayImage(codeList.get(position).getAlphabetimg(),
                             holder.alphabetList);


    if (checkFavoriteItem(codes)) {
        holder.favariteImage.setImageResource(R.drawable.favorite);
        holder.favariteImage.setTag("yes");
    } else {
        holder.favariteImage.setImageResource(R.drawable.unfavorite);
        holder.favariteImage.setTag("no");
    }                    

    view.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View arg0){
                Intent intent = new Intent(context, SingleItemView.class);

                //
                intent.putExtra("demovideo",
                                (codeList.get(position).getDailogdemovideo()));

                intent.putExtra("download",
                                (codeList.get(position).getDownloadCode()));


                intent.putExtra("videoimg",
                                (codeList.get(position).getVideoImage()));



                // Start SingleItemView Class
                context.startActivity(intent);

            }
        });             
        view.setOnLongClickListener(new OnLongClickListener(){
            @Override
            public boolean onLongClick(View v){

                ImageView fvrtebutton = (ImageView) v.findViewById(R.id.favbtn);

                String tag = fvrtebutton.getTag().toString();
                if (tag.equalsIgnoreCase("no")) {
                    shrdprfrnce.addFavorite(context, codeList.get(position));
                    Toast.makeText(context, R.string.fav_added,
                                   Toast.LENGTH_SHORT).show();

                    fvrtebutton.setTag("yes");
                    fvrtebutton.setImageResource(R.drawable.favorite);
                } else {
                    shrdprfrnce.removeFavorite(context, codeList.get(position));
                    fvrtebutton.setTag("no");
                    fvrtebutton.setImageResource(R.drawable.unfavorite);
                    Toast.makeText(context,
                                   R.string.fav_removed,
                                   Toast.LENGTH_SHORT).show();
                }
                return false;
            }
        });


    return view;
}
//to check whether list item exists in shared preferences
public boolean checkFavoriteItem(CodeList checkProduct) {
    boolean check = false;
    List<CodeList> favorites = shrdprfrnce.getFavorites(context);
    if (favorites != null) {
        for (CodeList codes : favorites) {
            if (codes.equals(checkProduct)) {
                check = true;
                break;
            }
        }
    }
    return check;
}


public void add(CodeList codes) {
    //super.add(codes);
    codeList.add(codes);
    notifyDataSetChanged();
}


public void remove(CodeList codes) {
    //super.remove(codes);
    codeList.remove(codes);
    notifyDataSetChanged();
}   

my favorites activity

public class MyFavActivity extends Activity
 {
@Override
protected void onCreate(Bundle savedInstanceState)
{
    ListView favoriteList;
    final SharedPreference shrdprefernces;
    final List<CodeList> favorites;
    final FinalAdapter fnladpter;


    super.onCreate(savedInstanceState);
    setContentView(R.layout.fav_layout);

    shrdprefernces= new SharedPreference();
    favorites = shrdprefernces.getFavorites(MyFavActivity.this);

    if (favorites == null) {
        showAlert(getResources().getString(R.string.nofav),
                  getResources().getString(R.string.nofavmsg));
    } else {

        if (favorites.size() == 0) {
            showAlert(
                getResources().getString(R.string.nofav),
                getResources().getString(R.string.nofavmsg));
        }

        favoriteList = (ListView) findViewById(R.id.favlayoutListView);
        if (favorites != null) {
            fnladpter = new FinalAdapter(MyFavActivity.this, favorites);
            favoriteList.setAdapter(fnladpter);

            favoriteList.setOnItemClickListener(new OnItemClickListener() {

                    public void onItemClick(AdapterView<?> parent, View arg1,
                                            int position, long arg3) {

                    }
                });

            favoriteList
                .setOnItemLongClickListener(new OnItemLongClickListener() {

                    @Override
                    public boolean onItemLongClick(
                        AdapterView<?> parent, View view,
                        int position, long id) {

                        ImageView button = (ImageView) view
                            .findViewById(R.id.favbtn);

                        String tag = button.getTag().toString();
                        if (tag.equalsIgnoreCase("no")) {
                            shrdprefernces.addFavorite(MyFavActivity.this,
                                                         favorites.get(position));
                            Toast.makeText(
                                MyFavActivity.this,
                                getString(
                                    R.string.fav_added),
                                Toast.LENGTH_SHORT).show();

                            button.setTag("yes");
                            button.setImageResource(R.drawable.favorite);
                        } else {
                            shrdprefernces.removeFavorite(MyFavActivity.this,
                                                            favorites.get(position));
                            button.setTag("no");
                            button.setImageResource(R.drawable.unfavorite);
                            fnladpter.remove(favorites
                                                      .get(position));
                            Toast.makeText(
                                MyFavActivity.this,
                                getString(
                                    R.string.fav_removed),
                                Toast.LENGTH_SHORT).show();
                        }
                        return true;
                    }
                });
        }
    }
}

public void showAlert(String title, String message) {
    if (MyFavActivity.this != null && !MyFavActivity.this.isFinishing()) {
        AlertDialog alertDialog = new AlertDialog.Builder(MyFavActivity.this)
            .create();
        alertDialog.setTitle(title);
        alertDialog.setMessage(message);
        alertDialog.setCancelable(false);

        // setting OK Button
        alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK",
            new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    // activity.finish();
                    getFragmentManager().popBackStackImmediate();
                }
            });
        alertDialog.show();
    }
}

@Override
protected void onResume()
{
    // TODO: Implement this method
    super.onResume();
}


@Override
public void onBackPressed() {
    super.onBackPressed();
    overridePendingTransition(R.anim.left_to_right, R.anim.right_to_left); 

}

 }

Upvotes: 1

Views: 9306

Answers (4)

Dusan Dimitrijevic
Dusan Dimitrijevic

Reputation: 3219

Before reading this, if you don't know how to create database, just follow this link.

Okay, let's start storing some favorites in database ..

You should also parse from json, id of post and store it in first table at database, so you can compare later that id with id of row from second table which is intended for storing favorites.

CREATING TABLES

These are my tables

// CREATE TABLES
private static final String CREATE_FUN_FACTS_TABLE = "CREATE TABLE " + TABLE_NAME + "("
        + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
        + POST_ID + " INTEGER,"
        + KEY_DESC + " TEXT,"
        + KEY_IMAGE + " TEXT,"
        + KEY_SOURCE + " TEXT" + ")";

private static final String CREATE_FAVS_TABLE = "CREATE TABLE " + TABLE_FAVS + "("
        + FAVS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
        + FACTS_ID + " INTEGER" + ")";

NOW LET WE ADD SOME ITEMS TO THE FIRST TABLE

// ADDING NEW FACTS ITEM
public void addItem(FunFactsData item) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(POST_ID, item.getId());
    values.put(KEY_DESC, item.getDescription());
    values.put(KEY_IMAGE, item.getImagePath());
    values.put(KEY_SOURCE, item.getSource());
    // INSERTING ROW
    db.insert(TABLE_NAME, null, values);
    db.close(); // CLOSING DATABASE CONNECTION
}

NOW LET WE ADD SOME FAVORITES TO THE SECOND TABLE

// ADDING NEW FAVORITE
public void addToFavorite(FunFactsData savedItem) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(FACTS_ID, savedItem.getId());
    // INSERTING ROW
    db.insert(TABLE_FAVS, null, values);
    db.close();
}

METHOD FOR REMOVING ITEMS FROM FAVORITES

// REMOVING FROM FAVORITE
public void removeFromFavorite(FunFactsData removedItem) {
    SQLiteDatabase db = this.getWritableDatabase();
    db.delete(TABLE_FAVS, FACTS_ID + " = ? ",
            new String[]{String.valueOf(removedItem.getId())});
    db.close();
}

THIS IS METHOD FOR GETTING ALL FAVORITES

// GETTING ALL FAVORITES
public List<FunFactsData> getFavorites() {
    List<FunFactsData> funFactsDataList = new ArrayList<>();

    // BUILD THE QUERY
    String query = "SELECT * FROM " + TABLE_NAME;
    String query2 = " INNER JOIN " + TABLE_FAVS;
    String query3 = " ON " + POST_ID + " = " + FACTS_ID + " GROUP BY " + FACTS_ID;

    // GET REFERENCE TO WRITABLE DB
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(query + query2 + query3, null);

    // GO OVER EACH ROW, AND GET FAVORITES FROM FAVORITES TABLE
    FunFactsData fact;
    if (cursor.moveToFirst()) {
        do {
            fact = new FunFactsData();
            fact.setId(cursor.getInt(1));
            fact.setDescription(cursor.getString(2));
            fact.setImagePath(cursor.getString(3));
            fact.setSource(cursor.getString(4));

            funFactsDataList.add(fact);
        } while (cursor.moveToNext());
    }

    return funFactsDataList;
}

METHOD FOR GETTING ALL ITEMS FROM DB

// GET ALL DATA FROM DATABASE
public List<FunFactsData> getAllFunFacts() {
    List<FunFactsData> funFactsDataList = new ArrayList<>();

    // 1. BUILD THE QUERY
    String query = "SELECT * FROM " + TABLE_NAME;

    // 2. GET REFERENCE TO WRITABLE DB
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(query, null);

    // 3. GO OVER EACH ROW, BUILD FUN FACTS AND ADD IT TO LIST
    FunFactsData fact;
    if (cursor.moveToFirst()) {
        do {
            fact = new FunFactsData();
            fact.setId(cursor.getInt(1));
            fact.setDescription(cursor.getString(2));
            fact.setImagePath(cursor.getString(3));
            fact.setSource(cursor.getString(4));

            // Add fun fac to facts
            funFactsDataList.add(fact);
        } while (cursor.moveToNext());
    }

    Log.d("getAllFunFacts()", funFactsDataList.toString());

    // RETURN FACT
    return funFactsDataList;
}

THIS IS HOW WE WILL STORE ITEMS PARSED FROM JSON TO DATABASE

@Override
public void getData(String link) {
    try {
        JSONObject response = new JSONObject(link);
        JSONArray posts = response.getJSONArray("posts");
        facts = new ArrayList<>();

        shuffleJsonArray(posts);
        for (int i = 0; i < posts.length(); i++) {
            JSONObject obj = posts.getJSONObject(i);
            JSONObject customFields = obj.getJSONObject("custom_fields");

            FunFactsData funFactsData = new FunFactsData();
            funFactsData.setId(obj.getInt("id"));
            funFactsData.setImagePath(obj.getString("thumbnail"));
            funFactsData.setDescription(customFields.optString("description"));
            funFactsData.setSource(customFields.optString("source"));

            facts.add(funFactsData);
            dataBase.deleteRecords(); // "DELETE FROM " + TABLE_NAME, so everytime we get data from json, we will delete records from database and store new, but as far as we got id of post, we are good!
            for (FunFactsData data : facts) { // go through loop for getting all objects and add them to database
                dataBase.addItem(data); // add items do database
            }
            facts = (ArrayList<FunFactsData>) dataBase.getAllFunFacts(); // retrieve items from database
            adapter = new FunFactsListAdapter(HomeActivity.this, facts);
            flyingContainer.setAdapter(adapter); // setting addapter
            loadMoreData.setVisibility(View.INVISIBLE);
            noMoreData.setVisibility(View.INVISIBLE);
        }

        hidePDialog();
        adapter.notifyDataSetChanged();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

NOW WE GET TO THE PART WHERE WE ARE STORING FAVORITES

I have written logic for that in my adapter and all magic is happening there..

// Here we are checking if item with specified post id we are getting from json exists in second database.
private boolean checkFavoriteItem(FunFactsData checkItem) {
    boolean check = false;
    List<FunFactsData> facts = dataBase.getFavorites();
    if (facts != null) {
        for (FunFactsData data : facts) {
            int id = data.getId();
            int id2 = checkItem.getId();
            if (id == id2) {
                check = true;
                break;
            }
        }
    }
    return check;
}

// Here i'm storing item to favorite
holder.favoriteIcon.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String getTag = holder.favoriteIcon.getTag().toString();
            if (getTag.equalsIgnoreCase("gray")) {
                dataBase.addToFavorite(data);
                toast(context.getString(R.string.add_favorite));
                holder.favoriteIcon.setTag("red");
                holder.favoriteIcon.setImageResource(R.drawable.heart_red);
            } else {
                dataBase.removeFromFavorite(data);
                toast(context.getString(R.string.remove_favorite));
                holder.favoriteIcon.setTag("gray");
                holder.favoriteIcon.setImageResource(R.drawable.heart);
            }
            mSmallBang.bang(v);
        }
    });

    // i think this is clear also what i'm doing here.
    if (checkFavoriteItem(data)) {
        holder.favoriteIcon.setImageResource(R.drawable.heart_red);
        holder.favoriteIcon.setTag("red");
    } else {
        holder.favoriteIcon.setImageResource(R.drawable.heart);
        holder.favoriteIcon.setTag("gray");
    }

I hope that you will managed your code based on mine and solved your problem !

UPDATE

mRecyclerView.addOnItemTouchListener(new GiftsFavoriteList.RecyclerTouchListener(TagGiftsActivity.this, mRecyclerView, new GiftsFavoriteList.ClickListener() {
        @Override
        public void onClick(View view, int position) {
            Intent intent = new Intent(TagGiftsActivity.this, GiftSingleActivity.class);
            GiftItem selectedItem = mAdapter.getItem(position); // you can create method in adapter for getting specific item in row or use this -- arrayList.get(position); That is the same. I just used this in adapter.
            intent.putExtra("selected_item", selectedItem);
            startActivity(intent);
        }

Then you need to make your class implements Serializable like this:

public class YourClass implements Serializable

Next, we need to get intent from this activity to activity where we are receiving object of your class..

// GETTING INTENT FROM PREVIOUS ACTIVITY
    final Intent i = getIntent();

// GETTING POSITION OF SELECTED ITEM
    GiftItem selectedItem = (GiftItem) i.getSerializableExtra("selected_item");

The same logic i have used in adapter for checking favorite item is in single view item. Here we are also checking if item is in favorites, so we can set appropriate image resource.

if (checkFavoriteItem(selectedItem)) {
        favorite.setImageResource(R.drawable.ic_favorite);
        favorite.setTag("red");
    } else {
        favorite.setImageResource(R.drawable.ic_add_favorite);
        favorite.setTag("gray");
    }

And here we are adding item to favorites:

String tag = favorite.getTag().toString();
        if (tag.equalsIgnoreCase("gray")) {
            dbh.addToFavorite(selectedItem);
            toast("Added to favorites!");
            favorite.setImageResource(R.drawable.ic_favorite);
            favorite.setTag("red");
        } else {
            dbh.removeFromFavorite(selectedItem);
            toast("Removed from favorites!");
            favorite.setImageResource(R.drawable.ic_add_favorite);
            favorite.setTag("gray");
        }
    }

Upvotes: 5

Ibrahim Gharyali
Ibrahim Gharyali

Reputation: 564

in your getFavorites(Context context) method

instead of this

favorites = Arrays.asList(favoriteItems);
favorites = new ArrayList<CodeList>(favorites);

use this

favorites  = new ArrayList<CodeList>();
favorites.addAll(Arrays.asList(favoriteItems));

and

return favorites;

Upvotes: 0

Haresh Ramani
Haresh Ramani

Reputation: 390

First you need to store favorite item in one another list then after store arraylist in sharedpreferences after that display share preferences data in another list.

Upvotes: 0

Vivek Mishra
Vivek Mishra

Reputation: 5705

make a array list/array for storing favorites position and add position to it on long Click and save it in shared preference. When you again navigate to that activity, first check if favorite list has any item or not . If it has than change favorite icon of that position

Upvotes: 0

Related Questions