使用RecyclerView Adapter中的其他值检查数据库中的Row_id

时间:2016-05-27 10:35:33

标签: android json sqlite android-recyclerview

  

这是我的json respose的结构:

{
"data": [
{
"id": 23,
"title": "this is title",
"description": " this is desc",                                                                                                                                                                       
"date": "21/2/16",
"authorname": "john smith",
"authorpic": "http://xtryz.com/users/1462862047com.yahoo.mobile.client.android.yahoo_128x128.png",
"filename": "1463770591.MP4",
"downloadlink": "http://xyrgz.com/download.zip",
"downloadcnt": "24"
},
...
]

RecyclerView的每一行中单击一个Buton,我将json行保存在数据库中。知道一些我需要知道的工作是这个json行存在于数据库中还是没有?为了完成这项工作,我想使用数据库中的id和json的id。如果数据库的id与json的id相同,那么就做一些工作。

  

这是QuestionDatabaseAdapter:

public class QuestionDatabaseAdapter {
    private Context context;
    private SQLiteOpenHelper sqLiteOpenHelper;
    private static final int DATABASE_VERSION = 1;

    //private SQLiteDatabase database = null;
    public QuestionDatabaseAdapter(Context context) {
        this.context = context;
        sqLiteOpenHelper = new SQLiteOpenHelper(context, "database.db", null, DATABASE_VERSION) {
            @Override
            public void onCreate(SQLiteDatabase db) {
                String sql = "CREATE TABLE tbl_questions ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE, question_id VARCHAR( 255 ) NOT NULL , title VARCHAR( 255 )  NOT NULL, [desc] TEXT NOT NULL, Date VARCHAR( 50 ) NOT NULL, authorName VARCHAR( 255 )  NOT NULL , authorPic VARCHAR( 255 )  NOT NULL, downLink  VARCHAR( 255 )  NOT NULL )";
                db.execSQL(sql);
            }

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

            }
        };
    }


    //================== SAVE QUESTION IN DATABASE ==========================

    public long saveQuestion(ModelQuestion modelQuestion) {

        String question_id = modelQuestion.getQuestionId();
        String title = modelQuestion.getQuestionTitle();
        String desc = modelQuestion.getQuestionDesc();
        String date = modelQuestion.getQuestionDate();
        String authorName = modelQuestion.getQuestionAuthorName();
        String authorPic = modelQuestion.getQuestionAuthorPic();
        String downloadLink = modelQuestion.getQuestionDownLink();

        SQLiteDatabase database = null;
        long id = -1;

        try {

            ContentValues values = new ContentValues();

            values.put("question_id", question_id);
            values.put("title", title);
            values.put("desc", desc);
            values.put("date", date);
            values.put("authorName", authorName);
            values.put("authorPic", authorPic);
            values.put("downLink", downloadLink);

            database = sqLiteOpenHelper.getWritableDatabase();
            id = database.insert("tbl_questions", null, values);

        } catch (Exception ex) {
            Log.i("DATABASE SAVE EX", ex.getMessage());
        } finally {
            if (database != null && database.isOpen()) {
                database.close();
            }
        }
        return id;
    }

    //=================== READ ALL QUESTION IN DATABASE=========================

    public ArrayList<ModelQuestion> readAllQuestions() {
        ArrayList<ModelQuestion> questions = null;
        String[] columns = new String[]{"*"};
        String selection = null;
        String[] selectionArgs = null;
        String groupBy = null;
        String having = null;
        String orderBy = null;
        String limit = null;
        String favorite = null;
        SQLiteDatabase database = null;

        try {

            database = sqLiteOpenHelper.getReadableDatabase();
            Cursor cursor = database.query("tbl_questions", columns, selection, selectionArgs, groupBy, having, orderBy, limit);

            if (cursor != null && cursor.moveToFirst()) {
                questions = new ArrayList<ModelQuestion>();

                int indexQuestionId = 0;
                int indexTitle = 1;
                int indexDesc = 2;
                int indexDate = 3;
                int indexAuthorName = 4;
                int indexAuthorPic = 5;
                int indexDownloadLink = 6;
                int indexFavorite = 7;

                do {

                    String questionId = cursor.getString(indexQuestionId);
                    String questionTitle = cursor.getString(indexTitle);
                    String questionDesc = cursor.getString(indexDesc);
                    String questionDate = cursor.getString(indexDate);
                    String questionAuthorName = cursor.getString(indexAuthorName);
                    String questionAuthorPic = cursor.getString(indexAuthorPic);
                    String questionDownloadLink = cursor.getString(indexDownloadLink);


                    ModelQuestion question = new ModelQuestion();

                    question.setQuestionId(questionId);
                    question.setQuestionTitle(questionTitle);
                    question.setQuestionDesc(questionDesc);
                    question.setQuestionDate(questionDate);
                    question.setQuestionAuthorName(questionAuthorName);
                    question.setQuestionAuthorPic(questionAuthorPic);
                    question.setQuestionDownLink(questionDownloadLink);

                    questions.add(question);


                } while (cursor.moveToNext());
            }


        } catch (Exception ex) {
            Log.i("DATABASE READ ALL EX", ex.getMessage());
        } finally {
            if (database != null && database.isOpen()) {
                database.close();
            }
        }
        return questions;
    }


    //=================== DELETE ONE QUESTION IN DATABASE=========================

    public int deletePerson(long id) {

        int noOfDeletedRecords = 0;
        String whereClause = "id=?";
        String[] whereArgs = new String[]{String.valueOf(id)};
        SQLiteDatabase database = null;

        try {
            database = sqLiteOpenHelper.getWritableDatabase();
            noOfDeletedRecords = database.delete("tbl_questions", whereClause, whereArgs);

        } catch (Exception ex) {
            Log.i("DATABASE DELETE EX", ex.getMessage());
        } finally {
            if (database != null && database.isOpen()) {
                database.close();
            }
        }
        return noOfDeletedRecords;
    }
}
  

这是adapterRecyclerQuestion:

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

    private Context context;
    private ArrayList<ModelQuestion> questionha;


    //constructor

    public AdapterRecyclerQuestion(Context context, ArrayList<ModelQuestion> questionha) {
        this.context = context;
        this.questionha = questionha;
    }

    //viewholder
    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        private TextView txtTitle;
        private TextView txtDesc;
        private TextView txtCntDown;
        private ImageView imgAuthorPic;
        private TextView txtAuthorName;
        private TextView txtDate;
        private Button btnDownload;
        private ImageView imgAddFav;

        public ViewHolder(View itemView) {
            super(itemView);
            itemView.setOnClickListener(this);
            txtTitle = (TextView) itemView.findViewById(R.id.txt_title_question);
            txtDesc = (TextView) itemView.findViewById(R.id.txt_desc_question);
            txtCntDown = (TextView) itemView.findViewById(R.id.txt_cnt_down_question_dy);
            imgAuthorPic = (ImageView) itemView.findViewById(R.id.img_author_pic_question);
            txtAuthorName = (TextView) itemView.findViewById(R.id.txt_author_name_question);
            txtDate = (TextView) itemView.findViewById(R.id.txt_date_question);
            btnDownload = (Button) itemView.findViewById(R.id.btn_down_question);
            imgAddFav = (ImageView) itemView.findViewById(R.id.img_add_to_fav);


        }

        @Override
        public void onClick(View v) {
            Toast.makeText(v.getContext(), "Hello" + txtTitle.getText(), Toast.LENGTH_SHORT).show();
        }
    }
    //oncreateviewholder

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.question_row, parent, false);
        return new ViewHolder(view);
    }

    //onbindviewholder

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

        QuestionDatabaseAdapter questionDatabaseAdapter = new QuestionDatabaseAdapter(holder.itemView.getContext());
        questionDatabaseAdapter.readAllQuestions();

        holder.txtTitle.setText(questionha.get(position).getQuestionTitle());
        holder.txtDesc.setText(questionha.get(position).getQuestionDesc());
        holder.txtCntDown.setText(questionha.get(position).getQuestionDownCnt());
        holder.txtAuthorName.setText(questionha.get(position).getQuestionAuthorName());
        Glide.with(holder.itemView.getContext()).load(questionha.get(position).getQuestionAuthorPic()).into(holder.imgAuthorPic);
        holder.txtDate.setText(questionha.get(position).getQuestionDate());

        //============= IMG ADD TO FAV ON CLICK LISTENER  =========================

        holder.imgAddFav.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                QuestionDatabaseAdapter databaseAdapter = new QuestionDatabaseAdapter(v.getContext());

                ModelQuestion question = new ModelQuestion();

                question.setQuestionId(questionha.get(position).getQuestionId());
                question.setQuestionTitle(questionha.get(position).getQuestionTitle());
                question.setQuestionDesc(questionha.get(position).getQuestionDesc());
                question.setQuestionDate(questionha.get(position).getQuestionDate());
                question.setQuestionAuthorName(questionha.get(position).getQuestionAuthorName());
                question.setQuestionAuthorPic(questionha.get(position).getQuestionAuthorPic());
                question.setQuestionDownLink(questionha.get(position).getQuestionDownLink());


                databaseAdapter.saveQuestion(question);

                Toast.makeText(v.getContext(), "اضافه شد", Toast.LENGTH_SHORT).show();


            }
        });


        //=============BTN DOWNLOAD CLICK LISTENER =========================

        holder.btnDownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
                DownloadManager.Request request = new DownloadManager.Request(Uri.parse(questionha.get(position).getQuestionDownLink()));

                request.setTitle(questionha.get(position).getQuestionTitle());
                request.setDescription("در حال دانلود");
                request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, questionha.get(position).getQuestionDownFileName());
                long enqueueId = downloadManager.enqueue(request);
            }
        });

    }

    //getitemcount
    @Override
    public int getItemCount() {
        return questionha.size();
    }

}
  

这是数据库结构:   (question_id是问题的ID)

现在我需要在适配器中比较数据库的id和json的id。但我不知道我怎么能这样做。 enter image description here

1 个答案:

答案 0 :(得分:0)

 private ArrayList<ModelQuestion> questionha;
 private ArrayList<ModelQuestion> jsonArrList;

//pass your json arraylist too in constructor from your main activity

public AdapterRecyclerQuestion(Context context, ArrayList<ModelQuestion> questionha,ArrayList<ModelQuestion> jsonArrList) {
    this.context = context;
    this.questionha = questionha;
    this.jsonArrList = jsonArrList;
}


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

   for(int i=0;i<jsonArrList.size();i++)
   {
        //Check your id here
 if(jsonArrList.get(i).getId().equalsIgnoreCase(questionha.get(position).getId()))

   }

}