· 8 years ago · Feb 16, 2018, 11:02 AM
1public class MainActivity extends AppCompatActivity {
2
3DBAdapter myDb;
4
5
6@Override
7protected void onCreate(Bundle savedInstanceState) {
8 super.onCreate(savedInstanceState);
9 setContentView(R.layout.activity_main);
10
11 openDB();
12 populateListView();
13 listViewItemLongClick();
14 listViewItemClick();
15}
16
17private void openDB(){
18 myDb = new DBAdapter(this);
19 myDb.open();
20}
21
22public void onClick_AddTast (View v) {
23 final AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this);
24 View mView = getLayoutInflater().inflate(R.layout.creategoaldialog_layout, null);
25 final EditText mSetProgbarVal = (EditText)mView.findViewById(R.id.progbarmaxvalue);
26 Button mAccept = (Button)mView.findViewById(R.id.accept);
27 Button mCancel = (Button)mView.findViewById(R.id.cancel);
28
29
30 mBuilder.setView(mView);
31
32
33 final AlertDialog dialog = mBuilder.create();
34 dialog.show();
35
36 mAccept.setOnClickListener(new View.OnClickListener() {
37 @Override
38 public void onClick(View v) {
39 if(!mSetProgbarVal.getText().toString().isEmpty()){
40 myDb.insertRow(mSetProgbarVal.getText().toString());
41 dialog.dismiss();
42 } else {
43 Toast.makeText(MainActivity.this,"Please fill in required fields", Toast.LENGTH_SHORT).show();
44
45 }
46 populateListView();
47 }
48 });
49
50
51 mCancel.setOnClickListener(new View.OnClickListener() {
52 @Override
53 public void onClick(View v) {
54 dialog.dismiss();
55 }
56 });
57
58}
59
60private void populateListView(){
61 Cursor cursor = myDb.getAllRows();
62 String[] fromFieldNames = new String[] {DBAdapter.KEY_ROWID,DBAdapter.KEY_AMT};
63 int[] toViewIDs = new int[]{R.id.goal_id,R.id.progbarprog};
64 SimpleCursorAdapter myCursorAdapter;
65 myCursorAdapter = new SimpleCursorAdapter(getBaseContext(),R.layout.item_layout, cursor, fromFieldNames, toViewIDs, 0);
66 myCursorAdapter.setViewBinder(new CustomViewBinder());
67 ListView myList = (ListView)findViewById(R.id.goalList);
68 myList.setAdapter(myCursorAdapter);
69}
70
71private class CustomViewBinder implements SimpleCursorAdapter.ViewBinder{
72 @Override
73 public boolean setViewValue(View view, Cursor cursor, int columnIndex){
74 if (view.getId()==R.id.progbar){
75 ProgressBar progress = (ProgressBar)view;
76 progress.setMax(cursor.getInt(cursor.getColumnIndex(String.valueOf(myDb.getRow(1)))));
77 return true;
78 }
79 return false;
80 }
81}
82
83
84private void populateProgView(){
85 Cursor cursor = myDb.getAllRows();
86 String[] fromFieldNames = new String[] {DBAdapter.KEY_PROG};
87 int[] toViewIDs = new int[]{R.id.progbarprog};
88 SimpleCursorAdapter myCursorAdapter;
89 myCursorAdapter = new SimpleCursorAdapter(this,R.layout.item_layout, cursor, fromFieldNames, toViewIDs, 0);
90 myCursorAdapter.setViewBinder(new CustomViewBinder2());
91 ListView myList = (ListView)findViewById(R.id.goalList);
92 myList.setAdapter(myCursorAdapter);
93}
94private class CustomViewBinder2 implements SimpleCursorAdapter.ViewBinder{
95 @Override
96 public boolean setViewValue(View view, Cursor cursor, int columnIndex){
97 if (view.getId()==R.id.progbar){
98 ProgressBar progress = (ProgressBar)view;
99 progress.setProgress(cursor.getInt(cursor.getColumnIndex(String.valueOf(myDb.getRow(2)))));
100 return true;
101 }
102 return false;
103 }
104}
105
106public void listViewItemClick(){
107 final ListView myList = (ListView)findViewById(R.id.goalList);
108 myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
109 @Override
110 public void onItemClick(AdapterView<?> parent, View view, int position, final long id) {
111 Context context = view.getContext();
112 final EditText goalAmt = new EditText(context);
113 goalAmt.setInputType(InputType.TYPE_CLASS_NUMBER);
114 AlertDialog dialog = new AlertDialog.Builder(MainActivity.this)
115 .setTitle("Set Amount")
116 .setView(goalAmt)
117 .setPositiveButton("Update", new DialogInterface.OnClickListener() {
118 @Override
119 public void onClick(DialogInterface dialog, int which) {
120 String goalValue = String.valueOf(goalAmt.getText().toString());
121 myDb.insertRow(goalValue);
122 populateProgView();
123 }
124 })
125 .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
126 @Override
127 public void onClick(DialogInterface dialog, int which) {
128 dialog.dismiss();
129 }
130 })
131 .create();
132 dialog.show();
133 }
134 });
135}
136
137public void onClickDeleteAllGoals(View v){
138 myDb.deleteAll();
139 populateListView();
140}
141
142private void listViewItemLongClick(){
143 ListView myList = (ListView)findViewById(R.id.goalList);
144 myList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
145 @Override
146 public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
147 myDb.deleteRow(id);
148 populateListView();
149
150 return false;
151 }
152 });
153 }
154}
155
156public class DBAdapter {
157
158private static final String TAG = "DBAdapter"; //used for logging database version
159
160//Field Names
161public static final String KEY_ROWID = "_id";
162public static final String KEY_AMT = "amt";
163public static final String KEY_PROG = "prog";
164
165public static final String[] ALL_KEYS = new String[]{KEY_ROWID, KEY_AMT};
166
167//Column Numbers for each field name;
168public static final int COL_ROWID = 0;
169public static final int COL_AMT = 1;
170public static final int COL_PROG = 2;
171
172//Database Info
173public static final String DATABASE_NAME = "dbGoals";
174public static final String DATABASE_TABLE = "tblGoals";
175public static final int DATABASE_VERSION = 1; //The Version number must be incremented
176
177//SQL Statement to create database
178private static final String DATABASE_CREATE_SQL = "CREATE TABLE " + DATABASE_TABLE + " (" +
179 KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
180 KEY_AMT + " INTEGER, " +
181 KEY_PROG + " INTEGER " +");";
182
183private final Context context;
184private DatabaseHelper myDBHelper;
185private SQLiteDatabase db;
186
187
188public DBAdapter(Context ctx){
189 this.context = ctx;
190 myDBHelper = new DatabaseHelper(context);
191}
192
193
194//Open the database connection
195public DBAdapter open(){
196 db = myDBHelper.getWritableDatabase();
197 return this;
198}
199
200//Close the database connection
201public void close(){
202 myDBHelper.close();
203}
204
205//Add a new set of values to be inserted into the database.
206public long insertRow(String amt){
207 ContentValues initialValues = new ContentValues();
208 initialValues.put(KEY_AMT, amt);
209
210 //Insert the data into the database
211 return db.insert(DATABASE_TABLE, null, initialValues);
212}
213
214public long insertProg(String prog){
215 ContentValues initialValues = new ContentValues();
216 initialValues.put(KEY_PROG, prog);
217
218 //Insert the data into the database
219 return db.insert(DATABASE_TABLE, null, initialValues);
220}
221
222
223//Delete a row from the database by rowId (primary key)
224public boolean deleteRow(long rowId){
225 String where = KEY_ROWID + "=" + rowId;
226 return db.delete(DATABASE_TABLE, where, null) != 0;
227}
228
229public void deleteAll(){
230 Cursor c = getAllRows();
231 long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
232 if (c.moveToFirst()){
233 do {
234 deleteRow(c.getLong((int) rowId));
235 } while (c.moveToNext());
236 }
237 c.close();
238}
239
240//Return all data to database
241public Cursor getAllRows(){
242 String where = null;
243 Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where,
244 null, null, null, null, null);
245 if (c != null){
246 c.moveToFirst();
247 }
248 return c;
249}
250
251//Get a specific row (by rowId)
252public Cursor getRow(long rowId){
253 String where = KEY_ROWID + "=" + rowId;
254 Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where,
255 null, null, null, null, null);
256 if (c != null){
257 c.moveToFirst();
258 }
259 return c;
260}
261
262private static class DatabaseHelper extends SQLiteOpenHelper {
263
264 DatabaseHelper(Context context){
265 super(context, DATABASE_NAME, null, DATABASE_VERSION);
266 }
267
268 @Override
269 public void onCreate(SQLiteDatabase _db){
270 _db.execSQL(DATABASE_CREATE_SQL);
271 }
272
273 @Override
274 public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion){
275 Log.w(TAG, "Upgrading application's database from new version " + oldVersion + " to " + newVersion +
276 ", which will destroy all old data!");
277
278 //Destroy old database:
279 _db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
280
281 //Recreate new database;
282 onCreate(_db);
283 }
284 }
285}
286
2872-16 18:50:05.562 7084-7084/com.example.eugene.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
288 Process: com.example.eugene.myapplication, PID: 7084
289 java.lang.IllegalArgumentException: column 'prog' does not exist
290 at android.database.AbstractCursor.getColumnIndexOrThrow(AbstractCursor.java:303)
291 at android.widget.SimpleCursorAdapter.findColumns(SimpleCursorAdapter.java:333)
292 at android.widget.SimpleCursorAdapter.<init>(SimpleCursorAdapter.java:107)
293 at com.example.eugene.myapplication.MainActivity.populateProgView(MainActivity.java:114)
294 at com.example.eugene.myapplication.MainActivity.access$300(MainActivity.java:25)
295 at com.example.eugene.myapplication.MainActivity$3$2.onClick(MainActivity.java:147)
296 at android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:162)
297 at android.os.Handler.dispatchMessage(Handler.java:102)
298 at android.os.Looper.loop(Looper.java:135)
299 at android.app.ActivityThread.main(ActivityThread.java:5221)
300 at java.lang.reflect.Method.invoke(Native Method)
301 at java.lang.reflect.Method.invoke(Method.java:372)
302 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
303 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)