I have created a ListView and populated it with items from a database. Currently I am trying to make it so you can long click on an item and delete it from both the ListView and the database together, but something seems to be going wrong. Everything works correctly up until the deleting part. I have it so it deletes the item by fetching its id, which is where I think it is going wrong. I have found a way to show the id and everytime it is returning 0. I have no idea why it is doing this. I am getting no errors, but it is not working as I am hoping for it to. If anybody could point me in the right direction for this that would be awesome.
Here is my databaseHelper class:
public class HabitDbHelper extends SQLiteOpenHelper{
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME="habits";
public static final String TABLE_HABITS = "habit_names";
public static final String KEY_NAME = "hname";
public static final String KEY_ID = "id";
public static final String KEY_STARTDATE = "start_date";
public static final String KEY_ENDDATE = "end_date";
public static final String KEY_DAYCOUNT = "day_count";
public HabitDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE "+TABLE_HABITS+" ("
+KEY_ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "
+KEY_NAME+" TEXT, "
+KEY_STARTDATE+" TEXT, "
+KEY_ENDDATE+" TEXT, "
+KEY_DAYCOUNT+" INTEGER);");
}
// Upgrading Database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_HABITS);
onCreate(db);
}
//Adding new habit
public void addHabit(Habit habit) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, habit.getName()); // Habit Name
values.put(KEY_STARTDATE, habit.getStartDate()); // Start Date
values.put(KEY_ENDDATE, habit.getEndDate()); // End Date
values.put(KEY_DAYCOUNT, habit.getDayCount());
// Inserting Row
db.insert(TABLE_HABITS, null, values);
db.close(); // Closing database connection
}
// Fetching 1 Habit
public Habit getHabit(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_HABITS, new String[] { KEY_ID,
KEY_NAME, KEY_STARTDATE ,KEY_ENDDATE, KEY_DAYCOUNT }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Habit habit = new Habit(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), cursor.getString(3), Integer.parseInt(cursor.getString(4)));
// return contact
return habit;
}
// Fetching all Habits
public ArrayList<Habit> getAllHabits() {
ArrayList<Habit> habitList = new ArrayList<Habit>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_HABITS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Habit habit = new Habit();
habit.setID(Integer.parseInt(cursor.getString(cursor.getColumnIndex(KEY_ID))));
habit.setName(cursor.getString(cursor.getColumnIndex(KEY_NAME)));
habit.setStartDate(cursor.getString(cursor.getColumnIndex(KEY_STARTDATE)));
habit.setEndDate(cursor.getString(cursor.getColumnIndex(KEY_ENDDATE)));
habit.setDayCount(Integer.parseInt(cursor.getString(cursor.getColumnIndex(KEY_DAYCOUNT))));
// Adding contact to list
habitList.add(habit);
} while (cursor.moveToNext());
}
return habitList;
}
//Updating single habit
public int updateHabit(Habit habit) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, habit.getName());
values.put(KEY_STARTDATE, String.valueOf(habit.getStartDate())); // Start Date
values.put(KEY_ENDDATE, habit.getEndDate()); // End Date
values.put(KEY_DAYCOUNT, habit.getDayCount()); // Day Count
// updating row
return db.update(TABLE_HABITS, values, KEY_ID + " = ?",
new String[] { String.valueOf(habit.getID()) });
}
// Deleting Single Habit
public void deleteHabit(Habit habit) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_HABITS, KEY_ID + " = ?",
new String[] { Integer.toString(habit.getID()) });
db.close();
}
// Getting habits count
public int getHabitsCount() {
String countQuery = "SELECT * FROM " + TABLE_HABITS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
}
And my mainActivity where I am calling the onItemLongClickListener with the delete method:
public class fourtyMain extends Activity
{
private HabitDbHelper mDB;
private ListView mList;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fourty_main);
mList = (ListView)findViewById(R.id.habit_list);
mDB = new HabitDbHelper(this);
getActionBar().setDisplayShowTitleEnabled(false);
//long click to delete data
mList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, final View view, int position, long id) {
final Habit habit = (Habit) parent.getAdapter().getItem(position);
deleteHabitInListView(habit);
return true;
}
private void deleteHabitInListView(final Habit habit){
Builder deleteDialog = new AlertDialog.Builder(fourtyMain.this);
deleteDialog.setTitle("Delete " + habit.getName() + "?");
deleteDialog.setMessage("Are you sure you want to delete this habit? All your progress will be lost!");
deleteDialog.setPositiveButton("Yes", new AlertDialog.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mDB.deleteHabit(habit);
displayData();
}
});
deleteDialog.setNegativeButton("No", new AlertDialog.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
deleteDialog.show();
}
});
}
My ListView adapter class:
public class HabitAdapter extends BaseAdapter {
private ArrayList<Habit> habits;
private Context context;
private int layoutId, id1;
public HabitAdapter(Context c, int LayoutId,ArrayList<Habit> habits) {
this.context = c;
this.layoutId = LayoutId;
this.habits = habits;
}
@Override
public int getCount() {
return habits.size();
}
@Override
public Habit getItem(int position) {
return habits.get(position);
}
@Override
public long getItemId(int position) {
Habit habit = (Habit)habits.get(position);
Long idInt = Long.parseLong(habit.getIDString());
return id1;
}
public View getView(int pos, View child, ViewGroup parent) {
Holder mHolder;
LayoutInflater layoutInflater;
Habit habit = habits.get(pos);
if (child == null) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutInflater.inflate(R.layout.fragment_start_habit_item, null);
mHolder = new Holder();
mHolder.title = (TextView)child.findViewById(R.id.fragment_title);
mHolder.dayCount = (TextView)child.findViewById(R.id.fragment_days_left);
mHolder.startDate = (TextView)child.findViewById(R.id.fragment_start_date);
child.setTag(mHolder);
} else {
mHolder = (Holder) child.getTag();
}
mHolder.title.setText(habit.getName());
mHolder.dayCount.setText("Days Completed: " + habit.getDayCountString());
mHolder.startDate.setText("Date Started: " + habit.getStartDate());
return child;
}
public class Holder {
TextView title;
TextView dayCount;
TextView startDate;
}
}
And finally my Habit Object Class:
public class Habit {
private int day_count;
private int _id;
private String habit_name, date_started, end_date, day_count_string, id_string;
public Habit(){
}
public Habit(int id, String name, String startDate, String endDate, int dayCount){
this._id = id;
this.habit_name = name;
this.date_started = startDate;
this.end_date = endDate;
this.day_count = dayCount;
}
public Habit(String name, String startDate, String endDate, int dayCount){
this.habit_name = name;
this.date_started = startDate;
this.end_date = endDate;
this.day_count = dayCount;
}
public int getID()
{
return _id;
}
public int setID(int id)
{
return this._id;
}
public String getIDString()
{
id_string = "" + this._id;
return id_string;
}
public int getDayCount()
{
return this.day_count;
}
public String getDayCountString()
{
day_count_string = "" + this.day_count;
return day_count_string;
}
public int setDayCount(int dayCount)
{
return this.day_count;
}
public String getName()
{
return this.habit_name;
}
public void setName(String name)
{
this.habit_name = name;
}
public String getStartDate()
{
return this.date_started;
}
public void setStartDate(String startDate)
{
this.date_started = startDate;
}
public String getEndDate()
{
return this.end_date;
}
public void setEndDate(String endDate)
{
this.end_date = endDate;
}
}
Now I think I am retrieving the id wrong either from my Habit object class or from the Listview adapter. I am not sure and I am completely lost on this one. Any help is greatly appreciated!
How are you populating your ArrayList? How are you setting the id of each Habit? This is just a guess, but perhaps you are using the position in the Listview as an ID, which does not match the database id? Also, can you clarify "not working"? Is it deleting? Not deleting?
尝试在适配器上调用notifyDataSetChanged()或尝试在listview上调用invalidateViews()。
the database is not deleting because the id in your table is different than the one in your listview.Every time you create an entry, it is established with a new unique id not by its order in the table as the listview does. So add this method to your habitDbHelper class:
public void delete(int orderInList){//orederInList is the position in your listView
SQLiteDatabase db = this.getWritableDatabase();
List<Integer> database_ids = new ArrayList<Integer>();
Cursor c = db.rawQuery("SELECT*FROM "+TABLE_HABITS,null);
while(c.moveToNext){
database_ids.add(Integer.parseInt(c.getString(0)));
}
db.delete(TABLE_HABITS,KEY_ID + " =?",new String[]{String.valueOf(database_ids.get(orderInList)});
And if you want to delete it OnLongClick add this:
ListView lv = (ListView)findViewById(R.id.your_id);
lv.setLongClickable(true);
lv.setOnLongClickListener(new OnLongClickListener(){
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
AlertDialog.Builder aat = new AlertDialog.Builder(this);
aat.setTitle("Delete?")
.setMessage("Are you sure you want to delete "+parent.getItemAtPosition(position).toString()+"?")
.setCancelable(true)
.setNegativeButton("Cancel", new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();
}
})
.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
HabitDbHelper helper = new HabitDBHelper(this);
helper.delete(position);
helper.close();
onCreate(null);//call it here to refresh listView upon delete
}
});
AlertDialog art = aat.create();
art.show();
}
});
hope this helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.