简体   繁体   English

使用Alertdialog插入项目后,RecyclerView不会刷新

[英]RecyclerView not refreshing after inserting item using Alertdialog

I have an RecycleView. 我有一个RecycleView。 i take an ArrayList for Fetch all my Category that i inserted in mySqliteDatabase. 我拿一个ArrayList来获取我在mySqliteDatabase中插入的所有类别。 and finally i set this ArrayList into RecycleView using its Adapter. 最后我使用它的适配器将这个ArrayList设置为RecycleView。

Problem: 问题:

(1) First Open CategoryActivity. (1)First Open CategoryActivity。 (no categories) (2) Add First Category, Second, Third no one is Refreshing. (没有类别)(2)添加第一类,第二类,第三类没有人刷新。 (3) but after Adding First if i go back. (3)但是如果我回去,在添加第一之后。 and come again in that Activity. 并再次参加那项活动。 and if now i am insert Second categories then all [next items] are getting refresh. 如果现在我插入第二个类别,那么所有[下一个项目]正在刷新。

My Problem is whenever i insert 1st Category. 我的问题是每当我插入第一类别。 it insert successfully but it is not shown in my RecycleView or an ArrayList [means Recycleview not refreshing]. 它成功插入但它没有显示在我的RecycleView或ArrayList中[意味着Recycleview没有刷新]。

but my Main Problem is my RecycleView is not Refreshing only FirstCategory on My ArrayList.. After adding First item my next all Arraylist item is getting Refreshed. 但我的主要问题是我的RecycleView没有刷新我的ArrayList上的FirstCategory ..添加第一项后我的下一个所有Arraylist项目正在刷新。

Below is my All Code. 以下是我的所有代码。

CategoryAdapter CategoryAdapter

public class CategoryAdapter extends RecyclerView.Adapter<CategoryAdapter.MyViewHolder> implements Filterable {

        private ArrayList<CategoryModel> dataList;

        class MyViewHolder extends RecyclerView.ViewHolder {
            TextView tvCategoryItem;

            MyViewHolder(View view) {
                super(view);
                tvCategoryItem = (TextView) view.findViewById(R.id.tvCategoryName);
            }
        }

        CategoryAdapter(ArrayList<CategoryModel> dataSet) {
            this.dataList = dataSet;
            this.filterList = dataSet;
        }

        // I used this method too. but same problem.
        void refreshAdapter(ArrayList<CategoryModel> dataSet) {
            dataList.clear();
            dataList.addAll(dataSet);
            notifyDataSetChanged();
        }

        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.rv_row_category_list, parent, false);

            return new MyViewHolder(itemView);
        }

        @Override
        public void onBindViewHolder(MyViewHolder holder, int position) {
            CategoryModel categoryModel = dataList.get(position);
            holder.tvCategoryItem.setText(categoryModel.getCategoryName());
        }

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

CategoryListActivity CategoryListActivity

MyDatabase myDb;
            CategoryModel categoryModel;
            RecyclerView recyclerCategory;
            RecyclerView.LayoutManager layoutManager;
            CategoryAdapter adapter;
            ArrayList<CategoryModel> allCategory;
            int CategoryType;

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

    myDb = new MyDatabase(this);
    recyclerCategory = (RecyclerView) findViewById(R.id.recyclerCategory);

    CategoryType = CaseActivity.CategoryType;
    Log.d(GlobalConstant.KEY_CATEGORY_TYPE, "" + CategoryType);

    allCategory = myDb.getCategoryByType(CategoryType);

    if (allCategory.size() == 0) {
        Toast.makeText(this, "No Category", Toast.LENGTH_SHORT).show();
    }

    adapter = new CategoryAdapter(allCategory);
    recyclerCategory.setAdapter(adapter);
    layoutManager = new LinearLayoutManager(this);
    recyclerCategory.setLayoutManager(layoutManager);
    recyclerCategory.setItemAnimator(new DefaultItemAnimator());
    recyclerCategory.setHasFixedSize(true);

    recyclerCategory.addOnItemTouchListener(new RecyclerItemClickListener(this, recyclerCategory,
            new RecyclerItemClickListener.OnItemTouchListener() {
                @Override
                public void onItemClick(View view, int position) {
                    TextView tvCategoryItem = (TextView) view.findViewById(R.id.tvCategoryName);
                    String CategoryName = tvCategoryItem.getText().toString();

                    Intent intent = new Intent();
                    CategoryId = allCategory.get(+position).getCategoryId();
                    intent.putExtra("CategoryId", String.valueOf(CategoryId));

                    Log.e("Clicked Cat Id is ", "" + CategoryId);
                    intent.putExtra("CategoryName", CategoryName);
                    setResult(Activity.RESULT_OK, intent);
                    finish();
                }

                @Override
                public void onLongItemClick(View view, int position) {

                }
            }
    ));
}

private void openAlert() {
    final EditText etCategoryName = new EditText(this);

    CustomAlertDialog dialog1 = new CustomAlertDialog(this);
    dialog1.setTitle("Add Category");
    dialog1.setView(etCategoryName);
    dialog1.setCancelable(true);

    dialog1.setPositiveButton("Add", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            final String CategoryName = etCategoryName.getText().toString().trim();
            final String storedCategoryName = myDb.ExistCategory(CategoryName);

            if (CategoryName.equals("") && CategoryName.length() == 0) {
                Builder builder1 = GlobalConstant.createAlert(CategoryListActivity.this, "Warning", "Enter Category Name");
                builder1.setPositiveButton("Back", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                });
            } else {
                if (CategoryName.equals(storedCategoryName)) {
                    Builder builder1 = GlobalConstant.createAlert(CategoryListActivity.this, "Warning", "Category Already Exists");
                    builder1.setPositiveButton("Back", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            dialogInterface.dismiss();
                        }
                    });
                } else {
                    dialogInterface.dismiss();

                    categoryModel = new CategoryModel(CategoryName, String.valueOf(CategoryType));

                    myDb.createCategory(categoryModel);

                    Toast.makeText(CategoryListActivity.this, "CategoryName " + CategoryName
                            + "\nCategoryType " + CategoryType, Toast.LENGTH_SHORT).show();


                    allCategory.clear();

                    allCategory = myDb.getCategoryByType(CategoryType);

                    adapter.notifyDataSetChanged();

                }
            }
        }
    });
    dialog1.show();
}

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            switch (item.getItemId()) {
                case R.id.action_add:
                    openAlert();
                default:
                    return super.onOptionsItemSelected(item);
            }
        }
    }

my createCategory() method. 我的createCategory()方法。

public long createCategory(CategoryModel categoryModel) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();

        values.put(CATEGORY_NAME, categoryModel.getCategoryName());
        values.put(CATEGORY_TYPE, categoryModel.getCategoryType());

        long CategoryId = db.insert(TABLE_CATEGORY, null, values);
        db.close();
        return CategoryId;
    }

and Finally my getCategoryByType() method on My Database . 最后我的数据库上的getCategoryByType()方法。

public ArrayList<CategoryModel> getCategoryByType(int CategoryType) {
        ArrayList<CategoryModel> Categories = new ArrayList<>();
        // String selectQuery = "SELECT " + CATEGORY_NAME + " FROM " + TABLE_CATEGORY + " WHERE " + CATEGORY_TYPE + " = " + CategoryType;
        String selectQuery = "SELECT * FROM " + TABLE_CATEGORY + " WHERE " + CATEGORY_TYPE + " = " + CategoryType + " ORDER BY CategoryId DESC";
        Log.e(DB_LOG, selectQuery);
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.rawQuery(selectQuery, null);
        if (cursor != null && cursor.getCount() > 0) {
            if (cursor.moveToFirst()) {
                do {
                    CategoryModel categoryModel = new CategoryModel();

                    categoryModel.setCategoryId(cursor.getInt(cursor.getColumnIndex(CATEGORY_ID)));
                    categoryModel.setCategoryName(cursor.getString(cursor.getColumnIndex(CATEGORY_NAME)));
                    categoryModel.setCategoryType(cursor.getString(cursor.getColumnIndex(CATEGORY_TYPE)));

                    Categories.add(categoryModel);
                } while (cursor.moveToNext());
            }
            cursor.close();
        }
        return Categories;
    }

Any Type of Help, Suggestion is much Appreciated.....Thanks in advance 任何类型的帮助,建议很多赞赏.....提前感谢

Below is Screenshot after adding First Item. 下面是添加First Item后的屏幕截图。

First Item Inserted but not shown in RecycleView 第一个项目已插入但未在RecycleView中显示

My LogCat Screenshot is below. 我的LogCat截图如下。

Logcat Screenshot Logcat截图

Change your Activity onCreate: 更改您的活动onCreate:

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

        myDb = new MyDatabase(this);
        recyclerCategory = (RecyclerView) findViewById(R.id.recyclerCategory);

        CategoryType = CaseActivity.CategoryType;
        Log.d(GlobalConstant.KEY_CATEGORY_TYPE, "" + CategoryType);
        allCategory = new ArrayList<>();
        adapter = new CategoryAdapter(allCategory);
        layoutManager = new LinearLayoutManager(this);
        recyclerCategory.setLayoutManager(layoutManager);
        recyclerCategory.setItemAnimator(new DefaultItemAnimator());
        recyclerCategory.setHasFixedSize(true);
        recyclerCategory.setAdapter(adapter);

        allCategory = myDb.getCategoryByType(CategoryType);
        adapter.notifyDataSetChange();

        if (allCategory.size() == 0) {

            Toast.makeText(this, "No Category", Toast.LENGTH_SHORT).show();
        }    
    }

and inside setPositiveButton , replace 并在setPositiveButton里面,替换

adapter = new CategoryAdapter(allCategory);
recyclerCategory.setAdapter(adapter);

adapter.notifyDataSetChanged();

with

adapter.notifyDataSetChanged();

Also replace 也替换

allCategory = myDb.getCategoryByType(CategoryType);

with

allCategory.addAll(myDb.getCategoryByType(CategoryType));

And try to run your program again. 并尝试再次运行您的程序。

change your onCreate in this way 以这种方式改变你的onCreate

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

    myDb = new MyDatabase(this);
    recyclerCategory = (RecyclerView) findViewById(R.id.recyclerCategory);

     CategoryType = CaseActivity.CategoryType;
     Log.d(GlobalConstant.KEY_CATEGORY_TYPE, "" + CategoryType);

     allCategory = myDb.getCategoryByType(CategoryType);

     if (allCategory.size() == 0) {
         Toast.makeText(this, "No Category", Toast.LENGTH_SHORT).show();
    }    

    adapter = new CategoryAdapter(allCategory);
    recyclerCategory.setAdapter(adapter);
    layoutManager = new LinearLayoutManager(this);
    recyclerCategory.setLayoutManager(layoutManager);
    recyclerCategory.setItemAnimator(new DefaultItemAnimator());
    recyclerCategory.setHasFixedSize(true);
}

and now you can use adapter.notifyDataSetChanged(); 现在你可以使用adapter.notifyDataSetChanged(); without recreation of adapter and set them to RecyclerView 无需重新创建adapter并将其设置为RecyclerView

if you make in setPositiveButton allCategory = myDb.getCategoryByType(CategoryType); 如果你在setPositiveButton allCategory = myDb.getCategoryByType(CategoryType); then your reference to allCategory is lost. 那么你对allCategory的引用就丢失了。

you need instead 你需要的

allCategory.clear();
allCategory.addAll(myDb.getCategoryByType(CategoryType));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM