skip to Main Content

I cant seem to find any solutions to this problem on the internet. basically im working on an app that lets the user create workouts and view them and I’m struggling with the view part.

My database is all set up with user input using the fields exercise, sets and reps, the user creates a workout and the contents of the table used to build it are copied to a new one and the table is cleared to take in new input.

I want to create a recycler view using the table names, pass the selected item name to the next fragment and use the users selection to determine what data will be shown in the next recycler view.

Is this possible and if so please show me how, I’m supposed to have this app ready in a couple of days for an assignment

any help would be appreciated, thanks – Ian

2

Answers


  1. Is this possible and if so please show me how.

    It is possible.

    Here’s a working demo that shows how.

    First the class that extends SQLiteOPenHelper, as is typically used, namely DatabaseHelper in this example:-

    class DatabaseHelper extends SQLiteOpenHelper {
    
        public static final String DATABASE_NAME = "thedatabase.db";
        public static final int DATABASE_VERSION = 1;
    
        private SQLiteDatabase db;
    
        private DatabaseHelper(Context context) {
            super(context,DATABASE_NAME,null,DATABASE_VERSION);
            db = this.getWritableDatabase();
        }
    
        private static volatile DatabaseHelper instance = null;
        public static DatabaseHelper getInstance(Context context) {
            if (instance == null) {
                instance = new DatabaseHelper(context);
            }
            return instance;
        }
    
        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(MyTable.CREATE_SQL);
        }
    
        @Override
        public void onUpgrade(SQLiteDatabase db, int old_version, int new_version) {
    
        }
    
        public long insertMyTableRow(Long id, String item_name) {
            ContentValues cv = new ContentValues();
            cv.put(MyTable.COL_ITEM_NAME,item_name);
            if (id != null && id == 0) {
                cv.put(MyTable.COl_ID,id);
            }
            return db.insertWithOnConflict(MyTable.TABLE_NAME,null,cv,SQLiteDatabase.CONFLICT_IGNORE);
        }
    
        @SuppressLint("Range")
        public MyTable[] getAllMyTableRowAsArrayOfMyTable() {
            MyTable[] rv = new MyTable[0];
            Cursor csr = db.query(MyTable.TABLE_NAME,null,null,null,null,null,null);
            if (csr.getCount() > 0) {
                rv = new MyTable[csr.getCount()];
            }
            int idx = 0;
            while (csr.moveToNext()) {
                rv[idx++] = new MyTable(
                        csr.getLong(csr.getColumnIndex(MyTable.COl_ID)),
                        csr.getString(csr.getColumnIndex(MyTable.COL_ITEM_NAME)
                        )
                );
            }
            csr.close();
            return rv;
        }
    
        @SuppressLint("Range")
        public MyTable getAMyTableById(long id) {
            MyTable rv = new MyTable(-1,"NOT FOUND");
            Cursor csr = db.query(MyTable.TABLE_NAME,null,MyTable.COl_ID+"=?",new String[]{String.valueOf(id)},null,null,null);
            if (csr.moveToFirst()) {
                rv = new MyTable(csr.getLong(csr.getColumnIndex(MyTable.COl_ID)),csr.getString(csr.getColumnIndex(MyTable.COL_ITEM_NAME)));
            }
            csr.close();
            return rv;
        }  
    }
    
    class MyTable {
        public static final String TABLE_NAME = (MyTable.class.getSimpleName()).toLowerCase();
        public static final String COl_ID = TABLE_NAME + BaseColumns._ID;
        public static final String COL_ITEM_NAME = TABLE_NAME + "_item_name";
        // and so on
        public static final String CREATE_SQL = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME +
                "("
                + COl_ID + " INTEGER PRIMARY KEY"
                + "," + COL_ITEM_NAME + " TEXT UNIQUE "
                // and so on
                + ")";
        long id;
        String itemName;
        MyTable(long id, String item_name) {
            this.id = id;
            this.itemName = item_name;
        }
    }
    

    The activity that will be called MainActivity2 being passed a unique identifier of the clicked item via an Intent Extra :-

    public class MainActivity2 extends AppCompatActivity {
    
        public static final String INTENT_EXTRA_MYTABLE_ID = "ie_mytable_id";
        DatabaseHelper dbHelper;
        TextView itemName;
        Button done;
    
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main2);
            itemName = this.findViewById(R.id.item_name);
            done = this.findViewById(R.id.done);
            dbHelper = DatabaseHelper.getInstance(this);
            itemName.setText((dbHelper.getAMyTableById(this.getIntent().getLongExtra(INTENT_EXTRA_MYTABLE_ID,-99))).itemName);
            done.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    finish();
                }
            });
        }
    }
    

    An Adapter TheAdapter etc for the RecyclerView, including Item Click and Item Long Click listeners. Clicking an item Toasts details. Long clicking starts the second activity which displays the clicked item:-

    public class TheAdapter extends RecyclerView.Adapter<TheAdapter.ViewHolder> {
    
        private MyTable[] localData;
        public static class ViewHolder extends RecyclerView.ViewHolder {
    
            private final TextView textView1;
            private final TextView textView2;
            public ViewHolder(View view) {
                super(view);
                textView1 = (TextView) view.findViewById(android.R.id.text1);
                textView2 = (TextView) view.findViewById(android.R.id.text2);
            }
    
            public TextView getTextView1() {
                return textView1;
            }
            public TextView getTextView2() {
                return textView2;
            }
        }
    
        public TheAdapter(MyTable[] thedata) {
            localData = thedata;
        }
    
        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(android.R.layout.simple_list_item_2,parent,false);
            return new ViewHolder(view);
        }
    
        @Override
        public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
            holder.getTextView1().setText(String.valueOf(localData[position].id));
            holder.getTextView2().setText(localData[position].itemName);
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Toast.makeText(
                            view.getContext(),
                            "You clicked the Item named "
                                    + localData[holder.getAdapterPosition()].itemName
                                    + " the ID is " + String.valueOf(localData[holder.getAdapterPosition()].id),
                            Toast.LENGTH_SHORT
                    ).show();
                }
            });
            holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View view) {
                    Intent intent = new Intent(view.getContext(),MainActivity2.class);
                    intent.putExtra(MainActivity2.INTENT_EXTRA_MYTABLE_ID,localData[holder.getAdapterPosition()].id);
                    view.getContext().startActivity(intent);
                    return true;
                }
            });
        }
    
        @Override
        public int getItemCount() {
            return localData.length;
        }
    }
    

    Finally the first/initial activity MainActivity :-

    public class MainActivity extends AppCompatActivity {
    
        DatabaseHelper dbHelper;
        RecyclerView myTableList;
        TheAdapter adapter;
        MyTable[] theDataToBeDisplayed;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            myTableList = this.findViewById(R.id.mytable_list);
            dbHelper = DatabaseHelper.getInstance(this);
            addSomeTestingData();
            setupOrRefreshMyTableList();
        }
    
        private void setupOrRefreshMyTableList() {
            theDataToBeDisplayed = dbHelper.getAllMyTableRowAsArrayOfMyTable();
            if (adapter == null) {
                adapter = new TheAdapter(theDataToBeDisplayed);
                myTableList.setAdapter(adapter);
                myTableList.setLayoutManager(
                        new LinearLayoutManager(this)
                );
            } else {
                /* handle changed data here */
            }
        }
    
        private void addSomeTestingData() {
            for (int i=0; i < 100; i++) {
                dbHelper.insertMyTableRow(null, "A" + String.valueOf(i));
            }
        }
    }
    

    When run:-

    enter image description here

    When an Item (e.g. A10 (whos’ id is 11)) is Long clicked :-

    enter image description here

    Clicking DONE returns to the first activity.

    Login or Signup to reply.
  2. To clairfy, you would like to make list of the list?
    Use one to many relationship or map using room.
    I have done such implementation days ago feel free to ask.

    https://developer.android.com/training/data-storage/room/relationships?fbclid=IwAR3P_rK8OeOpBpP9jgbL8FqxEKPXPvOaFwFiCMy4pIpblg_aF_9QloavHpM

    https://developer.android.com/training/data-storage/room/relationships?fbclid=IwAR22XINRNxTs3b_KOleeYwjGuIwjUA90S3tvpMWkf1dKYjvDDo5qWAbLfoE

    To get previous ID or name just use simple Bundle of position(or ID) of specific element from first recyclerview and use it in the second to display the right data.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search