· 8 years ago · Jul 27, 2018, 04:00 AM
1Deleting rows from a database issue
2public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
3 super.onCreateContextMenu(menu, v, menuInfo);
4 MenuInflater inflater = getMenuInflater();
5 inflater.inflate(R.menu.context_menu, menu);
6 }
7
8 public boolean onContextItemSelected(MenuItem item) {
9 //AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
10 //String[] names = getResources().getStringArray(R.array.names);
11 switch(item.getItemId())
12 {
13 case R.id.viewData:
14 { Intent r=new Intent(Database.this,MainMenu.class);
15 startActivity(r);
16 return true;
17 }
18
19 case R.id.DelData:
20 {
21
22 AdapterView.AdapterContextMenuInfo info1=
23 (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
24
25 delete(info1.id);
26 return true;
27
28 }
29 }
30 return(super.onOptionsItemSelected(item));
31
32 }
33 private void delete(final long rowId) {
34 if (rowId>0) {
35 new AlertDialog.Builder(this)
36 .setTitle(R.string.delete_title)
37 .setPositiveButton(R.string.ok,
38 new DialogInterface.OnClickListener() {
39 public void onClick(DialogInterface dialog,
40 int whichButton) {
41 processDelete(rowId);
42 }
43 })
44 .setNegativeButton(R.string.cancel,
45 new DialogInterface.OnClickListener() {
46 public void onClick(DialogInterface dialog,
47 int whichButton) {
48 // ignore, just dismiss
49 }
50 })
51 .show();
52 }
53 }
54
55 private void processDelete(long rowId) {
56 String[] args={String.valueOf(rowId)};
57
58 //DatabaseHelper dbh = new DatabaseHelper(this);
59 dbh.getWritableDatabase().delete("mygrades", "_ID=?", args);
60 c.requery();
61 }
62
6304-02 03:38:29.450: W/dalvikvm(541): threadid=1: thread exiting with uncaught exception (group=0x409c01f8)
6404-02 03:38:29.489: E/AndroidRuntime(541): FATAL EXCEPTION: main
6504-02 03:38:29.489: E/AndroidRuntime(541): java.lang.NullPointerException
6604-02 03:38:29.489: E/AndroidRuntime(541): at nidhin.survey.Database.processDelete(Database.java:139)
6704-02 03:38:29.489: E/AndroidRuntime(541): at nidhin.survey.Database.access$0(Database.java:135)
6804-02 03:38:29.489: E/AndroidRuntime(541): at nidhin.survey.Database$1.onClick(Database.java:121)
6904-02 03:38:29.489: E/AndroidRuntime(541): at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
7004-02 03:38:29.489: E/AndroidRuntime(541): at android.os.Handler.dispatchMessage(Handler.java:99)
7104-02 03:38:29.489: E/AndroidRuntime(541): at android.os.Looper.loop(Looper.java:137)
7204-02 03:38:29.489: E/AndroidRuntime(541): at android.app.ActivityThread.main(ActivityThread.java:4424)
7304-02 03:38:29.489: E/AndroidRuntime(541): at java.lang.reflect.Method.invokeNative(Native Method)
7404-02 03:38:29.489: E/AndroidRuntime(541): at java.lang.reflect.Method.invoke(Method.java:511)
7504-02 03:38:29.489: E/AndroidRuntime(541): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
7604-02 03:38:29.489: E/AndroidRuntime(541): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
7704-02 03:38:29.489: E/AndroidRuntime(541): at dalvik.system.NativeStart.main(Native Method)
7804-02 03:38:32.388: I/Process(541): Sending signal. PID: 541 SIG: 9
7904-02 03:39:09.788: D/dalvikvm(586): GC_FOR_ALLOC freed 66K, 4% free 9065K/9347K, paused 82ms
8004-02 03:39:09.788: I/dalvikvm-heap(586): Grow heap (frag case) to 9.452MB for 556016-byte allocation
8104-02 03:39:09.930: D/dalvikvm(586): GC_CONCURRENT freed <1K, 4% free 9607K/9927K, paused 5ms+5ms
8204-02 03:39:10.259: D/gralloc_goldfish(586): Emulator without GPU emulation detected.
83
84public class DatabaseHelper
85{
86
87 Context context;
88 private SQLiteDatabase db;
89 private final String DB_NAME = "database_name";
90 private final int DB_VERSION = 1;
91
92 private final String TABLE_NAME = "database_table";
93 private final String TABLE_ROW_ID = "id";
94 private final String TABLE_ROW_ONE = "table_row_one";
95 private final String TABLE_ROW_TWO = "table_row_two";
96
97 public DatabaseHelper(Context context)
98 {
99 this.context = context;
100
101 CustomSQLiteOpenHelper helper = new CustomSQLiteOpenHelper(context);
102 this.db = helper.getWritableDatabase();
103 }
104
105
106
107
108 /**********************************************************************
109 * ADDING A ROW TO THE DATABASE TABLE
110 *
111 * This is an example of how to add a row to a database table
112 * using this class. You should edit this method to suit your
113 * needs.
114 *
115 * the key is automatically assigned by the database
116 * @param rowStringOne the value for the row's first column
117 * @param rowStringTwo the value for the row's second column
118 */
119 public void addRow(String rowStringOne, String rowStringTwo)
120 {
121
122 ContentValues values = new ContentValues();
123 values.put(TABLE_ROW_ONE, rowStringOne);
124 values.put(TABLE_ROW_TWO, rowStringTwo);
125
126
127 try{db.insert(TABLE_NAME, null, values);}
128 catch(Exception e)
129 {
130 Log.e("DB ERROR", e.toString());
131 e.printStackTrace();
132 }
133 }
134
135
136
137 /**********************************************************************
138 * DELETING A ROW FROM THE DATABASE TABLE
139 *
140 * This is an example of how to delete a row from a database table
141 * using this class. In most cases, this method probably does
142 * not need to be rewritten.
143 *
144 * @param rowID the SQLite database identifier for the row to delete.
145 */
146 public void deleteRow(long rowID)
147 {
148 // ask the database manager to delete the row of given id
149 try {db.delete(TABLE_NAME, TABLE_ROW_ID + "=" + rowID, null);}
150 catch (Exception e)
151 {
152 Log.e("DB ERROR", e.toString());
153 e.printStackTrace();
154 }
155 }
156
157 /**********************************************************************
158 * UPDATING A ROW IN THE DATABASE TABLE
159 *
160 * This is an example of how to update a row in the database table
161 * using this class. You should edit this method to suit your needs.
162 *
163 * @param rowID the SQLite database identifier for the row to update.
164 * @param rowStringOne the new value for the row's first column
165 * @param rowStringTwo the new value for the row's second column
166 */
167 public void updateRow(long rowID, String rowStringOne, String rowStringTwo)
168 {
169
170 ContentValues values = new ContentValues();
171 values.put(TABLE_ROW_ONE, rowStringOne);
172 values.put(TABLE_ROW_TWO, rowStringTwo);
173
174 // ask the database object to update the database row of given rowID
175 try {db.update(TABLE_NAME, values, TABLE_ROW_ID + "=" + rowID, null);}
176 catch (Exception e)
177 {
178 Log.e("DB Error", e.toString());
179 e.printStackTrace();
180 }
181 }
182
183 /**********************************************************************
184 * RETRIEVING A ROW FROM THE DATABASE TABLE
185 *
186 * This is an example of how to retrieve a row from a database table
187 * using this class. You should edit this method to suit your needs.
188 *
189 * @param rowID the id of the row to retrieve
190 * @return an array containing the data from the row
191 */
192 public ArrayList<Object> getRowAsArray(long rowID)
193 {
194 // create an array list to store data from the database row.
195 // I would recommend creating a JavaBean compliant object
196 // to store this data instead. That way you can ensure
197 // data types are correct.
198 ArrayList<Object> rowArray = new ArrayList<Object>();
199 Cursor cursor;
200
201 try
202 {
203 // this is a database call that creates a "cursor" object.
204 // the cursor object store the information collected from the
205 // database and is used to iterate through the data.
206 cursor = db.query
207 (
208 TABLE_NAME,
209 new String[] { TABLE_ROW_ID, TABLE_ROW_ONE, TABLE_ROW_TWO },
210 TABLE_ROW_ID + "=" + rowID,
211 null, null, null, null, null
212 );
213
214 // move the pointer to position zero in the cursor.
215 cursor.moveToFirst();
216
217 // if there is data available after the cursor's pointer, add
218 // it to the ArrayList that will be returned by the method.
219 if (!cursor.isAfterLast())
220 {
221 do
222 {
223 rowArray.add(cursor.getLong(0));
224 rowArray.add(cursor.getString(1));
225 rowArray.add(cursor.getString(2));
226 }
227 while (cursor.moveToNext());
228 }
229
230 // let java know that you are through with the cursor.
231 cursor.close();
232 }
233 catch (SQLException e)
234 {
235 Log.e("DB ERROR", e.toString());
236 e.printStackTrace();
237 }
238
239 // return the ArrayList containing the given row from the database.
240 return rowArray;
241 }
242
243
244
245
246 /**********************************************************************
247 * RETRIEVING ALL ROWS FROM THE DATABASE TABLE
248 *
249 * This is an example of how to retrieve all data from a database
250 * table using this class. You should edit this method to suit your
251 * needs.
252 *
253 * the key is automatically assigned by the database
254 */
255
256 public ArrayList<ArrayList<Object>> getAllRowsAsArrays()
257 {
258 // create an ArrayList that will hold all of the data collected from
259 // the database.
260 ArrayList<ArrayList<Object>> dataArrays = new ArrayList<ArrayList<Object>>();
261
262 // this is a database call that creates a "cursor" object.
263 // the cursor object store the information collected from the
264 // database and is used to iterate through the data.
265 Cursor cursor;
266
267 try
268 {
269 // ask the database object to create the cursor.
270 cursor = db.query(
271 TABLE_NAME,
272 new String[]{TABLE_ROW_ID, TABLE_ROW_ONE, TABLE_ROW_TWO},
273 null, null, null, null, null
274 );
275
276 // move the cursor's pointer to position zero.
277 cursor.moveToFirst();
278
279 // if there is data after the current cursor position, add it
280 // to the ArrayList.
281 if (!cursor.isAfterLast())
282 {
283 do
284 {
285 ArrayList<Object> dataList = new ArrayList<Object>();
286
287 dataList.add(cursor.getLong(0));
288 dataList.add(cursor.getString(1));
289 dataList.add(cursor.getString(2));
290
291 dataArrays.add(dataList);
292 }
293 // move the cursor's pointer up one position.
294 while (cursor.moveToNext());
295 }
296 }
297 catch (SQLException e)
298 {
299 Log.e("DB Error", e.toString());
300 e.printStackTrace();
301 }
302
303 // return the ArrayList that holds the data collected from
304 // the database.
305 return dataArrays;
306 }
307
308
309
310
311 /**********************************************************************
312 * THIS IS THE BEGINNING OF THE INTERNAL SQLiteOpenHelper SUBCLASS.
313 *
314 * I MADE THIS CLASS INTERNAL SO I CAN COPY A SINGLE FILE TO NEW APPS
315 * AND MODIFYING IT - ACHIEVING DATABASE FUNCTIONALITY. ALSO, THIS WAY
316 * I DO NOT HAVE TO SHARE CONSTANTS BETWEEN TWO FILES AND CAN
317 * INSTEAD MAKE THEM PRIVATE AND/OR NON-STATIC. HOWEVER, I THINK THE
318 * INDUSTRY STANDARD IS TO KEEP THIS CLASS IN A SEPARATE FILE.
319 *********************************************************************/
320
321 /**
322 * This class is designed to check if there is a database that currently
323 * exists for the given program. If the database does not exist, it creates
324 * one. After the class ensures that the database exists, this class
325 * will open the database for use. Most of this functionality will be
326 * handled by the SQLiteOpenHelper parent class. The purpose of extending
327 * this class is to tell the class how to create (or update) the database.
328 *
329 * @author Randall Mitchell
330 *
331 */
332 private class CustomSQLiteOpenHelper extends SQLiteOpenHelper
333 {
334 public CustomSQLiteOpenHelper(Context context)
335 {
336 super(context, DB_NAME, null, DB_VERSION);
337 }
338
339 @Override
340 public void onCreate(SQLiteDatabase db)
341 {
342 // This string is used to create the database. It should
343 // be changed to suit your needs.
344 String newTableQueryString = "create table " +
345 TABLE_NAME +
346 " (" +
347 TABLE_ROW_ID + " integer primary key autoincrement not null," +
348 TABLE_ROW_ONE + " text," +
349 TABLE_ROW_TWO + " text" +
350 ");";
351 // execute the query string to the database.
352 db.execSQL(newTableQueryString);
353 }
354
355
356 @Override
357 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
358 {
359 // NOTHING TO DO HERE. THIS IS THE ORIGINAL DATABASE VERSION.
360 // OTHERWISE, YOU WOULD SPECIFIY HOW TO UPGRADE THE DATABASE.
361 }
362 }
363}