how can i change the contents of recycleview at the same time change the data in sqlite?

亡梦爱人 提交于 2020-03-05 03:14:21

问题


I have a button in recycleview(part of cardview, which is generated for each insertion) which increments an specific column with id in SQLite, the data gets changed but I have to relaunch the activity for it to change. The changed data has to be shown in textview.

I am new to this, how can I make them change dynamically?

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

    private List<attendence> mattendence_list;
    private Context mcontext;
    public RecyclerView mrecycleview;
    @NonNull
    @Override
    public attendence_recycleadapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater inflater= LayoutInflater.from(parent.getContext());
        View v=inflater.inflate(R.layout.attendence_recycleview_card,parent,false);
        ViewHolder viewHolder = new ViewHolder(v);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull attendence_recycleadapter.ViewHolder holder, final int position) {
        final attendence attendence= mattendence_list.get(position);

        holder.subname.setText("NAME: " + attendence.getSubname());
        holder.subcredit.setText("CREDIT: " + attendence.getCredit());
        holder.bunks.setText("BUNKS: " + attendence.getBunks());
        holder.deletesub.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Myhelper myhelper = new Myhelper(mcontext);
               myhelper.delete(attendence.getId(),mcontext);
               notifyItemRemoved(position);
               notifyItemRangeChanged(position,mattendence_list.size());
               notifyDataSetChanged();
                delete(position);
            }
        });
        holder.addbunk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Myhelper myhelper = new Myhelper(mcontext);
              myhelper.updatebunk(attendence.getId());
                Toast.makeText(mcontext,"+1 class bunked",Toast.LENGTH_SHORT).show();


            }
        });
        holder.deletebunk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Myhelper myhelper=new Myhelper(mcontext);
                myhelper.updatebunkdelete(attendence.getId());
                Toast.makeText(mcontext,"Bunk deleted",Toast.LENGTH_SHORT).show();
            }
        });

    }

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

    public class ViewHolder extends RecyclerView.ViewHolder {

        public TextView subname;
        public TextView subcredit;
        public TextView bunks;
        public View layout;
        public TextView addbunk;
public TextView deletebunk;
        public TextView deletesub;
        public ViewHolder(View itemView) {
            super(itemView);
            layout=itemView;
            subname=(TextView)itemView.findViewById(R.id.attendernce_subname);
            subcredit=(TextView)itemView.findViewById(R.id.attendernce_credit);
            bunks=(TextView)itemView.findViewById(R.id.attendernce_bunks);
deletebunk =(TextView)itemView.findViewById(R.id.attendence_deletebunk);
            addbunk = (TextView) itemView.findViewById(R.id.attendence_addbunk);
            deletesub = (TextView) itemView.findViewById(R.id.attendence_deletesub);

        }
    }
    public void add(int position,attendence attendence2){
        mattendence_list.add(position,attendence2);
        notifyItemInserted(position);
    }
    public  void delete(int position){
        mattendence_list.remove(position);
        notifyItemRemoved(position);
    }
    public attendence_recycleadapter(List<attendence> mydataset, Context context, RecyclerView recyclerView){
        mattendence_list =  mydataset;
        mcontext = context;
        mrecycleview= recyclerView;
    }


}

myactivity:

public class Manage_attendence extends AppCompatActivity {
    private RecyclerView recyclerView;
    private RecyclerView.LayoutManager layoutManager;
    private attendence_recycleadapter attendence_recycleadapter;
    String filter="";
    TextView add_subject;
    Dialog mycustomDialog;
    Myhelper myhelper;
    SQLiteDatabase sqLiteDatabase;
    Spinner nema_of_credit;
    EditText name_of_subject;
    String spinner_string = new String();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_manage_attendence);
        add_subject=(TextView)findViewById(R.id.add_subject_dialog);
        mycustomDialog = new Dialog(this);
        myhelper = new Myhelper(this);
        sqLiteDatabase = myhelper.getWritableDatabase();
        add_subject.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setupDialog();
            }
        });
        recyclerView= (RecyclerView)findViewById(R.id.attendence_recycleview);
        recyclerView.setHasFixedSize(true);
        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        attendence_recycleadapter= new attendence_recycleadapter(myhelper.list(filter),this,recyclerView);
        recyclerView.setAdapter(attendence_recycleadapter);
        name_of_subject = (EditText) mycustomDialog.findViewById(R.id.name_of_subject);
        nema_of_credit = (Spinner) mycustomDialog.findViewById(R.id.subject_credit);


    }

    public void setupDialog() {

        mycustomDialog.setContentView(R.layout.dialog_add_subject);
        TextView close = (TextView) mycustomDialog.findViewById(R.id.subject_delete);
        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mycustomDialog.dismiss();
            }
        });
     exqButton();
        mycustomDialog.setCancelable(false);
        mycustomDialog.show();
        mycustomDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
    }

    private void exqButton() {
        TextView add =(TextView)mycustomDialog.findViewById(R.id.add);
        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                name_of_subject = (EditText) mycustomDialog.findViewById(R.id.name_of_subject);
                nema_of_credit = (Spinner) mycustomDialog.findViewById(R.id.subject_credit);
                String xValues=String.valueOf(name_of_subject.getText());
                spinner_string=nema_of_credit.getSelectedItem().toString();
                String yValues= ((String.valueOf(spinner_string)));


                boolean insertData = myhelper.insertData(xValues,yValues,0);

                if (insertData==true){
                    Toast.makeText(Manage_attendence.this,"data inserted sucessfully",Toast.LENGTH_SHORT).show();
                }
                else {
                    Toast.makeText(Manage_attendence.this,"data inserted failed",Toast.LENGTH_SHORT).show();
                }
                name_of_subject.setText("");
                mycustomDialog.dismiss();

            }
        });
    }


}

mysqlitehelper:

public class Myhelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME="mydatabase.db";
    public static final String TABLE_NAME="mytable";
    public static final String COLUMN_ID="_id";
    public static final String COL_1="NAME";
    public static  final String COL_2="CREDIT";
    public  static final String COL_3="BUNKS";
    public static final String[] COLUMNS ={COLUMN_ID,COL_1,COL_2,COL_3};
    Context con;

    public Myhelper(Context context) {
        super(context, DATABASE_NAME, null, 1);
        con = context;
    }


    @Override
    public void onCreate(SQLiteDatabase db) {
        String createTable= "CREATE TABLE " + TABLE_NAME + " (" + COLUMN_ID +" INTEGER PRIMARY KEY AUTOINCREMENT, " + " NAME TEXT, CREDIT TEXT, BUNKS INTEGER )";
        db.execSQL(createTable);
        Toast.makeText(con,"table created",Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS "+ TABLE_NAME);
        onCreate(db);

    }
    public boolean insertData(String x,String y,int z){
        SQLiteDatabase db=this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COL_1, String.valueOf(x));
        contentValues.put(COL_2,String.valueOf(y));
       contentValues.put(COL_3,z);
        long result = db.insert(TABLE_NAME, null, contentValues);
        if (result == -1) {
            return false;
        } else {
            return true;
        }
    }

    public ArrayList<String> queryXdata(){
        ArrayList<String> xnewdata= new ArrayList<String>();
        String query = "SELECT "+ COL_1 + " FROM " + TABLE_NAME;
        SQLiteDatabase db=this.getWritableDatabase();
        Cursor cursor= db.rawQuery(query,null);
        for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
            xnewdata.add(cursor.getString(cursor.getColumnIndex(COL_1)));
        }
        cursor.close();
        return xnewdata;

    }
    public ArrayList<Integer> queryYdata(){
        ArrayList<Integer> ynewdata= new ArrayList<Integer>();
        String query = "SELECT "+ COL_3+ " FROM " + TABLE_NAME;
        SQLiteDatabase db=this.getWritableDatabase();
        Cursor cursor= db.rawQuery(query,null);
        for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
            ynewdata.add(cursor.getInt(cursor.getColumnIndex(COL_3)));
        }
        cursor.close();
        return ynewdata;

    }
    public  ArrayList<Integer> queryZdata(){
       ArrayList<Integer> znewdata= new ArrayList<Integer>();
        String query = "SELECT "+ COL_2+ " FROM " + TABLE_NAME;
        SQLiteDatabase db=this.getWritableDatabase();
        Cursor cursor= db.rawQuery(query,null);
        for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
            znewdata.add(((cursor.getColumnIndex(COL_2))));
        }
        cursor.close();
        return znewdata;
    }

    public attendence getdetails(long id){
        SQLiteDatabase db = this.getWritableDatabase();
        String query= "SELECT" + COL_2+" FROM " + TABLE_NAME +" WHERE _id=" + id;
        Cursor cursor= db.rawQuery(query,null);
        attendence attendence1= new attendence();
        if (cursor.getCount()>0){
            cursor.moveToFirst();
            attendence1.setSubname(cursor.getString(cursor.getColumnIndex(COL_1)));
            attendence1.setCredit(cursor.getString(cursor.getColumnIndex(COL_2)));
            attendence1.setBunks(cursor.getInt(cursor.getColumnIndex(COL_3)));
        }
        return attendence1;
    }

    public void delete(long id,Context context){
        SQLiteDatabase db=this.getWritableDatabase();
        db.execSQL("DELETE FROM "+TABLE_NAME+" WHERE _id='"+id+"'");
        Toast.makeText(context,"delted",Toast.LENGTH_SHORT).show();
    }
    public List<attendence> list(String  filter){
        String query;
        if (filter.equals("")){
            query = "SELECT * FROM " + TABLE_NAME ;

        }
        else {
            query= " SELECT * FROM " + TABLE_NAME ;

        }
        List<attendence> linkedlist = new LinkedList<>();
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(query,null);
        attendence attendence;
        if (cursor.moveToFirst()){
            do {
                attendence = new attendence();
                attendence.setId(cursor.getLong(cursor.getColumnIndex(COLUMN_ID)));
                attendence.setSubname(cursor.getString(cursor.getColumnIndex(COL_1)));
                attendence.setCredit(cursor.getString(cursor.getColumnIndex(COL_2)));
                attendence.setBunks(cursor.getInt(cursor.getColumnIndex(COL_3)));
                linkedlist.add(attendence);
            }
            while (cursor.moveToNext());
        }
        return linkedlist;
    }


    public int getbunk(long id) {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_NAME + " WHERE " + COLUMN_ID + " = " + String.valueOf(id), null);
        int output = -1;
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                output = cursor.getInt(cursor.getColumnIndex(COL_3));
            }
            cursor.close();
        }
        return output;

    }
    public void updatebunk(long id){
        SQLiteDatabase db = this.getWritableDatabase();
        int bunk = getbunk(id);
        int bunkinc= ++bunk;
        ContentValues contentValues= new ContentValues();
        contentValues.put(COL_3,bunkinc);
        db.update(TABLE_NAME,contentValues,COLUMN_ID+ "=?",new String[]{String.valueOf(id)});
        db.close();
    }
    public void updatebunkdelete(long id){
        SQLiteDatabase db = this.getWritableDatabase();
        int bunk = getbunk(id);
        int bunkinc= --bunk;
        ContentValues contentValues= new ContentValues();
        contentValues.put(COL_3,bunkinc);
        db.update(TABLE_NAME,contentValues,COLUMN_ID+ "=?",new String[]{String.valueOf(id)});
        db.close();
    }
}

回答1:


Change the updatebunk method:

public int updatebunk(long id){
    SQLiteDatabase db = this.getWritableDatabase();
    int bunk = getbunk(id);
    int bunkinc= ++bunk;
    ContentValues contentValues= new ContentValues();
    contentValues.put(COL_3, bunkinc);
    db.update(TABLE_NAME,contentValues,COLUMN_ID+ "=?",new String[]{String.valueOf(id)});
    db.close();

    return bunkinc;
}

then in your adapter change the listener of addbunk

    holder.addbunk.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Myhelper myhelper = new Myhelper(mcontext);
            int newbunk = myhelper.updatebunk(attendence.getId());
            attendence.setBunks(newbunk);
            mattendence_list.set(position, attendence);
            notifyDataSetChanged();
            Toast.makeText(mcontext,"+1 class bunked",Toast.LENGTH_SHORT).show();
        }
    });


来源:https://stackoverflow.com/questions/51610547/how-can-i-change-the-contents-of-recycleview-at-the-same-time-change-the-data-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!