-------------------------------------------- On Tue, 1/3/17, Martiman Henry <[email protected]> wrote:
Subject: Re: [android-developers] Save RecyclerView Item with Activity reference in SharedPreferences To: [email protected] Date: Tuesday, January 3, 2017, 5:34 AM Hi Marina, hope all is well. I made some adjustments to my code and would really appreciate it if you were able to help me implement the Database Helper. View Class: public class ViewDB { private Bitmap icon, fav; private String name, desp; private int icRecipe; private boolean cbFav; public ViewDB() { super(); } public ViewDB(int icRecipe, String name, String desp, boolean cbFav) { super(); this.setIcRecipe(icRecipe); this.setName(name); this.setDesp(desp); this.setCbFav(cbFav); } public ViewDB(Bitmap icon, String name, String desp) { icon = icon; name = name; desp = desp; } public Bitmap getIcon() { return icon; } public void setIcon(Bitmap icon) { this.icon = icon; } public Bitmap getFav() { return fav; } public void setFav(Bitmap fav) { this.fav = fav; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDesp() { return desp; } public void setDesp(String desp) { this.desp = desp; } public int getIcRecipe() { return icRecipe; } public void setIcRecipe(int icRecipe) { this.icRecipe = icRecipe; } public boolean isCbFav() { return cbFav; } public void setCbFav(boolean cbFav) { this.cbFav = cbFav; } } Database Helper class: public class DBHelper extends SQLiteOpenHelper { public static final String DB_NAME = "Recipes.db"; private static final String DB_TABLE = "recipe_table"; private static final int DB_VERSION = 1; private static final String RECIPE_ID = "ID"; private static final String RECIPE_ICON = "ICON"; private static final String RECIPE_NAME = "NAME"; private static final String RECIPE_DESP = "DESCRIPTION"; private static final String RECIPE_FAV = "FAVOURITE"; private static final String CREATE_RECIPE_TABLE = "create table " + DB_NAME + " (" + RECIPE_ID + "integer primary key autoincrement, " + RECIPE_ICON + " blob not null, " + RECIPE_NAME + " text not null unique, " + RECIPE_DESP + " text not null);"; public static final Object[] databaseLock = new Object[0]; private Context mContext; public DBHelper(Context context) { super(context, DB_NAME, null, DB_VERSION); } @Override public void onCreate(SQLiteDatabase sqLiteDatabase) { sqLiteDatabase.execSQL(CREATE_RECIPE_TABLE); } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) { sqLiteDatabase.execSQL("DROP TABLE IF EXIST " + DB_TABLE); onCreate(sqLiteDatabase); } //Add Favourite public void addFav(ViewDB viewDB) throws SQLiteException { synchronized (databaseLock) { SQLiteDatabase db = this.getWritableDatabase(); if (db != null) { ContentValues contentValues = new ContentValues(); contentValues.put(RECIPE_ICON, DBBitmapUtility.getBytes(viewDB.getIcon())); contentValues.put(RECIPE_NAME, viewDB.getName()); contentValues.put(RECIPE_DESP, viewDB.getDesp()); try { db.insert(DB_TABLE, null, contentValues); } catch (Exception e) { Toast.makeText(mContext, "Unable to add favourite.", Toast.LENGTH_LONG).show(); } db.close(); } } } //Open Database public DBHelper open() throws SQLException { this.getWritableDatabase(); return this; } // Close Database public void close() { this.close(); } //Delete Favourite public Integer deleteFav(String id) { SQLiteDatabase db = this.getWritableDatabase(); return db.delete(DB_TABLE, "ID=?", new String[]{id}); } //Show All Favourites public ViewDB getAllFav() throws SQLException { SQLiteDatabase db = this.getWritableDatabase(); Cursor cur = db.query(true, DB_TABLE, new String[]{RECIPE_ICON, RECIPE_NAME, RECIPE_DESP, RECIPE_FAV}, null, null, null, null, null, null); if (cur.moveToFirst()) { byte[] icon = cur.getBlob(cur.getColumnIndex(RECIPE_ICON)); String name = cur.getString(cur.getColumnIndex(RECIPE_NAME)); String desp = cur.getString(cur.getColumnIndex(RECIPE_DESP)); cur.close(); return new ViewDB(DBBitmapUtility.getImage(icon), name, desp); } cur.close(); return null; } //Auto-refresh Favourite } Bitmap Converter class: public class DBBitmapUtility { // convert from bitmap to byte array public static byte[] getBytes(Bitmap bitmap) { ByteArrayOutputStream stream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 0, stream); return stream.toByteArray(); } // convert from byte array to bitmap public static Bitmap getImage(byte[] image) { return BitmapFactory.decodeByteArray(image, 0, image.length); } } RecyclerView Adapter class: public class AdapterFavourite extends RecyclerView.Adapter<AdapterFavourite.VHFavourite> { private LayoutInflater mInflater; private ArrayList<ViewDB> viewRecipes; private Context mContext; private ClickedListener clickedListener; private LongClickedListener longClickedListener; public AdapterFavourite(Context context, ArrayList<ViewDB> data) { this.mContext = context; mInflater = LayoutInflater.from(context); this.viewRecipes = data; notifyDataSetChanged(); } @Override public VHFavourite onCreateViewHolder(ViewGroup parent, int viewType) { View v = mInflater.inflate(R.layout.item_recipe, parent, false); VHFavourite layout = new VHFavourite(v); return layout; } @Override public void onBindViewHolder(final VHFavourite holder, final int position) { //ViewDB current = viewRecipes.get(position); holder.bindData(viewRecipes.get(position)); holder.cbFav.setChecked(viewRecipes.get(position).isCbFav()); holder.cbFav.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { if (longClickedListener != null) { longClickedListener.longClicked(compoundButton, b ); } viewRecipes.get(holder.getAdapterPosition()).setCbFav(b); } }); } public void setClickedListener(ClickedListener clickedListener) { this.clickedListener = clickedListener; } public void setLongClickedListener(LongClickedListener longClickedListener) { this.longClickedListener = longClickedListener; } @Override public int getItemCount() { return viewRecipes.size(); } public class VHFavourite extends RecyclerView.ViewHolder { private ImageView icon, favourite; private TextView title, desp; private CheckBox cbFav; public VHFavourite(View itemView) { super(itemView); icon = (ImageView) itemView.findViewById(R.id.imgRecipeIC); title = (TextView) itemView.findViewById(R.id.txtRecipeTitle); desp = (TextView) itemView.findViewById(R.id.txtRecipeDesp); //favourite = (ImageView) itemView.findViewById(R.id.imgFavourite); cbFav = (CheckBox) itemView.findViewById(R.id.cbFavorite); itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (clickedListener != null) { clickedListener.itemClicked(view, getPosition()); } } }); } public void bindData(ViewDB data) { //icon.setImageResource(data.getIcRecipe()); Picasso.with(mContext).load(viewRecipes.get(getPosition()).getIcRecipe()).resize(80, 80).into(icon); title.setText(data.getName()); desp.setText(data.getDesp()); } private byte[] imageViewToByte(ImageView image) { Bitmap bitmap = ((BitmapDrawable) image.getDrawable()).getBitmap(); ByteArrayOutputStream stream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream); byte[] byteArray = stream.toByteArray(); return byteArray; } } public interface ClickedListener { public void itemClicked(View view, int position); } public interface LongClickedListener { public void longClicked(CompoundButton compoundButton, boolean b); } } Activity class: public class ActivityTest extends AppCompatActivity implements AdapterFavourite.ClickedListener, AdapterFavourite.LongClickedListener { private Toolbar mToolbar; private RecyclerView mRecycler; private AdapterFavourite mAdapter; ArrayList<ViewDB> contact_data = new ArrayList<ViewDB>(); private LinearLayoutManager mLayout; private DBHelper dbHelper; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_recycler); // setupToolbar(); dbHelper = new DBHelper(this); // Appetizer Recipe mRecycler = (RecyclerView) findViewById(R.id.recyclerGeneral); mRecycler.setNestedScrollingEnabled(false); mLayout = new LinearLayoutManager(this); mRecycler.setHasFixedSize(true); mRecycler.setItemAnimator(new DefaultItemAnimator()); mAdapter = new AdapterFavourite(this, getAppetizerRecipes()); mAdapter.setClickedListener(this); mAdapter.setLongClickedListener(this); mRecycler.setAdapter(mAdapter); mRecycler.setLayoutManager(mLayout); // Ads MobileAds.initialize(getApplicationContext(), "ca-app-pub-6794767631725244/2207648611"); AdView mAdView = (AdView) findViewById(R.id.adView); AdRequest adRequest = new AdRequest.Builder().build(); mAdView.loadAd(adRequest); } private void setupToolbar() { mToolbar = (Toolbar) findViewById(R.id.app_bar); setSupportActionBar(mToolbar); getSupportActionBar().setTitle("Test Activity"); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } public ArrayList<ViewDB> getAppetizerRecipes() { ArrayList<ViewDB> data = new ArrayList<>(); int[] recipe = {R.drawable.appetizer_roast_yam, R.drawable.appetizer_solomon_a_gundy, R.drawable.appetizer_peanut_porridge, R.drawable.appetizer_cornmeal_porridge, R.drawable.appetizer_chocolate_tea, R.drawable.appetizer_rice_porridge, R.drawable.appetizer_banana_porridge, R.drawable.appetizer_festival, R.drawable.appetizer_cornmeal_fritters}; String[] title = getResources().getStringArray(R.array.appetizer_list); String[] desp = getResources().getStringArray(R.array.appetizer_desp); for (int i = 0; i < title.length; i++) { ViewDB information = new ViewDB(); information.setIcRecipe(recipe[i]); information.setName(title[i]); information.setDesp(desp[i]); data.add(information); } return data; } @Override public void itemClicked(View view, int position) { switch (position) { case 0: startActivity(new Intent(this, AppetizerRoastYam.class)); break; case 1: startActivity(new Intent(this, AppetizerSolomonGundy.class)); break; case 2: startActivity(new Intent(this, AppetizerPeanutPorridge.class)); break; case 3: startActivity(new Intent(this, AppetizerCornmealPorridge.class)); break; case 4: startActivity(new Intent(this, AppetizerChocolateTea.class)); break; case 5: startActivity(new Intent(this, AppetizerRicePorridge.class)); break; case 6: startActivity(new Intent(this, AppetizerBananaPorridge.class)); break; case 7: startActivity(new Intent(this, AppetizerFestival.class)); break; case 8: startActivity(new Intent(this, AppetizerCornmealFritters.class)); break; default: break; } } //Refresh Data public void Set_Refresh_Data() { contact_data.clear(); mAdapter = new AdapterFavourite(this, contact_data); mRecycler.setAdapter(mAdapter); mRecycler.setLayoutManager(mLayout); mAdapter.notifyDataSetChanged(); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // Respond to the action bar's Up/Home button case android.R.id.home: NavUtils.navigateUpFromSameTask(this); return true; } return super.onOptionsItemSelected(item); } @Override public void longClicked(CompoundButton compoundButton, boolean b) { getAppetizerRecipes(); if (compoundButton.isChecked()==true){ dbHelper = new DBHelper(this); Toast.makeText(this, "Add to Favourite", Toast.LENGTH_LONG).show(); }else if(compoundButton.isChecked()==false){ Toast.makeText(this, "Removed from Favourite", Toast.LENGTH_LONG).show(); } } } So far everything is working how it is suppose to work. The RecyclerView is being populated and the Favourite button is showing the right message. My problem now is when I like the Favourite button in the activity it add the row that it is located in the RecyclerView to the Database. Right now that’s my biggest problem. On Wed, Dec 21, 2016 at 2:16 PM, Martiman Henry <[email protected]> wrote: I am unable to understand you so let me see if I can explain myself better. The when an item is stored in the SharedPreferences, it is used to populate a Favourite activity. When I select the Favourite activity I see the item stored but when I click on those items nothing happens because only the row from the RecyclerView is saved and nothing else. I don't just want the row to be saved, I also want the Activity that the row is collected to be saved also. So that when I select the Favourites activity in the app I can click on any of the items and I go directly to the activity as if I had selected it from the original activity. I attached a photo of the Appetizer Recipe activity which is the original activity. Each of the rows is tired to a different activity. After saving any row, I want not only the row to be saved but also the activity that its tied to so that when I view and select saved rows in SharedPreferences activity I am taken to the activity that its tied to. I was told that rather than using SharedPreferences I should use SQLite. What are your suggestions? On Wednesday, 21 December 2016 13:47:09 UTC-5, Marina Cuello wrote:I get it that you have a reference to the activities in each ViewRecipe and you're expecting the Gson instance to include it on your file. If that's the case, you need you find another way: When you take an object and turn it to json using Gson, you only get the items that are Serializable. An Activity doesn't implement that interface. If you just need it to start a different activity when an item is clicked, you could use an Enum or simply an integer as reference and use a switch to decide which XXActivity.class to use. Marina On Tue, Dec 20, 2016 at 11:33 AM, Martiman Henry <[email protected]> wrote: I have a RecyclerView with with each item referring to a different activity. I am able to save the individual items in SharedPreferences but the reference to the activity is not saved. This is the SharedPreference class that I created. I want to save not only the individual list in the recyclerview but also the reference to each activity from their respective row from the recyclerview public class SharedPreference { public static final String PREFS_NAME = "RECIPE_APP"; public static final String FAVORITES = "Recipe_Favorite"; // This four methods are used for maintaining favorites. public void saveFavorites(Context context, List<ViewRecipe> favorites) { SharedPreferences settings; SharedPreferences.Editor editor; settings = context.getSharedPreferences(P REFS_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, ViewRecipe recipe) { List<ViewRecipe> favorites = getFavorites(context); if (favorites == null) favorites = new ArrayList<ViewRecipe>(); favorites.add(recipe); saveFavorites(context, favorites); } public void removeFavorite(Context context, ViewRecipe product) { ArrayList<ViewRecipe> favorites = (ArrayList<ViewRecipe>) getFavorites(context); if (favorites != null) { favorites.remove(product); saveFavorites(context, favorites); } } public List<ViewRecipe> getFavorites(Context context) { SharedPreferences settings; List<ViewRecipe> favorites; settings = context.getSharedPreferences(P REFS_NAME, Context.MODE_PRIVATE); if (settings.contains(FAVORITES)) { String jsonFavorites = settings.getString(FAVORITES, null); Gson gson = new Gson(); ViewRecipe[] favoriteItems = gson.fromJson(jsonFavorites, ViewRecipe[].class); favorites = Arrays.asList(favoriteItems); favorites = new ArrayList<ViewRecipe>(favorite s); } else return null; return (ArrayList<ViewRecipe>) favorites; } } How am can I save both the item and the reference to the activity? -- You received this message because you are subscribed to the Google Groups "Android Developers" group. To unsubscribe from this group and stop receiving emails from it, send an email to android-developers+unsubscribe @googlegroups.com. To post to this group, send email to [email protected]. Visit this group at https://groups.google.com/grou p/android-developers. To view this discussion on the web visit https://groups.google.com/d/ms gid/android-developers/e03e6ba 3-b8e2-475c-b4d5-73b61da6d582% 40googlegroups.com. For more options, visit https://groups.google.com/d/op tout. -- You received this message because you are subscribed to a topic in the Google Groups "Android Developers" group. To unsubscribe from this topic, visit https://groups.google.com/d/ topic/android-developers/ bnhhyZyibIE/unsubscribe. To unsubscribe from this group and all its topics, send an email to android-developers+ [email protected]. To post to this group, send email to android-developers@ googlegroups.com. Visit this group at https://groups.google.com/ group/android-developers. To view this discussion on the web visit https://groups.google.com/d/ msgid/android-developers/ 5856c8f5-617e-4673-b8bd- 20990c3e92f8%40googlegroups. com. For more options, visit https://groups.google.com/d/ optout. -- Regards, Martiman P. Henry B.Sc Management Studies: Major - Accounting Minor(s) - Economics and Management Studies (Pursuing) -- You received this message because you are subscribed to the Google Groups "Android Developers" group. To unsubscribe from this group and stop receiving emails from it, send an email to [email protected]. To post to this group, send email to [email protected]. Visit this group at https://groups.google.com/group/android-developers. To view this discussion on the web visit https://groups.google.com/d/msgid/android-developers/CAK7hJBMHy%2BGDUNHccfoYfs%2Bf%3DVo4Xeg6qghv2ONgE8p36uC%3DPQ%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout. 9 febr - Independenta insulei Cipru iun - sept - Tulburari in Congo-ul belgian409 -- You received this message because you are subscribed to the Google Groups "Android Developers" group. To unsubscribe from this group and stop receiving emails from it, send an email to [email protected]. To post to this group, send email to [email protected]. Visit this group at https://groups.google.com/group/android-developers. To view this discussion on the web visit https://groups.google.com/d/msgid/android-developers/681691558.5755567.1483426930264%40mail.yahoo.com. For more options, visit https://groups.google.com/d/optout.

