Перезагрузите RecyclerView после добавления новых данных в SQLite - PullRequest
0 голосов
/ 06 мая 2020

Я добавляю новые данные в SQLite по фрагменту AddImages

public class AddImage extends Fragment {

    private ModelClass modelClass;
    private RecyclerViewAdapter recyclerViewAdapter;
    private List<ModelClass> modelClassList;
    private Context context;
    private DatabaseHelper myDB;
    private ImageView imageView;
    private Spinner sp_kind, sp_cat;
    private TextView colorTag;
    private Bitmap bitmap;
    private EditText brandItem;
    private List<ModelClass> oldModelClassList;


    @SuppressLint("ClickableViewAccessibility")
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        final View v = inflater.inflate(R.layout.fragment_addimage, container, false);


        Button add_image = (Button) v.findViewById(R.id.add_image);
        imageView = (ImageView) v.findViewById(R.id.imageview);
        imageView.setDrawingCacheEnabled(true);
        imageView.buildDrawingCache(true);
        sp_cat = (Spinner) v.findViewById(R.id.sp_cat);
        sp_kind = (Spinner) v.findViewById(R.id.sp_kind);
        Button save_image = (Button) v.findViewById(R.id.save_image);
        final View colorView = (View) v.findViewById(R.id.colorView);
        colorTag = (TextView) v.findViewById(R.id.colorTag);
        brandItem = (EditText) v.findViewById(R.id.brandItem);

        //function of button

        add_image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectImage();
            }
        });

         ...



        return v;
    }

    // Choose image from gallery and capture from camera

    private void selectImage() {
        final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("Add Photo");
        builder.setItems(options, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                if (options[item].equals("Take Photo"))
                {
                    Intent intent = new Intent();
                    intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(intent, 1);
                }
                else if (options[item].equals("Choose from Gallery"))
                {
                    Intent intent = new   Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(intent, 2);
                }
                else if (options[item].equals("Cancel")) {
                    dialog.dismiss();
                }
            }
        });
        builder.show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 1) {
                bitmap = (Bitmap) data.getExtras().get("data");
                imageView.setImageBitmap(bitmap);
            } else if (requestCode == 2) {
                Uri selectedImage = data.getData();
                String[] filePath = {MediaStore.Images.Media.DATA};
                assert selectedImage != null;
                Cursor c = getActivity().getContentResolver().query(selectedImage, filePath, null, null, null);
                assert c != null;
                c.moveToFirst();
                int columnIndex = c.getColumnIndex(filePath[0]);
                String picturePath = c.getString(columnIndex);
                c.close();
                bitmap = (BitmapFactory.decodeFile(picturePath));
                Log.w("******************", picturePath + "");
                imageView.setImageBitmap(bitmap);
            }
        }
    }



    public void replaceFragment() {
        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        transaction.replace(R.id.fragment_container, new ClosetFragment());
        transaction.commit();
    }





}

Это RecyclerViewAdapter:

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> {

    private Context context;
    private List<ModelClass> listModel;
    private OnItemClickListener listener;
    RecyclerView mRecyclerV;

    public RecyclerViewAdapter(List<ModelClass> listModel, Context mycontext) {
        this.listModel = listModel;
        context = mycontext;
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view;
        LayoutInflater inflater = LayoutInflater.from(context);
        view = inflater.inflate(R.layout.cardview_item, parent, false);

        return new MyViewHolder(view);
    }

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


        holder.itemDetail.setText(listModel.get(position).getItemKind());
        holder.itemImg.setImageBitmap(listModel.get(position).getItemImage());

    }


    @Override
    public int getItemCount() {

        return listModel.size();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {

        TextView itemDetail;
        ImageView itemImg;
        CardView cv_item;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);

            itemDetail = (TextView) itemView.findViewById(R.id.itemDetail);
            itemImg = (ImageView) itemView.findViewById(R.id.itemImg);
            cv_item = (CardView) itemView.findViewById(R.id.cv_item);


        }
    }

    public interface OnItemClickListener{
        void OnItemClick(ModelClass modelClass);
    }

    public void setOnItemClickListener(OnItemClickListener listener){
        this.listener = listener;
    }

    public void notify(List<ModelClass> list) {
        if (listModel != null) {
            listModel.clear();
            listModel.addAll(list);

        } else {
            listModel = list;
        }
        notifyDataSetChanged();
    }

    public void updateData(List<ModelClass> modelClassList) {
        listModel.clear();
        listModel.addAll(modelClassList);
        notifyDataSetChanged();
    }
    public void addItem(int position, ModelClass modelClass) {
        listModel.add(position, modelClass);
        notifyItemInserted(position);
    }

    public void removeItem(int position) {
        listModel.remove(position);
        notifyItemRemoved(position);
    }


}


ModelClass


public class ModelClass {
    private int itemID;
    private Bitmap itemImage;
    private String itemColor;
    private String itemBrand;
    private String itemKind;
    private String itemCat;

    public ModelClass(){

    }

    ModelClass(Bitmap itemImage, String itemColor, String itemBrand, String itemCat, String itemKind){
        this.itemImage = itemImage;
        this.itemColor = itemColor;
        this.itemBrand = itemBrand;
        this.itemKind = itemKind;
        this.itemCat = itemCat;
    }

    public void setItemID(int itemID){
        this.itemID = itemID;
    }

    public void setItemImage(Bitmap itemImage){
        this.itemImage = itemImage;
    }

    public void setItemColor(String itemColor){
        this.itemColor = itemColor;
    }

    public void setItemBrand(String itemBrand){
        this.itemBrand = itemBrand;
    }

    public  void setItemKind(String itemKind){
        this.itemKind = itemKind;
    }

    public void setItemCat(String itemCat) { this.itemCat = itemCat; }

    public int getItemID(){
        return this.itemID;
    }

    Bitmap getItemImage(){
        return this.itemImage;
    }

    String getItemColor(){
        return this.itemColor;
    }

    String getItemBrand(){
        return this.itemBrand;
    }

    String getItemKind(){
        return this.itemKind;
    }

    String getItemCat(){ return this.itemCat;}

}


DatabaseHelper



public class DatabaseHelper extends SQLiteOpenHelper {

    DatabaseHelper DBHelper;
    RecyclerViewAdapter recyclerViewAdapter;
    ModelClass objectModelClass;
    SQLiteDatabase db;
    public static final String DATABASE_NAME = "SmartFashion.db";
    Context context;
    private ByteArrayOutputStream objectByteArrayOutputStream;
    private byte[] imageInBytes;

    //table Category_table

    public static final String TABLE_CAT = "category_table";
    public static final String CAT_TAG = "cat_tag";
    public static final String CAT_NAME = "cat_name";

    //table Kind_table

    public static final String TABLE_KIND = "kind_table";
    public static final String KIND_TAG = "kind_tag";
    public static final String CAT_KIND_TAG = "cat_kind_tag";

    //table Items_table

    public static final String TABLE_ITEMS = "items_table";
    public static final String ITEM_ID = "item_id";
    public static final String ITEM_IMG = "item_img";
    public static final String ITEM_COLOR = "item_color";
    public static final String ITEM_BRAND = "item_brand";
    public static final String ITEM_KIND_TAG = "item_kind_tag";
    public static final String ITEM_CAT_TAG = "item_cat_tag";

    //create tables

    private static final String CREATE_TABLE_CATEGORY = "CREATE TABLE "
            + TABLE_CAT + "("
            + CAT_TAG + " VARCHAR PRIMARY KEY,"
            + CAT_NAME  + " VARCHAR" + ")";

    private static final String CREATE_TABLE_KIND = "CREATE TABLE "
            + TABLE_KIND + "("
            + KIND_TAG + " VARCHAR PRIMARY KEY,"
            + CAT_KIND_TAG + " VARCHAR,"
            + " FOREIGN KEY (" + CAT_KIND_TAG + ") REFERENCES " + TABLE_CAT + "(" + CAT_TAG + "))";

    private static final String CREATE_TABLE_ITEMS = "CREATE TABLE "
            + TABLE_ITEMS + "("
            + ITEM_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
            + ITEM_IMG + " BLOB NOT NULL,"
            + ITEM_COLOR + " TEXT,"
            + ITEM_BRAND + " VARCHAR,"
            + ITEM_KIND_TAG + "  VARCHAR,"
            + ITEM_CAT_TAG + " VARCHAR,"
            + " FOREIGN KEY (" + ITEM_CAT_TAG + ") REFERENCES " + TABLE_CAT + "(" + CAT_TAG + "), "
            + " FOREIGN KEY (" + ITEM_KIND_TAG + ") REFERENCES " + TABLE_KIND + "(" + KIND_TAG + "))";


    public DatabaseHelper(@Nullable Context context) {
        super(context, DATABASE_NAME, null, 1);
        SQLiteDatabase db = this.getWritableDatabase();
        this.context=context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        db.execSQL(CREATE_TABLE_CATEGORY);



    // Open data

    public DatabaseHelper open() throws SQLException
    {
        db = DBHelper.getWritableDatabase();
        return this;
    }

    // Close data

    public void close()
    {
        DBHelper.close();
    }

        ...

    // Get data of TABLE_ITEMS


    public List<ModelClass> getItem_Tops(){
        //recyclerViewAdapter = new RecyclerViewAdapter(context, getItem_Tops());


        List<ModelClass> topsList = new ArrayList<ModelClass>();

        SQLiteDatabase db = this.getReadableDatabase();
        String[] field = {ITEM_IMG, ITEM_COLOR, ITEM_BRAND, ITEM_CAT_TAG, ITEM_KIND_TAG};
        Cursor c = db.rawQuery("SELECT item_img, item_color, item_brand, item_cat_tag, item_kind_tag FROM items_table WHERE item_cat_tag like 'Tops' ", null);



        for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){


            byte[] IMG = c.getBlob(0);
            String COLOR = c.getString(1);
            String BRAND = c.getString(2);
            String CAT = c.getString(3);
            String KIND = c.getString(4);

            Bitmap bm = BitmapFactory.decodeByteArray(IMG , 0, IMG.length);

            topsList.add(new ModelClass(bm, COLOR, BRAND, CAT, KIND));

        }


        return topsList;
    }


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

        onCreate(db);

    }



    public void storeImage(ModelClass objectModelClass){
        try{
            SQLiteDatabase objectSQLiteDb = this.getWritableDatabase();
            Bitmap imageToStoreBitmap = objectModelClass.getItemImage();
            objectByteArrayOutputStream = new ByteArrayOutputStream();
            imageToStoreBitmap.compress(Bitmap.CompressFormat.JPEG, 100, objectByteArrayOutputStream);
            imageInBytes = objectByteArrayOutputStream.toByteArray();
            ContentValues contentValues = new ContentValues();
            contentValues.put("ITEM_IMG", imageInBytes);
            contentValues.put("ITEM_COLOR", objectModelClass.getItemColor());
            contentValues.put("ITEM_BRAND", objectModelClass.getItemBrand());
            contentValues.put("ITEM_KIND_TAG", objectModelClass.getItemKind());
            contentValues.put("ITEM_CAT_TAG", objectModelClass.getItemCat());

            long checkIfQueryRuns = objectSQLiteDb.insert( TABLE_ITEMS , null, contentValues);
            if(checkIfQueryRuns!=0){
                Toast.makeText(context, "Insert successful!", Toast.LENGTH_SHORT).show();
                objectSQLiteDb.close();
            }else {
                Toast.makeText(context, "Failed to insert...", Toast.LENGTH_SHORT).show();
            }
        }
        catch (Exception e){
            Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    public ModelClass getObjectModelClass(long id){
        SQLiteDatabase db = this.getWritableDatabase();
        String query = "SELECT  * FROM " + TABLE_ITEMS + " WHERE _id="+ id;
        Cursor cursor = db.rawQuery(query, null);

        ModelClass receivedModel = new ModelClass();
        if(cursor.getCount() > 0) {
            cursor.moveToFirst();

            byte[] IMG = cursor.getBlob(cursor.getColumnIndex(ITEM_IMG));
            Bitmap bm = BitmapFactory.decodeByteArray(IMG , 0, IMG.length);

            receivedModel.setItemImage(bm);
            receivedModel.setItemColor(cursor.getString(cursor.getColumnIndex(ITEM_COLOR)));
            receivedModel.setItemBrand(cursor.getString(cursor.getColumnIndex(ITEM_BRAND)));
            receivedModel.setItemCat(cursor.getString(cursor.getColumnIndex(ITEM_CAT_TAG)));
            receivedModel.setItemKind(cursor.getString(cursor.getColumnIndex(ITEM_KIND_TAG)));
        }



        return receivedModel;


    }



}

И это шоу recyclerView во фрагменте TopList


public class TopsList extends Fragment {

    private RecyclerView listItems;
    private RecyclerView.LayoutManager mLayoutManager;
    RecyclerViewAdapter myAdapter;
    DatabaseHelper myDB;
    private List<ModelClass> listModel;
    private String filter = "" ;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        final View v = inflater.inflate(R.layout.fragment_recycleview, container, false);

        listItems = v.findViewById(R.id.recycler_view);
        final Spinner sp_searchKind = v.findViewById(R.id.search_TopsKind);
        Spinner sp_searchColor = v.findViewById(R.id.search_TopsColor);

        myDB = new DatabaseHelper(getActivity());
        listModel = new LinkedList<>();
        listModel.clear();
        listModel.addAll(myDB.getItem_Tops());
        myAdapter = new RecyclerViewAdapter(listModel, this.getContext());
        myAdapter.notifyDataSetChanged();
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
        listItems.setLayoutManager(mLayoutManager);
        listItems.setItemAnimator(new DefaultItemAnimator());
        listItems.setHasFixedSize(true);

        listItems.setAdapter(myAdapter);


        return v;
    }


}


Мой вопрос: как перезагрузить или обновить sh мои данные после добавления данных в SQLite с помощью фрагмента AddImage и его отображения с моим RecyclerView во фрагменте TopsList? Я добавил данные в SQLite до того, как создал RecyclerViewAdapter, затем все данные были показаны с помощью RecyclerViewAdapter. Однако после того, как я добавил новые данные в SQLite, мой RecyclerView не показал их. : ((((Помогите, пожалуйста.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...