【问题标题】:how to refresh/update RecyclerView on button click如何在按钮单击时刷新/更新 RecyclerView
【发布时间】:2018-10-16 05:27:58
【问题描述】:

我使用带有片段的 RecyclerView 来显示来自 SQLite 数据库的数据。

我在 RecyclerView 外部有两个按钮来更改从数据库中检索数据的查询。第一个按钮显示(星期一至星期五)的数据,第二个按钮显示(星期六至星期日)的数据。我试过mAdapter.notifyDataSetChanged();,但它没有用,或者我写得不好。

请帮助我准确地编写该代码

这是我的片段代码:

public class stationFragment extends BaseFragment {

    private List<DatabaseModel> Times = new ArrayList<DatabaseModel>();
    DatabaseHelper databaseHelper;
    public View mView;
    RecyclerView mRecyclerView;
    public RecyclerView.Adapter mAdapter;
    public int Position;

    public static stationFragment instance(int position) {

        stationFragment fragment = new stationFragment();
        fragment.Position = position;
        return fragment;
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        mView = inflater.inflate(R.layout.fragment_station, container, false);
        showInRecyclerView();
        return mView;
    }


    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        list();
    }

    public void list(){
        ArrayList<DatabaseModel> LineList = new ArrayList<>();
        LineList.clear();
        mAdapter = new DataAdapter(LineList);
        DatabaseHelper db = new DatabaseHelper(getContext());
        final List<DatabaseModel> m = db.getAllUsers(Position);
        if (m.size() > 0) {
            for (int i = 0; i < m.size(); i++) {
                LineList.add(m.get(i));
                mAdapter.notifyDataSetChanged();
            }
        }
        db.close();
    }

    public void showInRecyclerView(){

        databaseHelper = new DatabaseHelper(getContext());
        Times = databaseHelper.getAllUsers(Position);
        mRecyclerView = mView.findViewById(R.id.myRecycler);
        mAdapter = new DataAdapter(Times);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecyclerView.setAdapter(mAdapter);

    }
}

这是我的活动代码(buttonOne 和 buttonTwo):

public class station extends BaseActivity {
    Toolbar mToolbar;
    private TabLayout tbLayout;
    private ViewPager vPager;
    private ButtonCell backBtn;
    Boolean btnOneOn = false;
    Boolean btnTwoOn = false;
    ButtonCell Button2;
    ButtonCell Button1;
    RecyclerView recyclerView=findViewById(R.id.myRecycler);


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

        final DatabaseHelper helper = new DatabaseHelper(this);
        try {
            helper.importIfNotExist();
        } catch (IOException ioe) {
            throw new Error("Unable to create database");
        }
        mToolbar = findViewById(R.id.tlbr1);

            setSupportActionBar(mToolbar);


            initView();
            setupWithViewPager();
            tbLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
                @Override
                public void onTabSelected(TabLayout.Tab tab) {

                }

                @Override
                public void onTabUnselected(TabLayout.Tab tab) {

                }

                @Override
                public void onTabReselected(TabLayout.Tab tab) {

                }
            });

        }


    public void line1(View view) {
        Intent line1 = new Intent(this, line1.class);
        startActivity(line1);
    }

    private void setupWithViewPager() {
        BasePagerAdapter basePagerAdapter = new BasePagerAdapter(this, getSupportFragmentManager());
        vPager.setAdapter(basePagerAdapter);
        tbLayout.setupWithViewPager(vPager);

    }

    private void initView() {
        vPager = findViewById(R.id.view_pager);
        tbLayout = findViewById(R.id.tab_layout);
        backBtn = findViewById(R.id.backBtn);


    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.backBtn:
                line1(view);
                return;
        }

    }


    public void buttonOne(View view) {
        Button1 = findViewById(R.id.tg_btn1);
        Button2 = findViewById(R.id.tg_btn2);

        //If the Button is off
        if (!btnOneOn) {

            Button2.setBackgroundColor(getResources().getColor(R.color.md_blue_grey_900));
            Button1.setBackgroundColor(getResources().getColor((R.color.md_white_1000)));
            Button1.setTextColor(getResources().getColor(R.color.md_blue_grey_900));
            Button2.setTextColor(getResources().getColor(R.color.md_white_1000));
            btnTwoOn = false;
            btnOneOn = true;
            C.whatDay = "6";


        }
        //If it is is clicked while on
        else {
            btnTwoOn = false;
            Button2.setBackgroundColor(getResources().getColor((R.color.md_blue_grey_900)));

        }
    }

    public void buttonTwo(View view) {

        Button2 = findViewById(R.id.tg_btn2);
        Button1 = findViewById(R.id.tg_btn1);
        //If the Button is off
        if (!btnTwoOn) {

            Button1.setBackgroundColor(getResources().getColor(R.color.md_blue_grey_900));
            Button2.setBackgroundColor(getResources().getColor((R.color.md_white_1000)));
            Button2.setTextColor(getResources().getColor(R.color.md_blue_grey_900));
            Button1.setTextColor(getResources().getColor(R.color.md_white_1000));
            btnOneOn = false;
            btnTwoOn = true;
            C.whatDay = "7";


        }
        //If it is is clicked while on
        else {
            btnOneOn = false;
            Button1.setBackgroundColor(getResources().getColor((R.color.md_blue_grey_900)));
        }
    }

}

这是我的数据库助手:

public class DatabaseHelper extends SQLiteOpenHelper {
    private static final int DATABASE_VERSION = 2;
    private static final String DATABASE_NAME = "MetroDB";//name of the database
    private static final String TABLE_NAME = "stationtime";//name for the table
    static String db_path = "/data/data/ir.shirazmetro/databases/";
    private static final String Station = "station";
    private static final String Time = "time";
    private static final String Line = "line";
    private static final String Day = "day";
    private final Context context;
    private SQLiteDatabase database;

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.context = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        //Query to create table in databse
        String CREATE_CONTACTS_TABLE = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + "(" + Station + " TEXT," + Time + " TEXT," + Line + " TEXT," + Day + " INTEGER)";
        db.execSQL(CREATE_CONTACTS_TABLE);
    }

    //Executes once a database change is occurred
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(db);

    }

    private boolean checkExist() {
        SQLiteDatabase db = null;
        try {
            db = SQLiteDatabase.openDatabase(db_path + DATABASE_NAME, null, SQLiteDatabase.OPEN_READONLY);
        } catch (SQLException e) {
        }
        return db != null;
    }

    private void copyDatabase() throws IOException {
        OutputStream myOutput = new FileOutputStream(db_path + DATABASE_NAME);
        byte[] buffer = new byte[1024];
        int length;
        InputStream myInput = context.getAssets().open(DATABASE_NAME + ".db");
        while ((length = myInput.read(buffer)) > 0) {
            myOutput.write(buffer, 0, length);
        }
        myInput.close();
        myOutput.flush();
        myOutput.close();
    }

    public void importIfNotExist() throws IOException {
        boolean dbExist = checkExist();
        if (!dbExist) {
            this.getReadableDatabase();
            try {
                copyDatabase();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void open() {
        database = SQLiteDatabase.openDatabase(db_path + DATABASE_NAME, null, SQLiteDatabase.OPEN_READWRITE);
    }

    //method to list all details from table
    public List<DatabaseModel> getAllUsers(int Position) {
        List<DatabaseModel> contactList = new ArrayList<DatabaseModel>();
        String whatStation = C.whatStation;
        String whatLine = C.whatLine;
        String selectQuery = null;
        switch (Position){
            case 0:
                selectQuery = "SELECT " + Time + " FROM " + TABLE_NAME + " WHERE " + Station + " LIKE '%" + whatStation + "%' AND " + Line + " LIKE '%B%' AND " + Day +" LIKE '%" + C.whatDay +"%'" ;
                break;
            case 1:
                selectQuery = "SELECT " + Time + " FROM " + TABLE_NAME + " WHERE " + Station + " LIKE '%" + whatStation + "%' AND " + Line + " LIKE '%A%' AND " + Day +" LIKE '%" + C.whatDay +"%'" ;
                break;

        }
        ;//retrieve data from the database
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        cursor.moveToFirst();
        if (cursor.getCount() > 0) {
            do {
                DatabaseModel m = new DatabaseModel();
//                m.setStation(cursor.getString(0));
                m.setTime(cursor.getString(cursor.getColumnIndex(Time)));
                //              m.setLine(cursor.getString(2));
                contactList.add(m);
            } while (cursor.moveToNext());
        }
        cursor.close();
        return contactList;
    }

}

这是我的数据适配器:

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

    List<DatabaseModel> Times;

    public DataAdapter(List<DatabaseModel> times) {
        Times = times;
    }

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

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

        holder.textViewCell_time.setText(Times.get(position).getTime());
    }

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

    public class MyViewHolder extends RecyclerView.ViewHolder {
        TextViewCell textViewCell_time;
        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            textViewCell_time = itemView.findViewById(R.id.textView);
        }
    }
}

我应该怎么做才能让它正常工作? 谢谢。

【问题讨论】:

  • 请发布您的适配器类
  • 您正在调用 onclickListener 内部活动。但是您想显示在​​该活动内的片段中实现的 recylerview 内的数据?对吗?
  • @Parul 我编辑我的帖子并将我的 dataAdapter 放入帖子中
  • 没错@Raza
  • 我在您的代码中找不到 button1 和 button 2 的点击监听器,以及您从哪里调用方法 public void buttonOne(View view) 和 public void buttonTwo(View view)

标签: android android-studio android-fragments android-sqlite recyclerview-layout


【解决方案1】:

阿里,

根据您的代码:

public void list(){
        ArrayList<DatabaseModel> LineList = new ArrayList<>();
        LineList.clear();
        mAdapter = new DataAdapter(LineList);
        DatabaseHelper db = new DatabaseHelper(getContext());
        final List<DatabaseModel> m = db.getAllUsers(Position);
        if (m.size() > 0) {
            for (int i = 0; i < m.size(); i++) {
                LineList.add(m.get(i));
                mAdapter.notifyDataSetChanged();
            }
        }
        db.close();
    }

    public void showInRecyclerView(){

        databaseHelper = new DatabaseHelper(getContext());
        Times = databaseHelper.getAllUsers(Position);
        mRecyclerView = mView.findViewById(R.id.myRecycler);
        mAdapter = new DataAdapter(Times);      //LINE 1
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecyclerView.setAdapter(mAdapter);

    }

在 OnActivityCreated() 中调用了 list(),在 onCreate() 中调用了 showInRecyclerView(),这两个函数都是 Adapter 的不同对象。所以,我认为,你的 list() 对象被 showInRecyclerView() 覆盖,这就是为什么 mAdapter.notifyDataSetChanged();不管用。 根据您的要求更改您的代码。

阿里, 将您的代码更改为:

 public void list(){
            ArrayList<DatabaseModel> LineList = new ArrayList<>();
            LineList.clear();
            DatabaseHelper db = new DatabaseHelper(getContext());
            final List<DatabaseModel> m = db.getAllUsers(Position);
            if (m.size() > 0) {
                for (int i = 0; i < m.size(); i++) {
                    LineList.add(m.get(i));
                }
            }
            db.close();
        }

【讨论】:

  • 我使用 showInRecyclerView() 因为我有两个标签,当更改标签时调用 showInRecyclerView() 但我是 android 的初学者。请你帮我怎么做
  • 好的,首先告诉我为什么要添加这两个功能。 “Times”和“LineList”的作用是什么?在这两个列表中,哪个列表包含要在回收站视图中填充的实际数据
  • 时间包含要在回收站视图中填充的数据
  • 我必须在哪里调用 list()?在 onclicklistener 中?
  • 我认为这两个函数都在做同样的工作。所以,不要从任何地方调用 List()。删除此方法并检查。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多