0

I am trying to make an android application that allows the user to create a custom workout list from an already existing list of workouts. I decided to create an sqlite database to accomplish this task. In my database handler class "DBHandles.java" I have created and populated "Table_Workouts" with all the available workouts in the application. Also in "DBHandles.java" I have created another empty table "Table_User_List" for the purpose of holding specific entries from the "Table_Workouts" table that the user selects. "Table_User_List" needs to be populated at runtime.

public class DBhandles extends SQLiteOpenHelper {
    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "Workouts.db";
    public static final String TABLE_WORKOUTS = "Workouts";
    public static final String TABLE_USER_LIST = "UserWorkouts";
    public static final String COLUMN_ID = "_id";
    public static final String COLUMN_NAME = "name";
    public static final String COLUMN_DESCRIPTION = "description";
    public static final String COLUMN_LINK = "link";

     @Override
    public void onCreate(SQLiteDatabase db) {
    String CREATE_WORKOUTS_TABLE = "CREATE TABLE " +
            TABLE_WORKOUTS + "("
            + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
            + COLUMN_NAME + " TEXT,"
            + COLUMN_DESCRIPTION + " TEXT,"
            + COLUMN_LINK + " TEXT" + ")";
    String CREATE_USER_TABLE ="CREATE TABLE " +
            TABLE_USER_LIST + "("
            + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
            + COLUMN_NAME + " TEXT,"
            + COLUMN_DESCRIPTION + " TEXT,"
            + COLUMN_LINK + " TEXT" + ")";
    db.execSQL(CREATE_WORKOUTS_TABLE);
    db.execSQL(CREATE_USER_TABLE);
    db.execSQL("INSERT INTO " + TABLE_WORKOUTS + "(name, description, link) VALUES ('Shoulder Press', 'Shoulder PRess description', 'https://www.youtube.com/watch?v=qEwKCR5JCog')");

    public void addWorkout(Workout workout) {
    SQLiteDatabase db = this.getWritableDatabase();
    db.beginTransaction();
    try {
        ContentValues values = new ContentValues();
        values.put(COLUMN_NAME, workout.getWorkoutName());
        values.put(COLUMN_DESCRIPTION, workout.getDescription());
        values.put(COLUMN_LINK, workout.getLink());
        db.insert(TABLE_USER_LIST, null, values);
    } catch (Exception e){
        Log.d(TAG, "Error while trying to add");
    }
    finally{
        db.endTransaction();
    }
    //db.close();
}
    public Workout findWorkout(String Workoutname) {
    String query = "SELECT * FROM " + TABLE_WORKOUTS
            +  " WHERE " + COLUMN_NAME
            + " = \""  + Workoutname + "\"";
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(query, null);
    Workout workout = new Workout();
    if (cursor.moveToFirst()) {
        cursor.moveToFirst();
        workout.setID(Integer.parseInt(cursor.getString(0)));
        workout.setWorkoutName(cursor.getString(1));
        workout.setDescription((cursor.getString(2)));
        workout.setLink(cursor.getString(3));
        cursor.close();
    } else {
        workout = null;
    }
    db.close();
    return workout;
}

public boolean deleteWorkout(String Workoutname) {
    boolean result = false;
    String query = " SELECT * FROM " + TABLE_USER_LIST
            + " WHERE " + COLUMN_NAME
            + " = \"" + Workoutname + "\"";
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(query, null);
    Workout workout = new Workout();
    if (cursor.moveToFirst()) {
        workout.setID(Integer.parseInt(cursor.getString(0)));
        db.delete(TABLE_WORKOUTS, COLUMN_ID + " = ?",
                new String[] { String.valueOf(workout.getID()) });
        cursor.close();
        result = true;
    }
    db.close();
    return result;
}

public ArrayList getAllWorkoutNames (){
   return genericGetSQL(TABLE_WORKOUTS, COLUMN_NAME);
}

public ArrayList genericGetSQL(String whichTable, String whichColumn){
    ArrayList<String> wrkArray = new ArrayList<String>();
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.query(whichTable, new String[]{whichColumn}, null,null, null, null,null);
    String fieldToAdd = null;
    if(cursor.moveToFirst()){
        while(cursor.isAfterLast()==false){
            fieldToAdd = cursor.getString(0);
            wrkArray.add(fieldToAdd);
            cursor.moveToNext();
        }
        cursor.close();
    }
    return wrkArray;

}

As you can see I am returning an Arraylist from the DBHandles.class to display the name column of the "Table_Workouts" table. This ArrayList is accessed in my "DisplayAllWorkouts.java" class. The "DiplayAllWorkouts.java" class generates a tablerow for each entry in the "Table_Workouts" table and displays the name column to the user.

public class DisplayAllWorkouts extends AppCompatActivity implements YourListFrag.OnFragmentInteractionListener { 
    DBhandles db;
    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.displayworkoutlist);

yourListFrag = new YourListFrag();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.LinLayDisplayYourList, yourListFrag, "ARG_PARAM1").
        commit();

context = this;
TableLayout tableLayout = (TableLayout) findViewById(R.id.tableLayout);
TableRow rowHeader = new TableRow(context);
rowHeader.setBackgroundColor(Color.parseColor("#c0c0c0"));
rowHeader.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT,
        TableLayout.LayoutParams.WRAP_CONTENT));
String[] headerText = {"NAME ", " ADD "};
for (String c : headerText) {
    TextView tv = new TextView(this);
    tv.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
            TableRow.LayoutParams.WRAP_CONTENT));
    tv.setTextSize(18);
    tv.setPadding(5, 5, 5, 5);
    tv.setText(c);
    rowHeader.addView(tv);
}
tableLayout.addView(rowHeader);

db = yourListFrag.getDb();//new DBhandles(this, null, null, 1);


final ArrayList<String> arrNames = db.getAllWorkoutNames();
final ArrayList<String> arrDesc = db.getAllWorkoutDescription();
final ArrayList<String> arrLink = db.getAllWorkoutsLink();
for (int i = 0; i < arrNames.size(); i++) {
    TableRow row = new TableRow(this);
    final CheckBox AddBox = new CheckBox(this);
    AddBox.setText("ADD");
    final TextView nametv = new TextView(this);
    //final TextView desctv = new TextView(this);
    //final TextView linktv = new TextView(this);


    nametv.setTextSize(30);
   // desctv.setTextSize(30);
    nametv.setText(arrNames.get(i));

    //desctv.setText(arrDesc.get(i));
    //linktv.setText(arrLink.get(i));

    text = nametv.getText().toString();
    row.addView(nametv);
    row.addView(AddBox);

    AddBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
//                    if(AddBox.isChecked()){
                        Workout wrk = (db.findWorkout(text));
                        db.addWorkout(wrk);
                        yourListFrag.refresh();
                       // yourListFrag.refresh();
                       // yourListFrag.refresh(text);
                //                           }
           // else{
                   // db.deleteWorkout(text);
                        //yourListFrag.delete(nametv.getText().toString());
                      //  yourListFrag.refresh();
             //       }

        }
    });



    row.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent i = new Intent(DisplayAllWorkouts.this, DisplaySingleWorkout.class);

            i.putExtra("itemName", nametv.getText());

            i.putStringArrayListExtra("everydesc", arrDesc);
            i.putStringArrayListExtra("everyname", arrNames);
            i.putStringArrayListExtra("everylink",arrLink);
            startActivity(i);
        }
    });

    tableLayout.addView(row);
}
}

@Override
public void onFragmentInteraction(int position) {

}
}

My problem is as follows. I want to be able to click on a table row displayed in the "DisplayAllWorkouts.java" class and have the corresponding row in "Table_Workouts" table be copied to the "Table_User_List" table. Once the row is copied I want the name column of "Table_User_List" displayed in "YourListFrag.java" class and inflated in the "DisplayAllWorkouts.java" class.

public class YourListFrag extends Fragment {
    private ArrayAdapter<String> arrayAdapter;
    private ListView lstView;
    public ArrayList<String> holdNamesFromDB;


    final DBhandles db = new DBhandles(getContext(), null, null, 1);
    public DBhandles getDb(){
        return this.db;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView =  inflater.inflate(R.layout.your_list, container, false);
        lstView = (ListView)rootView.findViewById(R.id.lstView);
        holdNamesFromDB = db.getAllUserWorkouts();
        arrayAdapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1, holdNamesFromDB);
        lstView.setAdapter(arrayAdapter);
public void refresh(){//String text){
        //arrayAdapter.add(text);
       // db.getAllUserWorkouts();
       // arrayAdapter.notifyDataSetChanged();

        holdNamesFromDB = db.getAllUserWorkouts();
        //arrayAdapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1, db.getAllUserWorkouts());
        arrayAdapter.notifyDataSetChanged();
       // arrayAdapter.notifyDataSetChanged();
       //

    }

I need the fragment to refresh its view everytime a new entry is added to the "Table_User_List" so the user can see every entry of the name column of "Table_User_List" in real time. I put logs in my program and the the flow seemed to successfully reach all the appropriate method calls without throwing an error or crashing. However, my program does not display the entries from Table_User_List in the "YourListFrag.java" class. I don't know if their is a problem copying the row from one sqlite table to the other, displaying and refershing the name column in the fragment or inflating the fragment into "DisplayAllWorkouts.java" class. I have been struggling with this problem for awhile now and I finally decided to reach out to the community that has always been there for me. I have referenced the following sqlite copy data from one table to another and i can't tell if this approach actually works in my program because nothing is displayed in the fragment. Thank you for your time and effort. I apologize for the lines of code i commented out and posted. I have been trying everything i could think of.

Community
  • 1
  • 1
  • First thing I'd do is debug with a breakpoint at `arrayAdapter.notifyDataSetChanged();` to see if `holdNamesFromDB` is populated. If not then error is obviously due to not populating the ArrayList, else the error is obviously later. – MikeT Jan 17 '17 at 02:08
  • To copy data it's something like. `INSERT INTO table1 SELECT column FROM table2`. but if you are trying to find all workouts for a user, that would require some JOIN operation. Whether that is done in a Fragment or Activity is irrelavant – OneCricketeer Jan 17 '17 at 02:09

0 Answers0