ListView在我第一次使用它来显示来自SQLite数据库的数据时表现得很奇怪

时间:2016-06-19 16:14:55

标签: android sqlite listview android-fragments

我正在制作一个FragmentActivity,它使用viewPager显示三个片段和两个来自SQLite数据库的访问数据。

我关注的片段是ContactList模块,它只显示数据库myDatabase3中表mainTable的两个字段。

现在,我通过长按和项目时出现的AlertDialog添加了编辑和删除功能。问题出在哪里,是删除部分。我之前遇到的问题是,一旦我从数据库中删除了一条记录,ListView就没有更新。我尝试了以下方法,但它没有用。

 dataAdapter.notifyDataSetChanged();
 listView.invalidateViews();

所以我决定通过另一个确认删除操作的AlertDialog以及当用户点击是时删除记录并重新启动当前的FragmentActivity来解决方法,从而刷新列表(当然我必须更改onBackPressed方法) FragmentActivity.java用于启动主要活动,但也是如此。一切顺利,但只是第一次。第二次在调试模式下启动应用程序时,ListView会在上一次会话结束时打开数据集,然后当我尝试删除记录时,记录不会从列表中消失!当然没有异常,并且该行从数据库中删除,但它会弄乱索引,因为我可以从ContactAdd.java模块添加新记录,它们也会出现在列表中,但是由于存在未删除的行索引都搞砸了,导致运行时异常。我尝试了4个不同的数据库名称,每次,我第一次使用数据库时一切正常,但在后续发布时,问题再次发生。 这是相关的代码:

ContactList.java

public class ContactList extends Fragment{
    private SimpleCursorAdapter dataAdapter;
    private ContactsAdapter dbHelper;
    private ListView listView;
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        ViewGroup rootView = (ViewGroup) inflater.inflate(
                R.layout.fragment_item_list, container, false);
        dbHelper = new ContactsAdapter(this.getActivity());
        dbHelper.open();
        Cursor cursor = dbHelper.getAllFriends();
        String[] columns = new String[] {
                ContactsAdapter.KEY_NAME, ContactsAdapter.KEY_Phone
        };
        int[] to = new int[] {
                R.id.name, R.id.phonenumber
        };
        dataAdapter = new SimpleCursorAdapter(
                this.getActivity(), R.layout.contact_row,
                cursor,
                columns,
                to,
                0);
        listView = (ListView) rootView.findViewById(R.id.list);
        listView.setAdapter(dataAdapter);
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.setTitle("Pick an action");
                builder.setItems(new String[]{"Edit", "Delete", "Activate Call Forwarding"}, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        if (which == 0) {
                            Intent i = new Intent(getActivity(), ContactEdit.class);
                            i.putExtra("RowID", position);
                            startActivity(i);
                        } else if (which == 1) {
                            AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
                            alertDialogBuilder.setMessage("Are you sure you want to delete the record?");

                            alertDialogBuilder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface arg0, int arg1) {

                                    dbHelper.removeFriend(position);
                                    dataAdapter.notifyDataSetChanged();
                                    listView.invalidateViews();
                                    /*Intent i = new Intent(getActivity(), FirstSplashScreen.class);
                                    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                    startActivity(i);*/
                                }
                            });


                            alertDialogBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Toast.makeText(getActivity(), "You clicked no button", Toast.LENGTH_LONG).show();
                                }
                            });
                            AlertDialog alertDialog = alertDialogBuilder.create();
                            alertDialog.show();

                        }

                    }
                });
                AlertDialog alertDialog = builder.create();
                alertDialog.show();
                return true;
            }
        });

        return rootView;
    }
}

ContactsAdapter.java

public class ContactsAdapter {
    private static final String DATABASE_NAME ="myDatabase4.db";
    private static final String DATABASE_TABLE ="mainTable1";
    private static final int DATABASE_VERSION = 1;

    public static final String KEY_ID="_id";
    public static final String KEY_NAME="name";
    public static final int NAME_COLUMN = 1;


    public static final String KEY_Phone="mobile";
    public static final int Mobile_COLUMN = 2;


    public static final String KEY_Home="home";
    public static final int Home_COLUMN = 3;


    public static final String KEY_Address="address";
    public static final int Address_COLUMN = 4;

     private SQLiteDatabase db;

    private final Context context;

    private MyDatabaseHelper dbHelper;
    public ContactsAdapter(Context _context){
        context = _context;
        dbHelper = new MyDatabaseHelper(context, DATABASE_NAME, null,DATABASE_VERSION);
    }
    public ContactsAdapter open() throws SQLException {
        try {
            db = dbHelper.getWritableDatabase();
        }
        catch(SQLException ex){
            db=dbHelper.getReadableDatabase();
        }
        return this;
    }
    public void close() {
        db.close();
    }
    public void addFriend(String name, String address, String mobile, String home)

    {

        ContentValues values=new ContentValues(4);

        values.put("name", name);
        values.put("address", address);
        values.put("mobile", mobile);
        values.put("home", home);

        db.insert(DATABASE_TABLE, null, values);

    }
    public Cursor getFriend(int id) throws SQLException
    {id+=1;
        Cursor res = db.query(true, DATABASE_TABLE,
                new String[] {KEY_ID, KEY_NAME, KEY_Address,KEY_Phone,KEY_Home},
                KEY_ID + "=" + id, null, null, null,
            null, null);
        if ((res.getCount() == 0) || !res.moveToFirst()) {
            throw new SQLException("No item found for row: " +
                    id);
        }
        return res;
    }
    public Cursor getAllFriends() {
        Cursor res = db.query(DATABASE_TABLE, new String[] {KEY_ID, KEY_NAME, KEY_Address,KEY_Phone,KEY_Home}, null, null, null, null, null);
       if(res!=null){
           res.moveToFirst();
       }

        return res;
    }
    public boolean removeFriend(long _rowIndex) {
         _rowIndex+=1;
        return db.delete(DATABASE_TABLE, KEY_ID + "=" + _rowIndex, null) > 0;
    }
}

MyDatabaseHelper

public class MyDatabaseHelper extends SQLiteOpenHelper {
    private static final String DATABASE_TABLE ="mainTable1";
    public static final String KEY_ID="_id";
    public static final String KEY_NAME="name";
    public static final int NAME_COLUMN = 1;


    public static final String KEY_Phone="mobile";
    public static final int Mobile_COLUMN = 2;


    public static final String KEY_Home="home";
    public static final int Home_COLUMN = 3;


    public static final String KEY_Address="address";
    public static final int Address_COLUMN = 4;

    private static final String DATABASE_CREATE = "create table " +
            DATABASE_TABLE + " (" + KEY_ID +" integer primary key autoincrement, " +KEY_NAME + " text not null,"+KEY_Address+" text ,"+KEY_Phone+" text not null,"+KEY_Home+" text);";


    public MyDatabaseHelper(Context context, String name,
                            SQLiteDatabase.CursorFactory factory, int version) {

        super(context, name, factory, version);

    }



    @Override
    public void onCreate(SQLiteDatabase database) {

        database.execSQL(DATABASE_CREATE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS "+DATABASE_TABLE+";");

        onCreate(db);
    }
}

请在这里帮忙。

1 个答案:

答案 0 :(得分:0)

我认为问题是removeFriend方法,因为你正在删除带有(_rowIndex + = 1)行的索引,这可能是不正确的,这就是为什么你得到错误并且列表没有正确地重新加载;您可以使用光标获取KEY_ID并尝试使用KEY_ID删除行:并提出一些建议为了更好地优化代码,您可以使用BaseAdapter和POJO类。