· 8 years ago · Aug 13, 2018, 09:14 PM
1inserting values into the db in android with a button click
2package com.istyle;
3
4import java.io.File;
5import java.io.IOException;
6
7import android.app.Activity;
8import android.content.ContentValues;
9import android.content.Intent;
10import android.database.Cursor;
11import android.database.SQLException;
12import android.database.sqlite.SQLiteDatabase;
13import android.database.sqlite.SQLiteException;
14import android.net.Uri;
15import android.os.Bundle;
16import android.provider.MediaStore;
17import android.util.Log;
18import android.view.View;
19import android.view.View.OnClickListener;
20import android.widget.Button;
21import android.widget.EditText;
22import android.widget.ImageView;
23import android.widget.Toast;
24
25public class Profile_Page extends Activity {
26 protected SQLiteDatabase sampleDB;
27 private static final String DATABASE_NAME = "istyle.sqlite";
28
29 private static final int SELECT_PICTURE = 1;
30 private String selectedImagePath;
31 private ImageView img;
32 String readName;
33 String readMail;
34 EditText Name;
35 EditText Email;
36 public void onCreate(Bundle savedInstanceState) {
37 super.onCreate(savedInstanceState);
38 setContentView(R.layout.profile_page);
39 Name=(EditText)findViewById(R.id.editText1);
40 Email=(EditText)findViewById(R.id.editText2);
41
42 final DataBaseHelper dbAdapter = DataBaseHelper.getInstance(this, DATABASE_NAME);
43 try {
44 if (getFirstRun()) {
45 sampleDB = dbAdapter.getDatabase();
46 setRunned();
47 } else {
48 sampleDB = dbAdapter.getWritableDatabase();
49 }
50
51 Cursor c1 = sampleDB.rawQuery("SELECT * FROM USER_PROFILE WHERE user_id='1'", null);
52
53 if (c1.moveToFirst()) {
54 do{
55
56 System.out.println(c1.getString(c1.getColumnIndex("user_id")));
57 System.out.println(c1.getString(c1.getColumnIndex("user_name")));
58 System.out.println(c1.getString(c1.getColumnIndex("user_email")));
59 } while (c1.moveToNext());
60 }
61 Button ok=(Button)findViewById(R.id.button1);
62 ok.setOnClickListener(new View.OnClickListener() {
63
64 @Override
65 public void onClick(View v) {
66 // TODO Auto-generated method stub
67 readName=Name.getText().toString();
68 readMail=Email.getText().toString();
69 String Query="UPDATE TABLE user_profile SET user_name="+readName+" user_email="+readMail+" WHERE user_id='1'";
70 sampleDB.execSQL(Query);
71 }
72 });
73
74 c1.close();
75 sampleDB.close();
76
77 }
78 catch (Exception e) {
79 // TODO Auto-generated catch block
80 e.printStackTrace();
81 }
82
83 img = (ImageView)findViewById(R.id.imageView1);
84 ((Button) findViewById(R.id.button3))
85 .setOnClickListener(new OnClickListener() {
86 public void onClick(View arg0) {
87 Intent intent = new Intent();
88 intent.setType("image/*");
89 intent.setAction(Intent.ACTION_GET_CONTENT);
90
91
92 startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE);
93
94 }
95 });
96
97 }
98
99private void setRunned() {
100 // TODO Auto-generated method stub
101
102 }
103
104private boolean getFirstRun() {
105 // TODO Auto-generated method stub
106 return false;
107 }
108
109public void onActivityResult(int requestCode, int resultCode, Intent data) {
110 if (resultCode == RESULT_OK) {
111 if (requestCode == SELECT_PICTURE) {
112 Uri selectedImageUri = data.getData();
113 selectedImagePath = getPath(selectedImageUri);
114 System.out.println("Image Path : " + selectedImagePath);
115 img.setImageURI(selectedImageUri);
116 }
117 }
118 }
119
120 public String getPath(Uri uri) {
121 String[] projection = { MediaStore.Images.Media.DATA };
122 Cursor cursor = managedQuery(uri, projection, null, null, null);
123 int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
124 cursor.moveToFirst();
125 return cursor.getString(column_index);
126 }
127
128}
129
130package com.istyle;
131import java.io.File;
132import java.io.FileOutputStream;
133import java.io.IOException;
134import java.io.InputStream;
135import java.io.OutputStream;
136
137import android.content.Context;
138import android.database.sqlite.SQLiteDatabase;
139import android.database.sqlite.SQLiteException;
140import android.database.sqlite.SQLiteOpenHelper;
141import android.database.sqlite.SQLiteDatabase.CursorFactory;
142import android.util.Log;
143
144// Modify by me 24/6/2010
145public class DataBaseHelper extends SQLiteOpenHelper {
146 private static SQLiteDatabase sqliteDb;
147 private static DataBaseHelper instance;
148 //private static final int DATABASE_VERSION = 1;
149 private static final int DATABASE_VERSION = 4;
150 // the default database path is :
151 // /data/data/pkgNameOfYourApplication/databases/
152 private static String DB_PATH_PREFIX = "/data/data/";
153 private static String DB_PATH_SUFFIX = "/databases/";
154 private static final String TAG = "DataBaseHelper";
155 private Context context;
156
157 /***
158 * Contructor
159 *
160 * @param context
161 * : app context
162 * @param name
163 * : database name
164 * @param factory
165 * : cursor Factory
166 * @param version
167 * : DB version
168 */
169 private DataBaseHelper(Context context, String name,
170 CursorFactory factory, int version) {
171 super(context, name, factory, version);
172 this.context = context;
173 Log.i(TAG, "Create or Open database : " + name);
174 }
175
176 /***
177 * Initialize method
178 *
179 * @param context
180 * : application context
181 * @param databaseName
182 * : database name
183 */
184 private static void initialize(Context context, String databaseName) {
185 if (instance == null) {
186 /**
187 * Try to check if there is an Original copy of DB in asset
188 * Directory
189 */
190 if (!checkDatabase(context, databaseName)) {
191 // if not exists, I try to copy from asset dir
192 try {
193 copyDataBase(context, databaseName);
194 } catch (IOException e) {
195 Log.e(TAG,"Database "+ databaseName + " does not exists and there is no Original Version in Asset dir");
196 }
197 }
198
199 Log.i(TAG, "Try to create instance of database (" + databaseName + ")");
200 instance = new DataBaseHelper(context, databaseName,
201 null, DATABASE_VERSION);
202 sqliteDb = instance.getWritableDatabase();
203 Log.i(TAG, "instance of database (" + databaseName + ") created !");
204 }
205 }
206
207 /***
208 * Static method for getting singleton instance
209 *
210 * @param context
211 * : application context
212 * @param databaseName
213 * : database name
214 * @return : singleton instance
215 */
216 public static final DataBaseHelper getInstance(
217 Context context, String databaseName) {
218 initialize(context, databaseName);
219 return instance;
220 }
221
222 /***
223 * Method to get database instance
224 *
225 * @return database instance
226 */
227 public SQLiteDatabase getDatabase() {
228 return sqliteDb;
229 }
230
231 @Override
232 public void onCreate(SQLiteDatabase db) {
233 Log.d(TAG, "onCreate : nothing to do");
234 }
235 @Override
236 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
237 Log.d(TAG, "onUpGrade : add column Cache_Id3 to table BUI_BUILDINGS in adcensusdb.sql. This is an upgrade");
238 }
239
240 /***
241 * Method for Copy the database from asset directory to application's data
242 * directory
243 *
244 * @param databaseName
245 * : database name
246 * @throws IOException
247 * : exception if file does not exists
248 */
249 private void copyDataBase(String databaseName) throws IOException {
250 copyDataBase(context, databaseName);
251 }
252
253 /***
254 * Static method for copy the database from asset directory to application's
255 * data directory
256 *
257 * @param aContext
258 * : application context
259 * @param databaseName
260 * : database name
261 * @throws IOException
262 * : exception if file does not exists
263 */
264 private static void copyDataBase(Context aContext, String databaseName)
265 throws IOException {
266
267 // Open your local db as the input stream
268 InputStream myInput = aContext.getAssets().open(databaseName);
269
270 // Path to the just created empty db
271 String outFileName = getDatabasePath(aContext, databaseName);
272
273 Log.i(TAG, "Check if create dir : " + DB_PATH_PREFIX
274 + aContext.getPackageName() + DB_PATH_SUFFIX);
275
276 // if the path doesn't exist first, create it
277 File f = new File(DB_PATH_PREFIX + aContext.getPackageName()
278 + DB_PATH_SUFFIX);
279 if (!f.exists())
280 f.mkdir();
281
282 Log.i(TAG, "Trying to copy local DB to : " + outFileName);
283
284 // Open the empty db as the output stream
285 OutputStream myOutput = new FileOutputStream(outFileName);
286
287 // transfer bytes from the inputfile to the outputfile
288 byte[] buffer = new byte[1024];
289 int length;
290 while ((length = myInput.read(buffer)) > 0) {
291 myOutput.write(buffer, 0, length);
292 }
293
294 // Close the streams
295 myOutput.flush();
296 myOutput.close();
297 myInput.close();
298
299 Log.i(TAG, "DB (" + databaseName + ") copied!");
300 }
301
302 /***
303 * Method to check if database exists in application's data directory
304 *
305 * @param databaseName
306 * : database name
307 * @return : boolean (true if exists)
308 */
309 public boolean checkDatabase(String databaseName) {
310 return checkDatabase(context, databaseName);
311 }
312
313 /***
314 * Static Method to check if database exists in application's data directory
315 *
316 * @param aContext
317 * : application context
318 * @param databaseName
319 * : database name
320 * @return : boolean (true if exists)
321 */
322 public static boolean checkDatabase(Context aContext, String databaseName) {
323 SQLiteDatabase checkDB = null;
324
325 try {
326 String myPath = getDatabasePath(aContext, databaseName);
327
328 Log.i(TAG, "Trying to conntect to : " + myPath);
329 checkDB = SQLiteDatabase.openDatabase(myPath, null,
330 SQLiteDatabase.OPEN_READONLY);
331 Log.i(TAG, "Database " + databaseName + " found!");
332 checkDB.close();
333 } catch (SQLiteException e) {
334 Log.i(TAG, "Database " + databaseName + " does not exists!");
335
336 }
337
338 return checkDB != null ? true : false;
339 }
340
341 /***
342 * Method that returns database path in the application's data directory
343 *
344 * @param databaseName
345 * : database name
346 * @return : complete path
347 */
348 private String getDatabasePath(String databaseName) {
349 return getDatabasePath(context, databaseName);
350 }
351
352 /***
353 * Static Method that returns database path in the application's data
354 * directory
355 *
356 * @param aContext
357 * : application context
358 * @param databaseName
359 * : database name
360 * @return : complete path
361 */
362 private static String getDatabasePath(Context aContext, String databaseName) {
363 return DB_PATH_PREFIX + aContext.getPackageName() + DB_PATH_SUFFIX
364 + databaseName;
365 }
366}
367
368final DataBaseHelper dbAdapter = DataBaseHelper.getInstance(this, DATABASE_NAME);
369 try {
370 sampleDB = dbAdapter.getWritableDatabase();
371 ...
372
373final DataBaseHelper dbAdapter = DataBaseHelper.getInstance(this, DATABASE_NAME);
374 try {
375 if (getFirstRun()) {
376 sampleDB = dbAdapter.getDatabase();
377 setRunned();
378 }
379 else {
380 sampleDB = dbAdapter.getWritableDatabase();
381 }
382 ...