单击按钮时如何刷新/更新RecyclerView

时间:2018-10-16 05:27:59

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

我使用带有片段的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)));
        }
    }

}

这是我的DatabaseHelper:

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;
    }

}

这是我的dataAdapter:

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);
        }
    }
}

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

1 个答案:

答案 0 :(得分: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(),而这两个函数都是您适配器的不同对象。所以,我认为,您的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();
        }