vendredi 24 juin 2016

ListView behaving weirdly after the first time I use it to display data from an SQLite Database

I am making a FragmentActivity that uses the viewPager to display three Fragments and two of those access data from SQLite databases. The Fragment of my concern is the ContactList module which simply displays two fields from the table mainTable in the database myDatabase3. Now, I have added the functionality of edit and delete via an AlertDialog that appears when you long press and item. Where the problem is, is the delete part. What I was facing earlier was the problem that the ListView wasn't updating as soon as I deleted a record from the database. I tried the following ways but it didn't work. dataAdapter.notifyDataSetChanged(); listView.invalidateViews(); So I decided on a workaround by putting another AlertDialog that confirms the delete action and when the user taps yes, deletes the record and relaunches the current FragmentActivity, thus refreshing the list (of course I had to change the onBackPressed method in the FragmentActivity.java to launch the main activity but that worked out as well). All goes well, but only for the first time. The second time I launch the app in debug mode, the ListView opens with the dataset at the time of previous session's closing, and then when I try to delete the record, the record doesn't disappear from the list! Of course there is no exception and the row is deleted from the database, but it messes up the indices, because I can add new records from the ContactAdd.java module and they do appear in the list as well, but because of the presence of the undeleted rows the indices are all messed up and result in Runtime exceptions. I have tried this with 4 different database names, and each time, the first time I use the database everything works fine, but on subsequent launches, the problem reoccurs. here is the relevant code: 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); } } Please help out a bro here.

Aucun commentaire:

Enregistrer un commentaire