Android Studio: Accessing SQLite Data In RecyclerView

In summary, the conversation is discussing a problem with accessing SQLite data in a RecyclerView and how it may be related to the connection between an activity and the RecyclerView adapter. The project also includes a MainActivity where user input is stored in a database, a DisplayRecordsv2 activity with the RecyclerView, and a RecordsAdapterv2 class for the RecyclerView.
  • #1
Peter Alexander
26
3
Hello everyone!

I'm working on a simple app for a project at the university and I'm having problems accessing the SQLite data in RecyclerView. I suspect that the problem lays in a connection with an activity that includes the RecyclerView and the RecyclerView adapter itself.
My project, in the current state, includes the following classes:
  1. MainActivity: this is where the user is prompted to insert data which will be stored in the database, but it also includes a button with respective on click listener which takes the user to the activity with RecyclerView
    Java:
    public class MainActivity extends AppCompatActivity {
    
        private EditText descriptionAddEdit;
        private EditText locationAddEdit;
        private EditText dateAddEdit;
        private EditText startAddEdit;
        private EditText finishAddEdit;
        private EditText commentsAddEdit;
        private Button addRecordsButton;
        private Button viewRecordsButton;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            descriptionAddEdit = (EditText) findViewById(R.id.descriptionEditMainActivity);
            locationAddEdit = (EditText) findViewById(R.id.locationEditMainActivity);
            dateAddEdit = (EditText) findViewById(R.id.dateEditMainActivity);
            startAddEdit = (EditText) findViewById(R.id.startEditMainActivity);
            finishAddEdit = (EditText) findViewById(R.id.finishEditMainActivity);
            commentsAddEdit = (EditText) findViewById(R.id.commentsEditMainActivity);
            addRecordsButton = (Button) findViewById(R.id.addRecordButtonMainActivity);
            viewRecordsButton = (Button) findViewById(R.id.viewRecordButtonMainActivity);
    
            addRecordsButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    saveRecord();
                }
            });
    
            viewRecordsButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    displayRecord();
                }
            });
    
        }
    
        private void saveRecord() {
            String DESCRIPTION = descriptionAddEdit.getText().toString();
            String LOCATION = locationAddEdit.getText().toString();
            String DATE = dateAddEdit.getText().toString();
            String START = startAddEdit.getText().toString();
            String FINISH = finishAddEdit.getText().toString();
            String COMMENTS = commentsAddEdit.getText().toString();
    
            RecordsDBHelperv2 recordsDBHelperv2 = new RecordsDBHelperv2(this);
            Recordsv2 recordsv2 = new Recordsv2(DESCRIPTION, LOCATION, DATE, START, FINISH, COMMENTS);
            recordsDBHelperv2.addRecords(recordsv2);
        }
    
        private void displayRecord() {
            Intent intent = new Intent(MainActivity.this, DisplayRecordsv2.class);
            startActivity(intent);
        }
    }
  2. DisplayRecordsv2: activity with the RecyclerView
    Java:
    public class DisplayRecordsv2 extends AppCompatActivity {
    
        private String filter = "";
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.display_recyclerview_activity);
    
            populateRecyclerView(filter);
    
        }
    
        private void populateRecyclerView(String filter) {
            RecyclerView recyclerView = findViewById(R.id.recyclerView);
            RecordsDBHelperv2 helperv2 = new RecordsDBHelperv2(this);
            RecordsAdapterv2 adapter = new RecordsAdapterv2(helperv2.recordsList(filter),this);
            recyclerView.setAdapter(adapter);
            recyclerView.setLayoutManager(new LinearLayoutManager(this));
        }
    }
  3. RecordsAdapterv2: adapter class for the RecyclerView
    Java:
    public class RecordsAdapterv2 extends RecyclerView.Adapter<RecordsAdapterv2.ViewHolder> {
        private List<Recordsv2> mRecordsList;
        private Context context;
    
        public RecordsAdapterv2(List<Recordsv2> mRecordsList, Context context) {
            this.mRecordsList = mRecordsList;
            this.context = context;
        }
    
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_line, parent, false);
            ViewHolder holder = new ViewHolder(view);
            return holder;
        }
    
        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
    
            //If "records" won't work, try out "mRecordsList"
            final Recordsv2 records = mRecordsList.get(position);
    
            String descText = context.getString(R.string.setDescriptionTxt);
            String desc = descText + records.getDescription();
            holder.descriptionText.setText(desc);
    
            String locText = context.getString(R.string.setLocationTxt);
            String loc = locText + records.getLocation();
            holder.locationText.setText(loc);
    
            String dtText = context.getString(R.string.setDateTxt);
            String dt = dtText + records.getDate();
            holder.dateText.setText(dt);
    
            String stText = context.getString(R.string.setTimeStartTxt);
            String st = stText + records.getStart();
            holder.startText.setText(st);
    
            String fnText = context.getString(R.string.setTimeFinishTxt);
            String fn = fnText + records.getStart();
            holder.finishText.setText(fn);
    
            String cmText = context.getString(R.string.setCommentsTxt);
            String cm = cmText + records.getComments();
            holder.commentsText.setText(cm);
    
            holder.parentLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    goToUpdateActivityASAP();
                }
            });
        }
    
        private void goToUpdateActivityASAP() {
        }
    
        @Override
        public int getItemCount() {
            return mRecordsList.size();
        }
    
        public class ViewHolder extends RecyclerView.ViewHolder {
            TextView descriptionText, locationText, dateText, startText, finishText, commentsText;
            RelativeLayout parentLayout;
    
            public ViewHolder(View itemView) {
                super(itemView);
                descriptionText = (TextView) itemView.findViewById(R.id.descriptionTextSingleRow);
                locationText = (TextView) itemView.findViewById(R.id.locationTextSingleRow);
                dateText = (TextView) itemView.findViewById(R.id.dateTextSingleRow);
                startText = (TextView) itemView.findViewById(R.id.startTextSingleRow);
                finishText = (TextView) itemView.findViewById(R.id.finsihTextSingleRow);
                commentsText = (TextView) itemView.findViewById(R.id.commentsTextSingleRow);
                parentLayout = (RelativeLayout) itemView.findViewById(R.id.parent_layout);
            }
        }
    }
  4. RecordsDBHelperv2: SQLite helper class which includes the SQLite queries and methods for adding, removing and updating data in the database
    Java:
    public class RecordsDBHelperv2 extends SQLiteOpenHelper {
        private static final int database_version = 1;
        private static final String database_name = "DatabaseRecords.db";
        private static final String table_name = "recordsTasks";
        private static final String column_id = "_id";
        private static final String column_desc = "description";
        private static final String column_loc = "location";
        private static final String column_date = "date";
        private static final String column_strt = "start";
        private static final String column_fnsh = "finish";
        private static final String column_comm = "comment";
    
        public RecordsDBHelperv2(Context context) {
            super(context, database_name, null, database_version);
        }
    
        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL("CREATE TABLE " + table_name + " ("
                    + column_id + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                    + column_desc + " TEXT, "
                    + column_loc + " TEXT, "
                    + column_date + " TEXT, "
                    + column_strt + " TEXT, "
                    + column_fnsh + " TEXT, "
                    + column_comm + " TEXT);");
        }
    
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL("DROP TABLE IF EXISTS " + table_name);
            this.onCreate(db);
        }
    
        public void addRecords(Recordsv2 records) {
            SQLiteDatabase db = this.getWritableDatabase();
            ContentValues values = new ContentValues();
            values.put(column_desc, records.getDescription());
            values.put(column_loc, records.getLocation());
            values.put(column_date, records.getDate());
            values.put(column_strt, records.getStart());
            values.put(column_fnsh, records.getFinish());
            values.put(column_comm, records.getComments());
            db.insert(table_name, null, values);
            db.close();
        }
    
        public void deleteRecords(long id, Context context) {
            SQLiteDatabase db = this.getWritableDatabase();
            db.execSQL("DELETE FROM " + table_name + " WHERE _id = '" + id + "'");
        }
    
        public void updateRecords(long recordID, Context context, Recordsv2 updatedRecords) {
            SQLiteDatabase db = this.getWritableDatabase();
            String query = "UPDATE " + table_name + "SET description = '" + updatedRecords.getDescription() +
                    "', location = '" + updatedRecords.getLocation() +
                    "', date = '" + updatedRecords.getDate() +
                    "', start = '" + updatedRecords.getStart() +
                    "', finish = '" + updatedRecords.getFinish() +
                    "', comment = '" + updatedRecords.getComments() + "' WHERE _id = '" + recordID + "'";
            db.execSQL(query);
        }
    
        public Recordsv2 getRecord(long id) {
            SQLiteDatabase db = this.getWritableDatabase();
            String query = "SELECT * FROM " + table_name + " WHERE _id = " + id;
            Cursor cursor = db.rawQuery(query, null);
    
            Recordsv2 receivedRecords = new Recordsv2();
            if(cursor.getCount() > 0) {
                cursor.moveToFirst();
                receivedRecords.setId(cursor.getLong(cursor.getColumnIndex(column_id)));
                receivedRecords.setDescription(cursor.getString(cursor.getColumnIndex(column_desc)));
                receivedRecords.setLocation(cursor.getString(cursor.getColumnIndex(column_loc)));
                receivedRecords.setDate(cursor.getString(cursor.getColumnIndex(column_date)));
                receivedRecords.setStart(cursor.getString(cursor.getColumnIndex(column_strt)));
                receivedRecords.setFinish(cursor.getString(cursor.getColumnIndex(column_fnsh)));
                receivedRecords.setComments(cursor.getString(cursor.getColumnIndex(column_comm)));
            }
            return receivedRecords;
        }
    
        public List<Recordsv2> recordsList(String filter) {
            String query;
            if(filter.equals("")) {
                query = "SELECT * FROM " + table_name;
            }
            else {
                query = "SELECT * FROM " + table_name + " ORDER BY " + filter;
            }
    
            List<Recordsv2> recordsLinkedList = new LinkedList<>();
            SQLiteDatabase db = this.getWritableDatabase();
            Cursor cursor = db.rawQuery(query, null);
            Recordsv2 records;
    
            if(cursor.moveToFirst()) {
                do {
                    records = new Recordsv2();
                    records.setId(cursor.getLong(cursor.getColumnIndex(column_id)));
                    records.setDescription(cursor.getString(cursor.getColumnIndex(column_desc)));
                    records.setLocation(cursor.getString(cursor.getColumnIndex(column_loc)));
                    records.setDate(cursor.getString(cursor.getColumnIndex(column_date)));
                    records.setStart(cursor.getString(cursor.getColumnIndex(column_strt)));
                    records.setFinish(cursor.getString(cursor.getColumnIndex(column_fnsh)));
                    records.setComments(cursor.getString(cursor.getColumnIndex(column_comm)));
                } while(cursor.moveToNext());
            }
            return recordsLinkedList;
        }
    }
  5. Recordsv2: here I've defined all the getters and setters for data stored in the database
    Java:
    public class Recordsv2 {
        private long id;
        private String description;
        private String location;
        private String date;
        private String start;
        private String finish;
        private String comments;
    
        public Recordsv2(String description, String location, String date, String start, String finish, String comments) {
            this.description = description;
            this.location = location;
            this.date = date;
            this.start = start;
            this.finish = finish;
            this.comments = comments;
        }
    
        public Recordsv2() {
    
        }
    
        public long getId() {
            return id;
        }
    
        public void setId(long id) {
            this.id = id;
        }
    
        public String getDescription() {
            return description;
        }
    
        public void setDescription(String description) {
            this.description = description;
        }
    
        public String getLocation() {
            return location;
        }
    
        public void setLocation(String location) {
            this.location = location;
        }
    
        public String getDate() {
            return date;
        }
    
        public void setDate(String date) {
            this.date = date;
        }
    
        public String getStart() {
            return start;
        }
    
        public void setStart(String start) {
            this.start = start;
        }
    
        public String getFinish() {
            return finish;
        }
    
        public void setFinish(String finish) {
            this.finish = finish;
        }
    
        public String getComments() {
            return comments;
        }
    
        public void setComments(String comments) {
            this.comments = comments;
        }
    }
  6. UpdateRecordsActivityv2: not entirely finished, but is accessible from DisplayRecordsv2 upon clicking on the RecyclerView item. In here, a user will have two options: to check the data and either modify it or delete the whole record
I've posted a similar question awhile ago on StackOverflow, where I though that the problem may lay in concatenating strings in ViewHolder, but even after improving my code with all the proposed edits, I was unable to find a solution to the problem.

The main question I'm having is whether it's OK to declare
Java:
public List<Recordsv2> recordsList(String filter)
in RecordsDBHelper2, then declaring
Java:
private List<Recordsv2>
in RecordsAdapterv2 and lastly populating the RecyclerView using
Java:
RecyclerView recyclerView = findViewById(R.id.recyclerView);
        RecordsDBHelperv2 helperv2 = new RecordsDBHelperv2(this);
        RecordsAdapterv2 adapter = new RecordsAdapterv2(helperv2.recordsList(filter),this);
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

I'm actually completely new to the whole Android scene, so any type of help, even if you are able to point me somewhere (I don't expect anyone to code for me) is very appreciated. I'm here trying to learn something, so if you have any sort of advice or good habits I should use, please feel free to share them.

Thank you in advance to anyone willing to help. Also, I wish you're having a wonderful Sunday!
 
Technology news on Phys.org
  • #2
This will be very hard to debug given only your code. My suggestion is to use some sort of logging to see where things are going and to see if an exception is being thrown. Usually when an exception is thrown, things don’t get executed after the exception point but the program recovers at the try/catch block and ambles on.
 
  • Like
Likes Peter Alexander

1. What is Android Studio?

Android Studio is an Integrated Development Environment (IDE) used for creating Android applications. It provides tools for designing, debugging, and testing Android apps.

2. What is SQLite and why is it used in Android Studio?

SQLite is a lightweight relational database management system that is embedded within the Android operating system. It is used in Android Studio to store and manage data for Android applications.

3. How can I access SQLite data in RecyclerView?

To access SQLite data in RecyclerView, you will need to create a custom RecyclerView adapter that retrieves data from the SQLite database and displays it in the RecyclerView. You will also need to use a RecyclerView.LayoutManager to handle the layout and positioning of items in the RecyclerView.

4. Are there any benefits to using RecyclerView over ListView when accessing SQLite data?

Yes, there are several benefits to using RecyclerView over ListView when accessing SQLite data. RecyclerView is more efficient and flexible, allowing for smoother scrolling and better memory management. It also allows for more customization and easier implementation of animations and touch gestures.

5. Is it possible to implement pagination when accessing SQLite data in RecyclerView?

Yes, pagination can be implemented when accessing SQLite data in RecyclerView. You can use the RecyclerView.OnScrollListener interface to detect when the user has reached the end of the current data set, and then load more data from the database to be displayed in the RecyclerView.

Similar threads

  • Programming and Computer Science
Replies
11
Views
2K
  • Programming and Computer Science
Replies
3
Views
2K
  • Programming and Computer Science
Replies
1
Views
1K
  • Programming and Computer Science
Replies
4
Views
2K
  • Programming and Computer Science
Replies
5
Views
2K
  • Programming and Computer Science
Replies
4
Views
1K
  • Programming and Computer Science
Replies
3
Views
3K
  • Programming and Computer Science
Replies
2
Views
2K
  • Programming and Computer Science
Replies
3
Views
2K
  • Programming and Computer Science
Replies
2
Views
2K
Back
Top