使用共享首选项添加listvview的收藏夹

时间:2015-12-31 10:10:58

标签: android listview sharedpreferences baseadapter

我有一个使用baseadapter的列表视图。长按时,每个列表项都应使列表项添加到另一个活动中显示的收藏夹中。长按列表项时,列表项末尾的星形图像应变暗,表示列表项已添加到收藏夹。这确实发生了但是当我退出列表视图活动并再次重新打开它时,星形图像不再暗 顺便说一句,我使用解析。 Com接收列表中的信息

我的代码

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;
}

}

我的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();
}   

我的最爱活动

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); 

}

 }

4 个答案:

答案 0 :(得分:5)

在阅读本文之前,如果您不知道如何创建数据库,请点击this链接。

好的,让我们开始在数据库中存储一些收藏夹。

您还应该从json,post的id解析并将其存储在数据库的第一个表中,这样您就可以在后面将该id与第二个表中用于存储收藏夹的行的id进行比较。

创建表格

这些是我的表

// 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" + ")";

现在我们将一些项目添加到第一个表中

// 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
}

现在让我们在第二个表中添加一些好处

// 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();
}

从收藏中删除物品的方法

// 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();
}

这是获取所有收藏的方法

// 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;
}

从数据库获取所有项目的方法

// 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;
}

这就是我们如何存储从JSON到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();
    }
}

现在我们得到了我们最喜欢的部分

我已经在我的适配器中编写了逻辑,所有魔法都在那里发生..

// 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");
    }

我希望您能够根据我的代码管理您的代码并解决您的问题!

<强>更新

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);
        }

然后你需要让你的类实现Serializable,如下所示:

public class YourClass implements Serializable

接下来,我们需要将此活动的意图转移到我们接收您的类对象的活动中。

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

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

我在适配器中用于检查喜欢的项目的相同逻辑是在单个视图项目中。这里我们还检查项目是否在收藏夹中,因此我们可以设置适当的图像资源。

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

在这里,我们将项目添加到收藏夹:

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");
        }
    }

答案 1 :(得分:0)

制作数组列表/数组,用于存储收藏夹位置,长时间添加位置点击并将其保存在共享首选项中。当您再次导航到该活动时,首先检查收藏列表是否包含任何项目。如果它改变了那个位置的喜欢的图标

答案 2 :(得分:0)

首先,您需要将收藏项目存储在另一个列表中,然后在共享首选项中存储arraylist之后,在另一个列表中显示共享首选项数据。

答案 3 :(得分:0)

在你的getFavorites(上下文上下文)方法中

而不是

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

使用此

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

return favorites;