在阅读本文之前,如果您不知道如何创建数据库,请点击此链接.
好的,让我们开始在数据库中存储一些收藏夹..
你还应该从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 ListgetFavorites() { List 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; }
从DB获取所有项目的方法
// GET ALL DATA FROM DATABASE public ListgetAllFunFacts() { List 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) 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; Listfacts = 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"); }
我希望您能够根据我的代码管理您的代码并解决您的问题!
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); }
然后你需要使你的类实现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"); } }