Что мне нужно, чтобы squentioal мой ID после Удалить записьUpdate SQlite ID
Так что мой Id начать, как (1. 2 +0,3)
Если я удалил строки 2 .. это будет похоже, что (1. 3), и мне нужно быть (1 .2) Я знаю, что идентификатор является первичным ключом, поэтому его нельзя изменить.
Но у меня есть 2 идеи, но я не знаю, как их реализовать
Сначала один является удаление Дб, а затем создать его снова
Второй это сделать новый столбец (Fake_ID) и сделать его последовательным, чтобы отобразить его пользователю, но я не знаю, чтобы сделать это
Это мой код, и если кто-то может его отредактировать и написать запросы, чтобы сделать это, потому что я начинаю эр в андроида и SQLite, я ценю это
Благодаря его заранее
MySQLiteHelper
public class MySQLiteHelper extends SQLiteOpenHelper {
public static final String TABLE_EMPLOYEES = "employees";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_EMPNAME = "empname";
public static final String COLUMN_AGE = "age";
private static final String DATABASE_NAME = "empdb.db";
private static final int DATABASE_VERSION = 1;
// Database creation sql statement
private static final String DATABASE_CREATE = "create table "
+ TABLE_EMPLOYEES + "(" + COLUMN_ID
+ " integer primary key autoincrement not null , " + COLUMN_EMPNAME
+ " text not null , " + COLUMN_AGE
+ " integer not null);";
public MySQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DATABASE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(MySQLiteHelper.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_EMPLOYEES);
onCreate(db);
}
}
Сотрудник
public class Employee {
private long id;
private int age;
private String empName;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
// Will be used by the ArrayAdapter in the ListView
@Override
public String toString() {
return "Name: "+empName+" Age: "+age+" "+ "ID : "+id ;
}
}
EmployeesDataSource
public class EmployeesDataSource {
private SQLiteDatabase database;
private MySQLiteHelper dbHelper;
private String[] allColumns = { MySQLiteHelper.COLUMN_ID,
MySQLiteHelper.COLUMN_EMPNAME, MySQLiteHelper.COLUMN_AGE , MySQLiteHelper.COLUMN_ID};
public EmployeesDataSource(Context context) {
// TODO Auto-generated constructor stub
dbHelper = new MySQLiteHelper(context);
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
public Employee createEmployee(String empname, int age) {
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_EMPNAME, empname);
values.put(MySQLiteHelper.COLUMN_AGE, age);
long insertId = database.insert(MySQLiteHelper.TABLE_EMPLOYEES, null,values);
Cursor cursor = database.query(MySQLiteHelper.TABLE_EMPLOYEES,
allColumns, MySQLiteHelper.COLUMN_ID + " = " + insertId, null,
null, null, null);
cursor.moveToFirst();
Employee newComment = cursorToEmployee(cursor);
cursor.close();
return newComment;
}
public void deleteEmployee(long itemId){
open();
database.delete(MySQLiteHelper.TABLE_EMPLOYEES, "_id = ?", new String[]{Long.toString(itemId)});
close();
}
public ArrayList<Employee> getAllEmployees() {
ArrayList<Employee> employees = new ArrayList<Employee>();
Cursor cursor = database.query(MySQLiteHelper.TABLE_EMPLOYEES,
allColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Employee employee = cursorToEmployee(cursor);
employees.add(employee);
cursor.moveToNext();
}
// Make sure to close the cursor
cursor.close();
return employees;
}
private Employee cursorToEmployee(Cursor cursor) {
Employee employee = new Employee();
employee.setId(cursor.getLong(0));
employee.setEmpName(cursor.getString(1));
employee.setAge(cursor.getInt(2));
return employee;
}
}
MeriUmarKeNaujawanoActivity
public class MeriUmarKeNaujawanoActivity extends Activity {
private EmployeesDataSource datasource;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
datasource = new EmployeesDataSource(this);
datasource.open();
Button btnDone;
btnDone = (Button) findViewById(R.id.btnDone);
btnDone.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Employee employee = null;
EditText enterName = (EditText) findViewById(R.id.edittxtEnterName);
EditText enterAge = (EditText) findViewById(R.id.edittxtEnterAge);
int age = Integer.parseInt(enterAge.getText().toString());
employee = datasource.createEmployee(enterName.getText().toString(),age);
Intent intent = new Intent(MeriUmarKeNaujawanoActivity.this, DisplayListActivity.class);
startActivity(intent);
}
});
}
}
DisplayListActivity
public class DisplayListActivity extends ListActivity {
private EmployeesDataSource datasource;
ArrayList<Employee> values ;
ArrayAdapter<Employee> adapter;
SQLiteDatabase db ;
MySQLiteHelper helper;
public void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.displaylist);
datasource = new EmployeesDataSource(this);
datasource.open();
ListView lv = (ListView)findViewById(android.R.id.list);
values = datasource.getAllEmployees();
adapter = new ArrayAdapter<Employee>(this,
android.R.layout.simple_list_item_1, values);
lv.setAdapter(adapter);
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int Position, long ID) {
// TODO Auto-generated method stub
datasource.deleteEmployee(ID+1);
values.remove(Position);
adapter.notifyDataSetChanged();
return true;
}
});
}
}
Зачем вам нужно обновлять почти все идентификаторы при удалении? – Paulo
Я могу удалить элемент из списка и DB в одно и то же время (OnClickItemlisnter), он работает со мной отлично с функцией удаления в первый раз , но когда я снова вхожу в приложение, просмотр списка indext начинается с 0 снова, а Db не может совпадать с новым списком –
Я думаю, что вам нужно изменить подход и не пытаться обновить идентификатор. Есть другие способы добиться этого без обновления идентификатора. можете ли вы опубликовать свой код, связанный с listview/arrayadapter/cursoradapter? возможно, лучший способ обновить все списки после этого удаления. – Paulo