altwin писал(а):откуда берется COLUMN_ID ? если передается в функцию long id параметром то скорее всего именно она должна использоваться в .update()
В функцию long id параметром передается
если я меняю значение тут на 3 например то будет редактироваться именно 3 строка.
Код: Выделить всё
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
EditText editTextDialogUserInput = userInput;
db.updateRec(editTextDialogUserInput
.getText().toString(), 3);
editTextDialogUserInput.setText("");
cursor.requery();
}
А как сделать чтобы я мог редактировать именно ту строку на которую жму?
Полный код BD:
Код: Выделить всё
public class DB {
protected static final long id = 1;
private static final String DB_NAME = "mydb";
private static final int DB_VERSION = 1;
private static final String DB_TABLE = "mytab";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_IMG = "img";
public static final String COLUMN_TXT = "txt";
public static final String COLUMN_NAME = "name";
private static final String DB_CREATE = "create table " + DB_TABLE + "("
+ COLUMN_ID + " integer primary key autoincrement, " + COLUMN_IMG
+ " integer, " + COLUMN_TXT + " text" + "," + COLUMN_NAME + " "
+ ");";
private final Context mCtx;
private DBHelper mDBHelper;
private SQLiteDatabase mDB;
public DB(Context ctx) {
mCtx = ctx;
}
// открыть подключение
public void open() {
mDBHelper = new DBHelper(mCtx, DB_NAME, null, DB_VERSION);
mDB = mDBHelper.getWritableDatabase();
}
// закрыть подключение
public void close() {
if (mDBHelper != null)
mDBHelper.close();
}
// получить все данные из таблицы DB_TABLE
public Cursor getAllData() {
return mDB.query(DB_TABLE, null, null, null, null, null, null);
}
// добавить запись в DB_TABLE
public void addRec(String txt, int img) {
ContentValues cv = new ContentValues();
cv.put(COLUMN_TXT, txt);
cv.put(COLUMN_IMG, img);
mDB.insert(DB_TABLE, null, cv);
}
// редактировать
public void updateRec(String txt, long id) {
ContentValues cv = new ContentValues();
cv.put(COLUMN_TXT, txt);
mDB.update(DB_TABLE, cv, COLUMN_ID + "=?",
new String[] { String.valueOf(id)});
}
public void delRec(long id) {
mDB.delete(DB_TABLE, COLUMN_ID + " = " + id, null);
}
// класс по созданию и управлению БД
private class DBHelper extends SQLiteOpenHelper {
public DBHelper(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
}
// создаем и заполняем БД
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DB_CREATE);
ContentValues cv = new ContentValues();
for (int i = 1; i < 2; i++) {
cv.put(COLUMN_TXT, "Ввести время " + i);
// cv.put(COLUMN_IMG, R.drawable.ic_launcher);
db.insert(DB_TABLE, null, cv);
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
}
Полный код MainActivity:
Код: Выделить всё
public class MainActivity extends Activity {
protected static final long id = 1;
final String TAG = "myLogs";
final Context context = this;
final int DIALOG_EDIT = 1;
int myHour = 12;
int myMinute = 00;
ListView lvMain;
DB db;
Cursor cursor;
SimpleCursorAdapter scAdapter;
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// открываем подключение к БД
db = new DB(this);
db.open();
// получаем курсор
cursor = db.getAllData();
startManagingCursor(cursor);
// формируем столбцы сопоставления
String[] from = new String[] { DB.COLUMN_IMG, DB.COLUMN_TXT };
int[] to = new int[] { R.id.ivImg, R.id.tvText };
// создааем адаптер и настраиваем список
scAdapter = new SimpleCursorAdapter(this, R.layout.item, cursor, from,
to);
lvMain = (ListView) findViewById(R.id.lvMain);
lvMain.setAdapter(scAdapter);
// Связываемся с ListView
ListView lvMain = (ListView) findViewById(R.id.lvMain);
lvMain.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
showDialog(DIALOG_EDIT);
}
});
}
protected Dialog onCreateDialog(int id) {
if (id == DIALOG_EDIT) {
AlertDialog.Builder adb = new AlertDialog.Builder(this);
// !
// get prompts.xml view
LayoutInflater li = LayoutInflater.from(context);
View promptsView = li.inflate(R.layout.promts, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
final EditText userInput = (EditText) promptsView
.findViewById(R.id.editTextDialogUserInput);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
EditText editTextDialogUserInput = userInput;
db.updateRec(editTextDialogUserInput
.getText().toString(), 3);
editTextDialogUserInput.setText("");
cursor.requery();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
// !
return super.onCreateDialog(id);
}
protected void onDestroy() {
super.onDestroy();
// закрываем подключение при выходе
db.close();
}
}