0

As question title says, can anyone help me how to upload any type of files to the database in android

I have tried this for uploading images..

//where we want to download it from

URL url = new URL(IMAGE_URL);  //http://example.com/image.jpg
//open the connection
URLConnection ucon = url.openConnection();
//buffer the download
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is,128);
ByteArrayBuffer baf = new ByteArrayBuffer(128);
//get the bytes one by one
int current = 0;
while ((current = bis.read()) != -1) {
        baf.append((byte) current);
}

//store the data as a ByteArray
//db is a SQLiteDatabase object
ContentValues dataToInsert = new ContentValues();                          
dataToInsert.put(TABLE_FIELD,baf.toByteArray());
db.insert(TABLE_NAME, null, dataToInsert);
And this is how you get the data back and convert it into a Bitmap:

//select the data
Cursor cursor = db.query(TABLE_STATIONLIST, new String[] {TABLE_FIELD},
                                                null, null, null, null, null);
//get it as a ByteArray
byte[] imageByteArray=cursor.getBlob(1);
//the cursor is not needed anymore
cursor.close();

//convert it back to an image
ByteArrayInputStream imageStream = new ByteArrayInputStream(mybyte);
Bitmap theImage = BitmapFactory.decodeStream(imageStream));
gauravsheohar
  • 396
  • 5
  • 12
Anushyah
  • 1
  • 1

2 Answers2

1

Android has a private directory that you can use to store data (like images) and other apps cannot see. It is secure and compliant with the new Android 6 permission system (you don't need to ask for write_storage permission).

In my opinion, saving images inside a sqlite is not a good practise in Android, due to you have a private directory for your app (where you save the sqlite...) and it is more easy to get/save data.

In this post Saving and Reading Bitmaps/Images from Internal memory in Android you can see how to do it.

Community
  • 1
  • 1
Neonamu
  • 736
  • 1
  • 7
  • 21
0

It is an bad practice to store file on Android because Android has limited storage.If you want download image just download it from image URL from server.When file is uploaded on server then generates one unique URL use that if you want to download it.

Mahesh Giri
  • 1,810
  • 19
  • 27