1

I use RecyclerView with fragment to show my data from SQLite database.

I have two button outside RecyclerView to change query that retrieve data from database.First button show data for (Monday-Friday) and second button show data for (Saturday- Sunday). I tried mAdapter.notifyDataSetChanged(); but it didn't work or I write it bad.

Please help me to write that code exactly

This is my fragment code:

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

    }
}

and this is my activity code (buttonOne and 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)));
        }
    }

}

and this is my 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;
    }

}

this is my 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);
        }
    }
}

what should i do to it work correctly? thanks.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Ali Afkari
  • 41
  • 1
  • 5
  • PLease post your Adapter class – Parul Oct 16 '18 at 05:32
  • you are calling the onclickListener inside activity. but you want to show the data inside recylerview which is implemented in fragment inside that activity ? right? – Raza Oct 16 '18 at 05:35
  • @Parul I edit my post and put my dataAdapter in post – Ali Afkari Oct 16 '18 at 06:12
  • thats right @Raza – Ali Afkari Oct 16 '18 at 06:15
  • i can not find the clicklisteners of button1 and button 2 in your code and where from you are calling the methods public void buttonOne(View view) and public void buttonTwo(View view) – Raza Oct 16 '18 at 06:21
  • but the best approach to update the data by onclicklistener outside the scope of class is that you use rxjava eventbus . – Raza Oct 16 '18 at 06:22
  • RX provides you utils that you can access outside the class. for example you have button in one activity and upon that click you want to perform some action in any other activity or class. – Raza Oct 16 '18 at 06:24
  • i dont write clicklistener becuse i write it but it dosent work and i delete it. buttonOne and ButtonTwo call in xml onclick. i am beginner in android.would you please help me how do that @Raza – Ali Afkari Oct 16 '18 at 06:28

1 Answers1

1

Ali,

As per your code:

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

    }

In OnActivityCreated() you called list() and in onCreate(), you called showInRecyclerView(), and both functions you different objects of Adapter. So , what I think , your list() object is overrided with showInRecyclerView(), That's why it seems that mAdapter.notifyDataSetChanged(); is not working. Change your code according to your requirement.

Ali, Change you code to :

 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();
        }
Parul
  • 387
  • 1
  • 5
  • i use showInRecyclerView() becuse i have two tabs and when change tab call showInRecyclerView() but i am beginner in android.would you please help me how do that – Ali Afkari Oct 16 '18 at 06:33
  • OK, First tell me why you have added these two functions. What is the role of "Times" and "LineList"? Out of these two lists, which list contain actual data to be populated in recycler view – Parul Oct 16 '18 at 06:36
  • Time contain data to be populated in recycler view – Ali Afkari Oct 16 '18 at 06:45
  • and where i must cal list()? in onclicklistener? – Ali Afkari Oct 16 '18 at 07:03
  • I think both functions are doing same work. So, don't call List() from anywhere. Remove this method and check. – Parul Oct 16 '18 at 07:06