1

我有个问题。我的项目中有一个 sqlite 数据库。我在数据库中选择数据并传输自定义列表视图。我的自定义 ListView 有一个删除按钮。当我按下按钮时,我的 CostumListView 类将删除这一行。但是 Listview 是一样的。我想在删除过程后刷新列表视图。

这是我的 LAUNCHER 类(TaskList.java):

package com.nano.tasklist;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

public class TaskList extends Activity {

ArrayList<CategoryInfo> CategoryList;

TaskListDatabase DatabaseActivity;

private CategoryAdapter CategoryAdapter = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_task_list);

    DatabaseActivity = new TaskListDatabase(this);

    CategoryInsert("School","21.02.2012","YES");
    CategoryInsert("House","21.02.2012","NO");
    CategoryInsert("Park","21.02.2012","YES");

    ListView lvCategories = (ListView) findViewById(R.id.lvCategories);

    CategoryList = new ArrayList<CategoryInfo>();

    CategoryAdapter = new CategoryAdapter(this, R.layout.category_row, CategoryList);
    lvCategories.setAdapter(this.CategoryAdapter);

    CategorySelect();
}

public void CategorySelect(){
    String[] Column = {"ID","Category","AddDate","Completed"};

    Cursor Result = null;

    try{
        SQLiteDatabase Database = DatabaseActivity.getReadableDatabase();

        Result = Database.query("Category", Column, null, null, null, null, null);

        startManagingCursor(Result);

        while(Result.moveToNext()){
            CategoryInfo Info = new CategoryInfo();

            CategoryList = new ArrayList<CategoryInfo>();

            Info.setID(Result.getString(Result.getColumnIndex("ID")));
            Info.setCategory(Result.getString(Result.getColumnIndex("Category")));
            Info.setAddDate(Result.getString(Result.getColumnIndex("AddDate")));
            Info.setCompleted(Result.getString(Result.getColumnIndex("Completed")));

            CategoryList.add(Info);

            if(CategoryList != null && CategoryList.size() > 0){
                CategoryAdapter.add(CategoryList.get(0));
                CategoryAdapter.notifyDataSetChanged();
            }
        }
    } catch (SQLiteException Error) {
        Toast.makeText(getApplicationContext(), "Error (CategorySelect) : " + Error.toString(), Toast.LENGTH_LONG).show();

        Result = null;
    }
}

public boolean CategoryInsert(String Category, String AddDate, String Completed){
    boolean Result;

    try{
        SQLiteDatabase Database = DatabaseActivity.getWritableDatabase();

        ContentValues Values = new ContentValues();

        Values.put("Category", Category);
        Values.put("AddDate", AddDate);
        Values.put("Completed", Completed);

        Database.insert("Category", null, Values);

        Result = true;
    } catch (SQLiteException Error) {
        Toast.makeText(getApplicationContext(), "Error (CategoryInsert) : " + Error.toString(), Toast.LENGTH_LONG).show();

        Result = false;
    }

    return Result;
}

这是我的 CustomListAdapter 类(CategoryAdapter.java)

package com.nano.tasklist;

import java.util.ArrayList;

import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;

public class CategoryAdapter extends ArrayAdapter<CategoryInfo>{

private Context ActivityContext = null;
private ArrayList<CategoryInfo> Items = null;

TaskListDatabase DatabaseActivity;

public CategoryAdapter(Context Context, int textViewResourceId, ArrayList<CategoryInfo> Items){
    super(Context,textViewResourceId,Items);

    this.ActivityContext = Context;
    this.Items=Items;

    DatabaseActivity = new TaskListDatabase(Context);
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    View MainView = convertView;

    if (MainView == null) {
        LayoutInflater Layout = (LayoutInflater) ActivityContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        MainView = Layout.inflate(R.layout.category_row, null);
    }

    final CategoryInfo Item = Items.get(position);

    if (Item != null) {

        final CheckBox cbCompleted = (CheckBox) MainView.findViewById(R.id.cbCategoryCompleted);
        final TextView tvCategoryName = (TextView) MainView.findViewById(R.id.tvCategoryName);
        final TextView tvAddDate = (TextView) MainView.findViewById(R.id.tvAddDate);
        final TextView tvDataValue = (TextView) MainView.findViewById(R.id.tvDataValue);
        final Button btnDeleteCategory = (Button) MainView.findViewById(R.id.btnDeleteCategory);

        tvCategoryName.setText(Item.getCategory());
        tvAddDate.setText(Item.getAddDate());
        tvDataValue.setText(Item.getDataValue());

        if(Item.getCompleted().equals("YES")){
            cbCompleted.setChecked(true);

            tvCategoryName.setEnabled(false);
            tvAddDate.setEnabled(false);
            tvDataValue.setEnabled(false);
        } else {
            cbCompleted.setChecked(false);

            tvCategoryName.setEnabled(true);
            tvAddDate.setEnabled(true);
            tvDataValue.setEnabled(true);
        }

        cbCompleted.setOnCheckedChangeListener(new OnCheckedChangeListener(){
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    CategoryUpdate(Item.getID(),"Completed","YES");

                    tvCategoryName.setEnabled(false);
                    tvAddDate.setEnabled(false);
                    tvDataValue.setEnabled(false);
                } else {
                    CategoryUpdate(Item.getID(),"Completed","NO");

                    tvCategoryName.setEnabled(true);
                    tvAddDate.setEnabled(true);
                    tvDataValue.setEnabled(true);
                }
            }
        });

        btnDeleteCategory.setOnClickListener(new OnClickListener(){
            public void onClick(View v) {
                TaskList Process = new TaskList();
                Process.Delete(btnDeleteCategory, Item.getID());
            }
        });
    }

    return MainView;
}

public boolean CategoryUpdate(String ID, String Key, String Value){
    boolean Result;

    try{
        SQLiteDatabase Database = DatabaseActivity.getWritableDatabase();

        ContentValues Values = new ContentValues();

        Values.put(Key, Value);

        Database.update("Category", Values, "ID = " + ID, null);

        Result = true;
    } catch (SQLiteException Error) {
        Toast.makeText(ActivityContext, "Error (CategoryUpdate) : " + Error.toString(), Toast.LENGTH_LONG).show();

        Result = false;
    }

    return Result;
}

public void CategoryDelete(final String ID){
    try{

        AlertDialog.Builder Builder = new AlertDialog.Builder(ActivityContext);
        Builder.setMessage("If you delete this category, category's tasks will be deleted ! Do you want to delete this category ?")
                .setCancelable(false)
                .setPositiveButton("YES",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int which) {
                                SQLiteDatabase Database = DatabaseActivity.getWritableDatabase();

                                Database.delete("Category", "ID = " + ID, null);
                            }
                        })
                .setNegativeButton("NO",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int which) {
                                dialog.cancel();
                            }
                        });
        AlertDialog Alert = Builder.create();
        Alert.show();
    } catch (SQLiteException Error) {
        Toast.makeText(ActivityContext, "Error (CategoryDelete) : " + Error.toString(), Toast.LENGTH_LONG).show();
    }
}

}

这是我的 DatabaseClass (TaskListDatabase.java)

package com.nano.tasklist;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class TaskListDatabase extends SQLiteOpenHelper{

private static final String DatabaseName = "TaskList";
private static final int DatabaseVersion = 1;
private static final String Category = "Category";
private static final String Tasks = "Tasks";

private static final String CreateCategoryTable = "CREATE TABLE " + Category + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, Category TEXT, AddDate TEXT, Completed TEXT);";
private static final String CreateTaskTable = "CREATE TABLE " + Tasks + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, Category TEXT, Task TEXT, AddDate TEXT, StartDate TEXT, FinishDate TEXT, Completed TEXT);";

public TaskListDatabase(Context Context){
    super(Context,DatabaseName,null,DatabaseVersion);
}

@Override
public void onCreate(SQLiteDatabase Database) {
    Database.execSQL(CreateCategoryTable);
    Database.execSQL(CreateTaskTable);
}

@Override
public void onUpgrade(SQLiteDatabase Database, int OldVersion, int NewVersion) {
    Database.execSQL("DROP TABLE IF EXISTS " + DatabaseName);
    onCreate(Database);
}
}

这是我的项目:https ://rapidshare.com/files/578334898/Task%20List.rar

请帮我...

4

4 回答 4

2

删除行后,调用

categoryAdapter.notifyDataSetChanged();

刷新listView的方法。

于 2012-10-29T08:39:10.057 回答
1

在删除按钮上:添加行:-

            adapter.notifyDataSetChanged();//or
            list.destroyDrawingCache();//both line
于 2012-10-29T08:41:44.637 回答
0
btnDeleteCategory.setOnClickListener(new OnClickListener(){
        public void onClick(View v) {
            TaskList Process = new TaskList();
            Process.Delete(btnDeleteCategory, Item.getID());
            this.CategoryAdapter.notifyDataSetChanged(); // refresh list view
        }
    });
于 2012-10-29T08:39:28.273 回答
0

您这样做是为了删除记录。

btnDeleteCategory.setOnClickListener(new OnClickListener(){
            public void onClick(View v) {
                TaskList Process = new TaskList();
                Process.Delete(btnDeleteCategory, Item.getID());
            }
        });

你的错误。

1)TaskList is your launcher Activity and I can't find any Delete() method in this class and call it in listener.
2)May be some code of query for delete in this method Delete()
3)You didn't refresh list using `categoryAdapter.notifyDataSetChanged();`

解决方案:

1)Make method for delete(delete query) in `TaskListDatabase.java`
2)You display data from `ArrayList<CategoryInfo> Items;` so You also remove that data from this ArrayList.
3)Use `categoryAdapter.notifyDataSetChanged();` for refresh list

试试这个代码...

btnDeleteCategory.setOnClickListener(new OnClickListener(){
            public void onClick(View v) {
                TaskListDatabase db = new TaskListDatabase();
                db.delete();
                Items.remove(position);
                notifyDataSetChanged();
            }
        });
于 2012-10-29T08:47:31.580 回答