通过对话框更新片段列表视图中显示的数据库条目

Update Database Entry Displayed in Fragment Listview by Dialog

我有一个显示 ListviewFragment,其中填充了来自 Database 使用 SQLiteOpenHelper 的条目。我目前有 ContextMenu 允许删除或编辑条目。 DELETE 选项起作用并从我的 Database 中删除条目,但是 EDIT 选项只接受在 Dialog 中输入的字段并向 [=22] 添加一个新条目=].我希望能够将对话框提供的值归因于 Database 中已经存在的条目。在此先感谢您的任何意见或建议。

片段:

   public static class FragmentS extends Fragment {

    private ListView saveListView;
    private List<LiftSave> LiftSaves = new ArrayList<LiftSave>();
    private static final int EDIT = 0, DELETE = 1;

    LiftSave longClickedItemLiftSave;
    DatabaseHandler dbHandler;
    ArrayAdapter<LiftSave> saveAdapter;

    public FragmentS() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.listview_s,
                container, false);
        saveListView = (ListView) rootView.findViewById(R.id.saveListView);
        registerForContextMenu(saveListView);
        DatabaseHandler dbHandler;
        dbHandler = new DatabaseHandler (getActivity().getApplicationContext());
        if (dbHandler.getLiftSavesCount() != 0)
            LiftSaves.addAll(dbHandler.getAllLiftSaves());

        populateList();

        saveListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                longClickedItemLiftSave = (LiftSave) parent.getItemAtPosition(position);
                return false;
            }
        });

        return rootView;
    }

    private void populateList() {
        saveAdapter = new SaveListAdapter();
        saveListView.setAdapter(saveAdapter);
    }


    public class SaveListAdapter extends ArrayAdapter<LiftSave> {
            public SaveListAdapter() {
                super(getActivity(), R.layout.listview_item, LiftSaves);
            }

            @Override
            public View getView(int position, View view, ViewGroup parent) {
                if (view == null)
                    view = getActivity().getLayoutInflater().inflate(R.layout.listview_item, parent, false);

                LiftSave currentLiftSave = LiftSaves.get(position);

                TextView liftName = (TextView) view.findViewById(R.id.liftName);
                liftName.setText(currentLiftSave.getLiftName());
                TextView maxValue = (TextView) view.findViewById(R.id.maxValue);
                maxValue.setText(currentLiftSave.getMaxValue());
                TextView liftNotes = (TextView) view.findViewById(R.id.liftNotes);
                liftNotes.setText(currentLiftSave.getLiftNotes());
                TextView weightAndReps = (TextView) view.findViewById(R.id.weightAndReps);
                weightAndReps.setText(currentLiftSave.getRepsAndWeight());
                TextView date = (TextView) view.findViewById(R.id.todayDate);
                date.setText(currentLiftSave.getTodayDate());

                return view;
            }

    }
    public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, view, menuInfo);

        menu.setHeaderIcon(R.drawable.pencil_icon);
        menu.setHeaderTitle("Save Options");
        menu.add(Menu.NONE, EDIT, menu.NONE, "Edit Save");
        menu.add(Menu.NONE, DELETE, menu.NONE, "Delete Save");
    }

    public boolean onContextItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case EDIT:
                final View dialogViewEdit = LayoutInflater.from(this.getActivity()).inflate(R.layout.edit_save, null, false);
                final AlertDialog builderE = new AlertDialog.Builder(this.getActivity()).create();

                TextView liftName = (TextView) getActivity().findViewById(R.id.liftName);
                TextView maxValue = (TextView) getActivity().findViewById(R.id.maxValue);
                TextView weightAndReps = (TextView) getActivity().findViewById(R.id.weightAndReps);
                TextView liftNotes = (TextView) getActivity().findViewById(R.id.liftNotes);
                TextView date = (TextView) getActivity().findViewById(R.id.todayDate);

                final EditText editName = (EditText) dialogViewEdit.findViewById(R.id.liftNameED);
                editName.setText(liftName.getText().toString());
                EditText editNotes = (EditText) dialogViewEdit.findViewById(R.id.liftNotesED);
                editNotes.setText(liftNotes.getText().toString());
                EditText editWR = (EditText) dialogViewEdit.findViewById(R.id.txtWRED);
                editWR.setText(weightAndReps.getText().toString());
                EditText editMax = (EditText) dialogViewEdit.findViewById(R.id.txtMaxED);
                editMax.setText(maxValue.getText().toString());
                EditText editDate = (EditText) dialogViewEdit.findViewById(R.id.txtDateED);
                editDate.setText(date.getText().toString());

                Button cancel =(Button) dialogViewEdit.findViewById(R.id.btnCancel);
                Button save =(Button) dialogViewEdit.findViewById(R.id.btnSave);
                cancel.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                    builderE.dismiss();
                    }
                });

                save.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {

                        final EditText editName = (EditText) dialogViewEdit.findViewById(R.id.liftNameED);
                        EditText editNotes = (EditText) dialogViewEdit.findViewById(R.id.liftNotesED);
                        EditText editWR = (EditText) dialogViewEdit.findViewById(R.id.txtWRED);
                        EditText editMax = (EditText) dialogViewEdit.findViewById(R.id.txtMaxED);
                        EditText editDate = (EditText) dialogViewEdit.findViewById(R.id.txtDateED);
                        //Problem
                        dbHandler = new DatabaseHandler(getActivity().getApplicationContext());
                        LiftSave liftSave = new LiftSave(dbHandler.getLiftSavesCount(), String.valueOf(editName.getText()), String.valueOf(editMax.getText()), String.valueOf(editNotes.getText()), String.valueOf(editWR.getText()), String.valueOf(editDate.getText()));
                        LiftSaves.add(liftSave);
                        dbHandler.getLiftSave(longClickedItemLiftSave.getId());
                        dbHandler.updateLiftSave(longClickedItemLiftSave);
                        saveAdapter.notifyDataSetChanged();
                        //Problem
                    }
                });
                builderE.setView(dialogViewEdit);
                builderE.show();
                break;
            case DELETE:
                AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity());
                builder.setMessage("Are you sure you want to delete this save?")
                        .setCancelable(false)
                        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                dbHandler = new DatabaseHandler(getActivity().getApplicationContext());
                                dbHandler.deleteLiftSave(longClickedItemLiftSave);
                                saveAdapter.remove(longClickedItemLiftSave);
                            }
                        })
                        .setNegativeButton("No", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                dialog.cancel();
                            }
                        });
                AlertDialog dialogD = builder.create();
                dialogD.show();
                break;
                            }
                            return super.
                            onContextItemSelected(item);
                        }
        }

数据库:

public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 2;

private static final String DATABASE_NAME = "saveManager",
        TABLE_SAVES = "saves",
        KEY_ID = "id",
        KEY_LIFTNAME = "liftName",
        KEY_MAXVALUE = "txtMax",
        KEY_LIFTNOTES = "txtNotes",
        KEY_REPSANDWEIGHT = "repsAndWeight",
        KEY_TODAYDATE = "todayDate";

public DatabaseHandler(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("CREATE TABLE " + TABLE_SAVES + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_LIFTNAME + " TEXT," + KEY_MAXVALUE + " TEXT," + KEY_LIFTNOTES + " TEXT," + KEY_REPSANDWEIGHT + " TEXT," + KEY_TODAYDATE + " TEXT)");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_SAVES);

    onCreate(db);
}

public void createLiftSave(LiftSave liftSave) {
    SQLiteDatabase db = getWritableDatabase();

    ContentValues values = new ContentValues();

    values.put(KEY_LIFTNAME, liftSave.getLiftName());
    values.put(KEY_MAXVALUE, liftSave.getMaxValue());
    values.put(KEY_LIFTNOTES, liftSave.getLiftNotes());
    values.put(KEY_REPSANDWEIGHT, liftSave.getRepsAndWeight());
    values.put(KEY_TODAYDATE, liftSave.getTodayDate());

    db.insert(TABLE_SAVES, null, values);
    db.close();
}

public LiftSave getLiftSave(int id) {
    SQLiteDatabase db = getReadableDatabase();
    Cursor cursor = db.query(TABLE_SAVES, new String[] { KEY_ID, KEY_LIFTNAME, KEY_MAXVALUE, KEY_LIFTNOTES, KEY_REPSANDWEIGHT, KEY_TODAYDATE }, KEY_ID + "=?", new String[] { String.valueOf(id) }, null, null, null, null );

    if (cursor != null)
        cursor.moveToFirst();

    LiftSave liftSave = new LiftSave(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5) );
    db.close();
    cursor.close();
    return liftSave;
}

public void deleteLiftSave(LiftSave liftSave) {
    SQLiteDatabase db = getWritableDatabase();
    db.delete(TABLE_SAVES, KEY_ID + "=?", new String[] { String.valueOf(liftSave.getId()) });
    db.close();
}

public int getLiftSavesCount() {
    SQLiteDatabase db = getReadableDatabase();
    Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_SAVES, null);
    int count = cursor.getCount();
    db.close();
    cursor.close();

    return count;
}

public int updateLiftSave(LiftSave liftSave) {
    SQLiteDatabase db = getWritableDatabase();

    ContentValues values = new ContentValues();

    values.put(KEY_LIFTNAME, liftSave.getLiftName());
    values.put(KEY_MAXVALUE, liftSave.getMaxValue());
    values.put(KEY_LIFTNOTES, liftSave.getLiftNotes());
    values.put(KEY_REPSANDWEIGHT, liftSave.getRepsAndWeight());
    values.put(KEY_TODAYDATE, liftSave.getTodayDate());

    int rowsAffected = db.update(TABLE_SAVES, values, KEY_ID + "=?", new String[] { String.valueOf(liftSave.getId()) });
    db.close();

    return rowsAffected;
}

public List<LiftSave> getAllLiftSaves() {
    List<LiftSave> liftSaves = new ArrayList<LiftSave>();

    SQLiteDatabase db = getWritableDatabase();
    Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_SAVES, null);

    if (cursor.moveToFirst()) {
        do {
            liftSaves.add(new LiftSave(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5)));
        }
        while (cursor.moveToNext());
    }
    cursor.close();
    db.close();
    return liftSaves;
}
}

提升节省:

public class LiftSave {

private String _liftName, _maxValue, _liftNotes, _repsAndWeight, _todayDate;
private int _id;

public LiftSave(int id, String liftName, String maxValue, String liftNotes, String repsAndWeight, String todayDate) {
    _id = id;
    _liftName = liftName;
    _maxValue = maxValue;
    _liftNotes = liftNotes;
    _repsAndWeight = repsAndWeight;
    _todayDate = todayDate;
}



public int getId() { return _id; }

public String getLiftName() {return _liftName;}

public String getMaxValue() {return _maxValue;}

public String getLiftNotes() {return _liftNotes;}

public String getRepsAndWeight() {return _repsAndWeight;}

public String getTodayDate() {return _todayDate;}

}

编辑:我刚刚看到您的 LiftSave class 后解决它的一种方法。 有了这个修复,你根本不需要修改 DatabaseHandler class:

                //Problem
                dbHandler = new DatabaseHandler(getActivity().getApplicationContext());

                //pass in the existing ID instead of dbHandler.getLiftSavesCount()
                LiftSave liftSave = new LiftSave(longClickedItemLiftSave.getId() , String.valueOf(editName.getText()), String.valueOf(editMax.getText()), String.valueOf(editNotes.getText()), String.valueOf(editWR.getText()), String.valueOf(editDate.getText()));

                //LiftSaves.add(liftSave); //Don't add to the list here
                //dbHandler.getLiftSave(longClickedItemLiftSave.getId()); //looks like this is not needed

                //pass in the LiftSave object with existing ID and new values
                dbHandler.updateLiftSave(liftSave);

                LiftSaves.clear(); //Remove all entries from the list
                LiftSaves.addAll(dbHandler.getAllLiftSaves()); //Re-add all records to List including modified entry
                saveAdapter.notifyDataSetChanged();
                //Problem

请注意,longClickedItemLiftSave.getId() 作为新 LiftSaveid 传入,因此当您将其传入 updateLiftSave() 时,它会更新原始条目。

最初提出的解决方案,另一种解决方法:

首先,让你的 updateLiftSave() 方法接受一个 id 作为参数,并用 id:

更新记录
public int updateLiftSave(LiftSave liftSave, int id) {
    SQLiteDatabase db = getWritableDatabase();

    ContentValues values = new ContentValues();

    values.put(KEY_LIFTNAME, liftSave.getLiftName());
    values.put(KEY_MAXVALUE, liftSave.getMaxValue());
    values.put(KEY_LIFTNOTES, liftSave.getLiftNotes());
    values.put(KEY_REPSANDWEIGHT, liftSave.getRepsAndWeight());
    values.put(KEY_TODAYDATE, liftSave.getTodayDate());

    //int rowsAffected = db.update(TABLE_SAVES, values, KEY_ID + "=?", new String[] { String.valueOf(liftSave.getId()) });
    int rowsAffected = db.update(TABLE_SAVES, values, KEY_ID + "=?", new String[] { String.valueOf(id) });

    db.close();

    return rowsAffected;
}

然后更新时,使用原来的id和新的值:

                        //Problem
                        dbHandler = new DatabaseHandler(getActivity().getApplicationContext());
                        LiftSave liftSave = new LiftSave(dbHandler.getLiftSavesCount(), String.valueOf(editName.getText()), String.valueOf(editMax.getText()), String.valueOf(editNotes.getText()), String.valueOf(editWR.getText()), String.valueOf(editDate.getText()));
                        //LiftSaves.add(liftSave); //don't add it do the list
                        //dbHandler.getLiftSave(longClickedItemLiftSave.getId()); //looks like this is not needed
                        dbHandler.updateLiftSave(liftSave, longClickedItemLiftSave.getId()); //pass in the new values and the existing ID

                        LiftSaves.clear(); //Remove all entries from the list
                        LiftSaves.addAll(dbHandler.getAllLiftSaves()); //Re-add all records to List including modified entry
                        saveAdapter.notifyDataSetChanged();
                        //Problem

更新:您可能还需要添加一个调用来清除 onCreateView() 中的列表,以确保您永远不会在列表中获得重复的条目,并且列表始终反映当前在数据库:

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
       //........
        if (dbHandler.getLiftSavesCount() != 0){
            LiftSaves.clear();  //Clear the list just in case
            LiftSaves.addAll(dbHandler.getAllLiftSaves());
        }

更新 2:关于您的上一期,请尝试使用 LiftSaves 列表而不是 parent AdapterView:

saveListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                //longClickedItemLiftSave = (LiftSave) parent.getItemAtPosition(position);
                longClickedItemLiftSave = LiftSaves.get(position);
                return false;
            }
        });