在运行时

时间:2017-01-17 01:58:57

标签: java android android-sqlite

我正在尝试创建一个Android应用程序,允许用户从现有的训练列表中创建自定义锻炼列表。我决定创建一个sqlite数据库来完成这个任务。在我的数据库处理程序类“DBHandles.java”中,我创建并填充了“Table_Workouts”,其中包含应用程序中的所有可用训练。同样在“DBHandles.java”中,我创建了另一个空表“Table_User_List”,目的是保存用户选择的“Table_Workouts”表中的特定条目。需要在运行时填充“Table_User_List”。

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;

}

如您所见,我将从DBHandles.class返回一个Arraylist,以显示“Table_Workouts”表的name列。在我的“DisplayAllWorkouts.java”类中访问此ArrayList。 “DiplayAllWorkouts.java”类为“Table_Workouts”表中的每个条目生成一个tablerow,并向用户显示name列。

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

}
}

我的问题如下。我希望能够单击“DisplayAllWorkouts.java”类中显示的表行,并将“Table_Workouts”表中的相应行复制到“Table_User_List”表中。复制行后,我希望“YourListFrag.java”类中显示“Table_User_List”的名称列,并在“DisplayAllWorkouts.java”类中膨胀。

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

    }

每次将新条目添加到“Table_User_List”时,我都需要片段刷新其视图,以便用户可以实时查看“Table_User_List”的名称列的每个条目。我把日志放在我的程序中,流程似乎成功地到达了所有适当的方法调用,而不会抛出错误或崩溃。但是,我的程序不会在“YourListFrag.java”类中显示Table_User_List中的条目。我不知道将行从一个sqlite表复制到另一个sqlite表是否存在问题,显示并引用片段中的name列或将片段膨胀为“DisplayAllWorkouts.java”类。我一直在努力解决这个问题,我终于决定联系我一直在那里的社区。我引用了以下sqlite copy data from one table to another 我无法判断这种方法是否真的适用于我的程序,因为片段中没有显示任何内容。感谢您的时间和精力。我为我评论和发布的代码行道歉。我一直在尝试我能想到的一切。

0 个答案:

没有答案