Android Open Source - Android_ApplicationTemplate Favorite Manager






From Project

Back to project page Android_ApplicationTemplate.

License

The source code is released under:

MIT License

If you think the Android project Android_ApplicationTemplate listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

/*The MIT License (MIT)
/*from   w w  w .j  av a2s .  co  m*/
Copyright (c) 2014 Ahmad Barqawi (github.com/Barqawiz)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
package com.iaraby.template.data;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.iaraby.template.control.FavGarbagCollector;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;

/**
 * Shared preferences manager to store favorite fields IDs and manage the
 * required queries to get the favorite from the database and restore the fields
 * for new database versions
 * 
 * @author Barqawiz
 * 
 */
public class FavoriteManager {
  
  public static String FAV_ITEM_TAG = "FAV_LIST";
  
  private Context context;
  private static FavoriteManager instance;

  private SharedPreferences preferences;

  public static FavoriteManager getInstance(Context context) {
    if (instance == null)
      instance = new FavoriteManager(context);
    return instance;
  } // method: get instance

  private FavoriteManager(Context context) {
    preferences = context.getSharedPreferences("FavoriteManager", 0/*
                                     * private
                                     * mode
                                     */);
    this.context = context;
  } // constructor

  public boolean addToFav(long id) {
    boolean res = true;

    if (preferences.getString(FAV_ITEM_TAG + id, null) == null) {
      preferences.edit().putString(FAV_ITEM_TAG + id, id + "").commit();
    }

    return res;
  }

  public boolean removeFav(long id) {
    boolean res = true;

    if (preferences.getString(FAV_ITEM_TAG + id, null) != null) {
      preferences.edit().remove(FAV_ITEM_TAG + id).commit();
    }

    return res;
  }

  public boolean isFav(long id) {
    return (preferences.getString(FAV_ITEM_TAG + id, null) != null);
  }

  public void clear() {
    preferences.edit().clear().commit();
  }

  public Map<String,?> getFavSet() {
    return preferences.getAll();
  }

  public Set<String> geKeysSet() {

    return preferences.getAll().keySet();
  }

  public int countFav() {
    try {
      return preferences.getAll().size();
    } catch(NullPointerException ex) {
      return 0;
    }
  }

  /**
   * Check if the received id available in the database or not
   *
   * @param Long id of the item
   * @return true if id available in database otherwise return false
   * @throws IllegalAccessError
   */
  public boolean isItemInDatabase(long id) throws IllegalAccessError {
    boolean res = false;
    if (MyDataAdapter.getInstance().isOpen()) {
      Cursor cursor = MyDataAdapter.getInstance().getContentItem(id);
      if (cursor.moveToFirst())
        return true;
    } else {
      throw new IllegalAccessError(
          "Database adapter not open, make sure you called MyDataAdapter.getInstance().open(config); at least once");
    } // check if the database is opened
    return res;
  }

  /* preferences operations variables */
  

  /**
   * Get favorite cursor from database 
   * 
   * @return Cursor of favorite items
   * @throws IllegalAccessError if error occurs while connecting to database
   */
  public Cursor getFavCursor() throws IllegalAccessError {
    if (!MyDataAdapter.getInstance().isOpen())
      throw new IllegalAccessError(
          "Database adapter not open, make sure you called MyDataAdapter.getInstance().open(config); at least once");
    int numFav = countFav();
    if (numFav == 0)
      return null;

    String cols[] = { Beans.Content.COL_ID, Beans.Content.COL_TITLE,
        Beans.Content.COL_CONTENT, Beans.Content.COL_IMAGE };
    String selection = null;
    ArrayList<String> whereList = new ArrayList<String>();
    HashMap<String, ?> collection = (HashMap<String, ?>) getFavSet();
    for (Map.Entry<String,?> entry : collection.entrySet()) {
      if (entry.getValue() == null)
        continue;
      if (!entry.getKey().startsWith(FAV_ITEM_TAG))
        continue;
      
      if (selection == null) {
        selection = Beans.Content.COL_ID + " = ? ";
      } else {
        selection += " OR " + Beans.Content.COL_ID + " = ? ";
      }
      whereList.add(entry.getValue().toString());
    } // loop on all values

    String[] where = new String[whereList.size()];
    where = whereList.toArray(where);
    
    Cursor cursor = MyDataAdapter.getInstance().fetchDataWhere(
        Beans.Content.TABLE_NAME, selection, where, null, cols);
    
    return cursor;
  }

  /**
   * This method to call a service that check the favorite list with the new
   * data and delete favorite id's that does not exist in database anymore
   */
  public void maintainFavChange(int dataVerion) {
    //validate
    if (!MyDataAdapter.getInstance().isOpen())
      return;
    
    //process
    int numFav = countFav();
    if (numFav == 0) {
      FavGarbagCollector.clearVersion(context, dataVerion);
      return;
    }

    Intent intent = new Intent(context, FavGarbagCollector.class);
    intent.putExtra(Constants.PARAM_FAV_VER, dataVerion);
    
    context.startService(intent); 
  }
} // class





Java Source Code List

android.UnusedStub.java
com.iaraby.template.control.DetailsPagerAdapter.java
com.iaraby.template.control.DetailsTask.java
com.iaraby.template.control.FavGarbagCollector.java
com.iaraby.template.data.Beans.java
com.iaraby.template.data.Constants.java
com.iaraby.template.data.FavoriteManager.java
com.iaraby.template.data.MyDataAdapter.java
com.iaraby.template.data.Preferences.java
com.iaraby.template.util.DialogManager.java
com.iaraby.template.util.FontManager.java
com.iaraby.template.view.MainActivity.java
com.iaraby.template.view.Master_Activity.java
com.iaraby.template.view.fragment.DetailsFrag.java
com.iaraby.template.view.fragment.ListFrag.java
com.iaraby.template.view.fragment.MainFragment.java