Android-如何在数据库中添加/删除项目后动态刷新ListView [英] Android - How to refresh dynamically listview after adding/deleting items from database

查看:82
本文介绍了Android-如何在数据库中添加/删除项目后动态刷新ListView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Android新手.我在此处中描述了相同的问题...我正在尝试在Android应用程序中管理一个简单列表.列表的内容在SQLite数据库中维护.当用户选择并按住特定行时,将显示一个带有打开/删除"选项的上下文菜单.当他们选择删除"时,该行将从数据库中删除,但视图不会刷新.当我退出应用程序并返回时,相应的行已被删除.因此,我知道该行已删除,只是ListView不会刷新.将新项目添加到数据库中也是如此.我搜索了解决方案,但尚未找到.感谢任何帮助.

I'm new in Android. I have the same problem as described here...I am trying to manage a simple list in an Android application. The contents of the list are maintained in a SQLite database. When the user selects and holds on a specific row, a context menu appears with a "Open/Delete" option. When they select "Delete", the row is deleted from the database, but the view does not refresh. When I back out of the application and get back in, the appropriate row has been removed. So, I know the row is deleted, it's just the ListView that doesn't refresh. The same with adding new item to the database. I searched solution, but not yet find. Appreciate any help.

活动分类:

 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;
}

推荐答案

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

on delete action fetch the data once again and then again call adapter.notifyDataSetChanged it will work

这篇关于Android-如何在数据库中添加/删除项目后动态刷新ListView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆