如何在Android编程中使用SQLite数据库向喜欢的活动添加项目

时间:2017-06-28 06:56:47

标签: android sqlite android-fragments android-sqlite

我有带导航菜单的导航栏。当点击每个项目导航抽屉时,加载了一个片段。在每个片段中,我从外部SQLite数据库加载数据,并使用Recyclerview显示。现在我想要点击它时添加收藏夹按钮,添加到收藏项目和背景收藏夹按钮的项目必须更改为喜欢。或者,当点击收藏项目时,项目UnFavorited和背景更改为UnLiked按钮。我在表格中创建了“收藏”列,并将每个原始数据设置为0 =文本,因为当首次加载应用时,没有任何项目不是最喜欢的。现在我不知道怎么做这个功能。请帮帮我。

这是我的 WorldCOuntryDabase

public class WorldCountryDatabase extends SQLiteOpenHelper {

private static final String TAG = "databaseHelper";
private static final String DB_NAME = "worldCountries.db";
private static final int DB_VERSION = 1;
private static final String TABLE_NAME = "country";
private static String DB_PATH = "";
private Context mContext;
private SQLiteDatabase database;


public WorldCountryDatabase(Context context) {
    super(context, DB_NAME, null, DB_VERSION);

    DB_PATH = context.getDatabasePath(DB_NAME).getPath();

    File file = new File(DB_PATH + "worldCountries.db");
    if (file.exists())

        openDataBase();

    this.mContext = context;


}

public void createDatabase() {

    boolean dbExist = checkDatabase();

    if (dbExist) {

        Log.d("MIN1", "Database already Exist");

    } else {
        this.getReadableDatabase();
    }
    try {
        copyDataBase();
    } catch (IOException e) {
        e.printStackTrace();
        Log.i("MIN2", e.getMessage());

    }


}

private boolean checkDatabase() {
    SQLiteDatabase checkDB = null;

    try {


        String myPath = DB_PATH + DB_NAME;
        checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);

    } catch (SQLiteException e) {
        e.printStackTrace();
        Log.d("MIN3", e.getMessage());

    }
    if (checkDB != null) {
        checkDB.close();
    }
    return checkDB != null;
}

public synchronized void close() {
    if (database != null) {
        database.close();
        SQLiteDatabase.releaseMemory();
    }
    super.close();

}


private void copyDataBase() throws IOException {

    try {


        InputStream in = mContext.getAssets().open(DB_NAME);
        String outFileName = DB_PATH + DB_NAME;
        OutputStream out = new FileOutputStream(outFileName);
        byte[] buffer = new byte[1024];
        int length;

        while ((length = in.read(buffer)) > 0) {
            out.write(buffer, 0, length);
        }


        out.flush();
        out.close();
        in.close();

        Log.d("MIN4", "Database copy");


    } catch (SQLiteException e) {
        Log.d("MIN5", e.getMessage());

    }
}

public Cursor QueryData(String query) {
    return database.rawQuery(query, null);
}


@Override
public void onCreate(SQLiteDatabase db) {

    Log.d("MIN6", "onCreate");



}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {




    Log.v("LOG_TAG", "Upgrading Database from version" + oldVersion + "To" + newVersion +
            "Which will destroy all  oldest data");


    if (newVersion > oldVersion) {
        try {
            copyDataBase();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}

public void openDataBase() {

    String myPath = DB_PATH + DB_NAME;
    database = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
    Log.d("MIN7", "Opened database");


}

// CRUD Table
public List<Questions> getAllQuestions() {

    List<Questions> questionsList = new ArrayList<>();
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor c;

    try {
        c = db.rawQuery("SELECT * FROM country ORDER BY Random()", null);
        if (c == null) return null;
        c.moveToFirst();
        do {
            int Id = c.getInt(c.getColumnIndex("id"));
            String Image = c.getString(c.getColumnIndex("Image"));
            String AnswerA = c.getString(c.getColumnIndex("AnswerA"));
            String AnswerB = c.getString(c.getColumnIndex("AnswerB"));
            String AnswerC = c.getString(c.getColumnIndex("AnswerC"));
            String AnswerD = c.getString(c.getColumnIndex("AnswerD"));
            String CorrectAnswer = c.getString(c.getColumnIndex("CorrectAnswer"));

            Questions question = new Questions(Id, Image, AnswerA, AnswerB, AnswerC, AnswerD, CorrectAnswer);
            questionsList.add(question);


        } while (c.moveToNext());
        c.close();


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

    database.close();
    return questionsList;
}


// Insert Score to Ranking table.
public void insertScore(double score) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues content = new ContentValues();
    content.put("Score", score);
    db.insert("Ranking", null, content);
}

// Get score and sort Ranking.
public List<Ranking> getRanking() {

    List<Ranking> rankingList = new ArrayList<>();
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor c;
    try {
        c = db.rawQuery("SELECT * FROM Ranking ORDER BY Score DESC;", null);
        if (c == null) return null;
        c.moveToFirst();
        do {

            int Id = c.getInt(c.getColumnIndex("Id"));
            int Score = c.getInt(c.getColumnIndex("Score"));

            Ranking ranking = new Ranking(Id, Score);
            rankingList.add(ranking);


        } while (c.moveToNext());
        c.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
    db.close();
    return rankingList;
}


//Update version 2.0
public int getPlayCount(int level) {
    int result = 0;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor c;
    try {
        c = db.rawQuery("SELECT PlayCount FROM UserPlayCount WHERE Level=" + level + ";", null);
        if (c == null) return 0;
        c.moveToNext();
        do {
            result = c.getInt(c.getColumnIndex("PlayCount"));
        } while (c.moveToNext());
        c.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return result;
}

public void updatePlayCount(int level, int PlayCount) {
    String query = String.format("UPDATE UserPlayCount Set PlayCount = %d WHERE Level = %d", PlayCount, level);
    database.execSQL(query);
}

这是我的 ContentAdapter

public class ContentAdapter extends RecyclerView.Adapter<ContentAdapter.ViewHolder> {

public Context context;
private boolean isFavorite;
WorldCountryDatabase worldCountryDatabase;
private List<AsiaCountry> item = Collections.emptyList();
private int mLastPosition = -1;
private Listener listener;


public ContentAdapter(Context context, List<AsiaCountry> item) {
    this.context = context;
    this.item = item;

}


public void setListener(Listener listener) {
    this.listener = listener;
}

@Override
public ContentAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, final int viewType) {
    //Defain the view for take layout
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item,
            parent, false);
    Log.d("Adapter", "Loaded");
    return new ViewHolder(view);
}

@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {


    final AsiaCountry asia = item.get(position);

    isFavorite = true;
    holder.titleNameCountry.setText(asia.getName());
    Log.d("TAG", asia.getName());


    Glide.with(context).load(asia.getFlag(context)).into(holder.titleImageCountry);


    holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (listener != null) {
                listener.onClick(position);

                String nameCountry = holder.titleNameCountry.getText().toString();

                Intent intent = new Intent(context, DetailsCountry.class);
                intent.putExtra("name", nameCountry);
                Log.d("CONT", nameCountry);

                context.startActivity(intent);
            }
        }
    });


    if (position > mLastPosition) {
        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.playTogether(
                ObjectAnimator.ofFloat(holder.itemView, "translationY",
                        holder.itemView.getMeasuredHeight() * 2, 0));
        ObjectAnimator.ofFloat(holder.itemView, "alpha", 0, 1);
        ObjectAnimator.ofFloat(holder.itemView, "scaleX", 0.5f, 1);
        ObjectAnimator.ofFloat(holder.itemView, "scaleY", 0.5f, 1);


        animatorSet.setInterpolator(new DecelerateInterpolator());
        animatorSet.start();

        mLastPosition = position;
    } else {

        ViewHolder.clear(holder.itemView);
    }


}

private void updateUnFavoriteCountry() {

    AsiaCountry asiaCountry;
    int position = item.size();
    asiaCountry = item.get(position);
    String nameCountry = asiaCountry.getName();
    worldCountryDatabase.QueryData("UPDATE country SET FavoriteCountry = 1 WHERE name =' " + nameCountry);
    worldCountryDatabase.close();
}

private void updateFavoriteCountry() {

    AsiaCountry asiaCountry;
    int position = item.size();
    asiaCountry = item.get(position);
    String nameCountry = asiaCountry.getName();
    worldCountryDatabase.QueryData("UPDATE country SET FavoriteCountry = 0 WHERE name =' " + nameCountry);
    worldCountryDatabase.close();
}

@Override
public int getItemCount() {
    return item.size();
}

public void setFilter(ArrayList<AsiaCountry> arrayList) {

    item.clear();
    item.addAll(arrayList);
    notifyDataSetChanged();
}

public static interface Listener {
    public void onClick(int position);
}

public static class ViewHolder extends RecyclerView.ViewHolder {

    private ImageView titleImageCountry;
    public TextView titleNameCountry;
    private ImageButton favoriteCountry;
    private ImageButton shareFavoriteCountry;

    // Defian the viewHolder
    private ViewHolder(View itemView) {
        super(itemView);

        titleImageCountry = (ImageView) itemView.findViewById(R.id.imageHolder);
        titleNameCountry = (TextView) itemView.findViewById(R.id.titleCountry);
        favoriteCountry = (ImageButton) itemView.findViewById(R.id.favoriteCountryImage);
        shareFavoriteCountry = (ImageButton) itemView.findViewById(R.id.shareFavoriteCountry);
    }

    // public static class ViewHolder {

    private static void clear(View itemView) {
        ViewCompat.setAlpha(itemView, 1);
        ViewCompat.setTranslationY(itemView, 0);
        itemView.setPivotY(itemView.getMeasuredHeight() / 2);
        ViewCompat.setScaleX(itemView, 1);
        ViewCompat.setScaleY(itemView, 1);
        ViewCompat.animate(itemView).setInterpolator(null);
        Log.d("Animationg", "Loaded");


    }
}

}

我加载了如下所示的项目,点击“赞”按钮时,必须更改为“喜欢”按钮,并将项目添加到收藏项目中。Recylerview items inside fragment

2 个答案:

答案 0 :(得分:2)

在您的数据库中, ITEM_TABLE 应该有一个 FAVORITE 列,其中整数值(0 == false和1 == true)。当用户点击“收藏夹”按钮时,将FAVORITE值更改为1.

此外,您应该为您的项目设置一个监听器,因此如果项目FAVORITE值发生变化,将会发生某些事情(按钮设计会发生变化等...)

答案 1 :(得分:1)

另外,您可以添加另一个新表格(favourites_table),并在发生操作后,将在您的表格中添加或删除新项目。