Android - 如何在添加/删除数据库中的项目后动态刷新listview

时间:2014-04-14 08:13:06

标签: android listview

我是Android的新手。我遇到了与here所述相同的问题...我正在尝试管理Android应用程序中的简单列表。列表的内容保存在SQLite数据库中。当用户选择并保留特定行时,将出现带有“打开/删除”选项的上下文菜单。当他们选择“删除”时,该行将从数据库中删除,但视图不会刷新。当我退出应用程序并重新进入时,相应的行已被删除。所以,我知道该行被删除,它只是ListView不刷新。将新项添加到数据库也是如此。我搜索了解决方案,但还没找到。感谢任何帮助。

活动类:

 public class ProjectsActivity extends Activity {

private RMProject rmProject = null;
private RMProjectDBHelper projectDBHelper = null;
ArrayAdapter<String> adapter;

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

    rmProject = new RMProject();
    projectDBHelper = new RMProjectDBHelper(this);

    final ListView lv = (ListView) findViewById(R.id.list);

    adapter = new ArrayAdapter<>(this, R.layout.list_item, getProjectNames());
    adapter.notifyDataSetChanged();
    lv.setAdapter(adapter);

    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
            AlertDialog.Builder  builder = new AlertDialog.Builder(ProjectsActivity.this);
            builder.setTitle("What to do with project?");
            builder.setPositiveButton("Open", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                    Intent intent = new Intent(ProjectsActivity.this, OpenProjectActivity.class);
                    //todo: send project information as parameter
                    startActivity(intent);
                }
            });
            //**!!!Here I delete project item from database!!!**
            builder.setNegativeButton("Delete", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    String selected = ((TextView) view.findViewById(R.id.list_textView)).getText().toString();
                    int projId = projectDBHelper.findIdByName(selected);
                    projectDBHelper.deleteProject(projId);
                    Toast toast=Toast.makeText(getApplicationContext(), "Project "+selected+" deleted", Toast.LENGTH_SHORT);
                    toast.show();
                    //**call getProjectNames and notifydataSetChanged**
                    getProjectNames();
                    adapter.notifyDataSetChanged();
                }
            });
            builder.show();
        }
    });

}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {


    if (item.getItemId() == R.id.menu_item) {
        final Dialog dialog = new Dialog(ProjectsActivity.this);
        dialog.setContentView(R.layout.add_proj);
        dialog.setTitle("Введите название проекта:");
        dialog.setCancelable(false);

        Button okBtn = (Button) dialog.findViewById(R.id.btn_create_proj);
        Button cancelBtn = (Button) dialog.findViewById(R.id.btn_cancel_proj);

        okBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EditText editProjName = (EditText) dialog.findViewById(R.id.edit_proj_name);
                String projName = editProjName.getText().toString();
                if (rmProject == null) {
                    rmProject = new RMProject();
                }
                rmProject.setName(projName);
                if (projectDBHelper == null) {
                    projectDBHelper = new RMProjectDBHelper(ProjectsActivity.this);
                }
                projectDBHelper.addProject(rmProject);
                dialog.dismiss();
            }
        });

        cancelBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        dialog.show();
        return true;
    }
    return super.onOptionsItemSelected(item);
}

private String[] getProjectNames() {
    LinkedList<RMProject> projects = (LinkedList<RMProject>) projectDBHelper.getAllProjects();
    String[] names = new String[projects.size()];
    int i = 0;
    for (RMProject p : projects) {
        names[i++] = p.getName();
    }
    return names;
}
}

使用自定义DbHelper类的片段:

public class RMProjectDBHelper extends SQLiteOpenHelper {

private static final String DB_NAME = "RM_DB";
private static final String TABLE_PROJECT = "PROJECT";
private static final String[] COLUMNS = {"id_project", "project_name"};
private static final int DB_VERSION = 1;
public RMProjectDBHelper(Context context) {
    super(context, DB_NAME, null, DB_VERSION);
}
//.....some code...
public void deleteProject(int id){
    SQLiteDatabase db = this.getWritableDatabase();
    db.delete(TABLE_PROJECT, "id_project = ?", new String[]{String.valueOf(id)});
    db.close();
    Log.d("deleteProject with id: ", Integer.toString(id));
}
public int findIdByName(String name){
    SQLiteDatabase db = this.getReadableDatabase();
    String selectQuery = "SELECT PROJECT.id_project FROM PROJECT WHERE PROJECT.project_name = '"+name+"'";
    Cursor cursor = db.rawQuery(selectQuery,null);
    int id=-1;
    while (cursor.moveToNext()){
        id = cursor.getInt(cursor.getColumnIndex("id_project"));
        Log.i("LOGGING:"," FIND ID BY NAME: ID="+id);
    }
    return id;
}

1 个答案:

答案 0 :(得分:3)

关于删除操作再次获取数据然后再次调用adapter.notifyDataSetChanged它将起作用