收藏时会判断失误,然后出现重复收藏的情况

收藏时会判断失误,然后出现重复收藏的情况

首次点击收藏时运行良好,再次点击时也能判断出已收藏。但是在上下页翻动后,判断是否收藏的机制出现异常。之后任意一篇点击收藏后再次点击收藏也能再次收藏,甚至是同篇的多次收藏。

MainActivity.java
package com.example.self_application_homework.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;相关截图:
import android.widget.TextView;
import android.widget.Toast;

import com.example.self_application_homework.R;
import com.example.self_application_homework.bean.Article;
import com.example.self_application_homework.biz.ArticleBiz;
import com.example.self_application_homework.dao.ArticleDao;
import com.example.self_application_homework.dao.ArticleDbHelper;
import com.example.self_application_homework.utils.ImageLoader;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

private Button mBtnDeleteDb;

private Button mBtnLastOne, mBtnCollect, mBtnNextOne;
private TextView mTvMyfavourites, mTvTitle, mTvAuthor, mTvContent;
private ImageView mIvAdvertise;

// for advertisement bitmap
private ImageLoader imageLoader;

// for current page article
int currentPage = 1;
private ArticleBiz mArticleBiz = new ArticleBiz();
private ArticleDao mArticleDao = new ArticleDao();
private Article article = new Article();

// for MyFavourites
Intent itToMyFavourites = null;
List<Article> articleList = new ArrayList<>();

private static final String TAG = "MainActivity -app";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

initViewsNDatas();

loadAdvertisement();

loadDatas(currentPage, false);
}

private void initViewsNDatas() {
mBtnLastOne = findViewById(R.id.id_btn_lastOne);
mBtnCollect = findViewById(R.id.id_btn_collect);
mBtnNextOne = findViewById(R.id.id_btn_nextOne);
mTvMyfavourites = findViewById(R.id.id_tv_myFavourites);
mTvTitle = findViewById(R.id.id_tv_title);
mTvAuthor = findViewById(R.id.id_tv_author);
mTvContent = findViewById(R.id.id_tv_content);
mIvAdvertise = findViewById(R.id.id_iv_advertise);

itToMyFavourites = new Intent(MainActivity.this, MyFavouritesActivity.class);

mBtnDeleteDb = findViewById(R.id.id_btn_deleteDb);
}

public void initEvenets(View v) {
switch (v.getId()) {
case R.id.id_tv_myFavourites:
// 打开收藏页面
if (mArticleDao.loadFromDb(this).isEmpty())
Toast.makeText(this, "还没收藏任何内容", Toast.LENGTH_SHORT).show();
else
startActivity(itToMyFavourites);
break;
case R.id.id_btn_lastOne:
// 打开上一页
Log.d(TAG, "currentPage: " + currentPage);
loadDatas(loadPage(false), true);
break;
case R.id.id_btn_collect:
// 点击收藏按钮
List<Article> articleList = mArticleDao.loadFromDb(this);

// 先判断收藏里(数据库)是否为空,为空直接添加数据,不为空则进一步判断
if (articleList.isEmpty() || articleList == null) {
mArticleDao.insertToDb(this, article);
Toast.makeText(this, "收藏成功", Toast.LENGTH_SHORT).show();
Log.d(TAG, "articleList.isEmpty(): " + articleList.isEmpty());
} else {
// 收藏中有相同的文章则跳过,否则添加巾数据库
for (Article articleInLoop : articleList) {
Log.d(TAG, "article.getTitle().equals(articleInLoop.getTitle()): " + article.getTitle().equals(articleInLoop.getTitle()));
if (article.getTitle().equals(articleInLoop.getTitle())) {
Toast.makeText(this, "此文章已收藏", Toast.LENGTH_SHORT).show();
} else {
mArticleDao.insertToDb(this, article);
Toast.makeText(this, "收藏成功", Toast.LENGTH_SHORT).show();
}
}
}
break;
case R.id.id_btn_nextOne:
// 打开下一页
loadDatas(loadPage(true), true);
break;
case R.id.id_btn_deleteDb:
// 删库
mArticleDao.deleteDb(this);
Toast.makeText(this, "数据库已清空", Toast.LENGTH_SHORT).show();
break;
}
}

private void loadAdvertisement() {
imageLoader = new ImageLoader();
int random = (int) (3 * Math.random() + 1);
imageLoader.loadImageByAsynTask(mIvAdvertise, "http://www.imooc.com/api/teacher?type=1", random);
}

private void loadDatas(int page, boolean isUseCache) {
mArticleBiz.loadDatas(new ArticleBiz.Callback() {
@Override
public void onSuccess(Article resultArticle) {
article = resultArticle;
mTvTitle.setText(article.getTitle());
mTvAuthor.setText(article.getAuthor());
mTvContent.setText(article.getContent());
}

@Override
public void onFailure(Exception ex) {
ex.printStackTrace();
}
}, page, isUseCache);
}

private int loadPage(boolean nextPage) {
if (nextPage == true)
currentPage++;
else
currentPage--;

if (currentPage < 1)
currentPage = 30;
if (currentPage > 30)
currentPage = 1;

return currentPage;
}

}
​ArticleDao.java
​package com.example.self_application_homework.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import androidx.annotation.NonNull;

import com.example.self_application_homework.bean.Article;

import java.util.ArrayList;
import java.util.List;

public class ArticleDao {
public List<Article> loadFromDb(@NonNull Context context) {

ArticleDbHelper dbHelper = ArticleDbHelper.getInstance(context);
SQLiteDatabase db = dbHelper.getWritableDatabase();

List<Article> articleList = new ArrayList<>();

Cursor cursor = db.rawQuery("SELECT * FROM " + Article.TABLE_NAME, null);
Article article = null;
while (cursor.moveToNext()) {
int id = cursor.getInt(cursor.getColumnIndex(Article.COL_ID));
String title = cursor.getString(cursor.getColumnIndex(Article.COL_TITLE));
String author = cursor.getString(cursor.getColumnIndex(Article.COL_AUTHOR));
String content = cursor.getString(cursor.getColumnIndex(Article.COL_CONTENT));
article = new Article(title, author, content);
articleList.add(article);
}
cursor.close();

return articleList;
}

public void insertToDb(@NonNull Context context, Article article) {

if (article == null) {
return;
}

ArticleDbHelper dbHelper = ArticleDbHelper.getInstance(context);
SQLiteDatabase db = dbHelper.getWritableDatabase();

db.beginTransaction();

ContentValues contentValues = null;
contentValues = new ContentValues();
contentValues.put(Article.COL_TITLE, article.getTitle());
contentValues.put(Article.COL_AUTHOR, article.getContent());
contentValues.put(Article.COL_CONTENT, article.getAuthor());
db.insertWithOnConflict(Article.TABLE_NAME, null, contentValues, SQLiteDatabase.CONFLICT_REPLACE);

db.setTransactionSuccessful();
db.endTransaction();
}

public void deleteDb(@NonNull Context context) {
ArticleDbHelper dbHelper = ArticleDbHelper.getInstance(context);
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.execSQL("DELETE FROM " + Article.TABLE_NAME);
}
}

http://img1.sycdn.imooc.com//climg/604436c309f59fd204040859.jpg

http://img1.sycdn.imooc.com//climg/604436c309a64f3f13850992.jpg


正在回答 回答被采纳积分+1

登陆购买课程后可参与讨论,去登陆

1回答
好帮手慕雪 2021-03-08 09:59:34

同学,你好!同学这里的逻辑有问题

http://img1.sycdn.imooc.com//climg/6045844e0953ae2407420221.jpg

判断表中是否有此记录,是不是你得循环完毕才知道它是否已经存在呢?并不是走一条记录就能决定的。所以需要增加一个标志位,如果存在就把标志位设置为已经存在,循环完之后再判断标志位,是不是应该insertToDb()。祝:学习愉快!

  • 提问者 AgonyX #1

    http://img1.sycdn.imooc.com//climg/60458f3d095c68f607290207.jpg

    http://img1.sycdn.imooc.com//climg/60458f5509ee87ce08860495.jpg

    为什么我用这个方法也是行不通呢

    2021-03-08 10:43:46
  • 好帮手慕雪 回复 提问者 AgonyX #2

    http://img1.sycdn.imooc.com//climg/6045b7d709329bd405800188.jpg

    sql的条件连接符是什么?修改一下

    2021-03-08 13:37:27
  • 提问者 AgonyX 回复 好帮手慕雪 #3

    http://img1.sycdn.imooc.com//climg/6045b89f0988922207270231.jpg

    只是中间我怕不会有空格隔开所以加了个连接符而已,但是去掉后一样不管用

    2021-03-08 13:40:15
问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
2.Android 网络操作与流行框架
  • 参与学习           人
  • 提交作业       220    份
  • 解答问题       1800    个

本阶段是联网及数据处理的必备技能。课程从网络基础知识到线程间协同工作、异步下载处理;从文件存储、到轻量级数据库SQLite的使用;最后利用最流程的第三方框架助你快速开发企业级APP。

了解课程
请稍等 ...
意见反馈 帮助中心 APP下载
官方微信

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师