I am creating an inventory app for a friend's crystal specimens in Kotlin. The intended logic is:
However, I am unsure how to store the image in Firebase RealTime DataBase. I have seen examples of this process in Java and it requires in the onActivityResult, data.data be converted to a bitmap before storing but I do not fully understand enough to convert this. I was hoping someone could explain the hows and whys of storing images from the camera and not from the camera into the firebase.
My code is below and I add some questions.
RockEnry.kt
package com.inven.rock_stock
import android.content.Intent
import android.graphics.Picture
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.core.Context
class RockEntry {
var name = ""
var purchDate = ""
var local = ""
var mine = ""
var weight = ""
var paid = ""
var asking = ""
var description = ""
var dimensions = ""
constructor(name:String,purchDate:String,local:String,mine:String,
weight:String,paid:String,asking:String,description:String,dimensions:String,){
this.name = name
this.purchDate = purchDate
this.local = local
this.mine = mine
this.weight = weight
this.paid = paid
this.asking = asking
this.description = description
this.dimensions = dimensions
how do I store picture in constructor?
MainActivity
package com.inven.rock_stock
import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.Intent
import android.os.Bundle
import android.provider.MediaStore
import androidx.appcompat.app.AppCompatActivity
import com.google.firebase.database.FirebaseDatabase
import kotlinx.android.synthetic.main.activity_main.*
var CAMERA_REQUEST_CODE = 0
var database = FirebaseDatabase.getInstance().reference
class MainActivity : AppCompatActivity() {
private val TAG = "MyActivity"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
button.setOnClickListener {
var name = name.text.toString()
var local = locality.text.toString()
var mine = mine.text.toString()
var weight = weight.text.toString()
var dimensions = dimensions.text.toString()
var paid = paid.text.toString()
var asking = asking.text.toString()
var description = description.text.toString()
database.child("Rocks").child(name.toLowerCase()).setValue(
RockEntry(
name,
local,
mine,
weight,
dimensions
paid,
asking,
description
)
)
}
imageBtn.setOnClickListener {
takePicture()
}
}
private fun takePicture() {
CAMERA_REQUEST_CODE = 222
val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
try {
startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE)
} catch (e: ActivityNotFoundException) {
// display error state to the user
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
CAMERA_REQUEST_CODE -> {
if (resultCode == Activity.RESULT_OK && data != null) {
println("What do I need to do to get picture into firebase?")
val singularity = data.data
}
}
}
}
}
I guess I am having some conceptual issues on:
I found some examples in Java here, (which I probably should have created this project in) but my conversion is pretty ugly at this point.
here's the doc i've been staring at photobasicsDoc, uploadDoc
My misconception was that FireBaseDatabase & FireBaseStorage were one in the same.
I most importantly configured some storage by using the firebase
tools in Android Studio (which also added the appropriate dependancies)
I declared private var mStorageRef: StorageReference? = null
& set it equal to mStorageRef = FirebaseStorage.getInstance().getReference("Images")
in my
onCreate.
the following is the code I was missing from my onActivityResult:
val imageBitmap = data.extras?.get("data") as Bitmap
val baos = ByteArrayOutputStream()
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos)
val datar = baos.toByteArray()
storageRef!!.putBytes(datar)
I still welcome input on the post, questions that still stand:
How should I link FireBaseDataBase & FireBaseStorage.
UPDATE: You can 'link' FireBaseDataBase & FireBaseStorage files through storing the location the file lives at in the database or getting a http download link to the file and storing it in the database.
storageRef.downloadUrl?.addOnSuccessListener {
downloadUri -> {
//do something with https download file link
var link = downloadUri.toString()
//which is different from
var databaseStoragelocation = storageref.toString()
}
}
How should you store picture in object.
UPDATE: You can create a constructor who takes a ByteArray or Uri as a parameter
how does the way a photo is returned from the library differ from
the way a photo is returned from the live camera?
UPDATE: basically takePicture and pickImageFromGallery() (below) both run under an Intent (code sample below). In the onActivityResult camera pictures will be presented as a bitmap and gallery pictures will be a Uri
// take picture from camera
private fun takePicture() {
CAMERA_REQUEST_CODE = 222
val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
try {
startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE)
} catch (e: ActivityNotFoundException) {
// display error state to the user
}
}
/* goes to gallery to select image */
private fun pickImageFromGallery() {
val intent = Intent()
intent.type = "image/*"
intent.action = Intent.ACTION_GET_CONTENT
startActivityForResult(intent, GALLERY_REQUEST_CODE)
}
/* checks to see if app had permission to access gallery, then calls pickImageFromGallery */
private fun checkPermissionForImage() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if ((checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED)
&& (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED)
) {
val permission = arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE)
val permissionCoarse = arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE)
val PERMISSION_CODE_READ = 0
requestPermissions(
permission,
PERMISSION_CODE_READ
) // GIVE AN INTEGER VALUE FOR PERMISSION_CODE_READ LIKE 1001
val PERMISSION_CODE_WRITE = 0
requestPermissions(
permissionCoarse,
PERMISSION_CODE_WRITE
) // GIVE AN INTEGER VALUE FOR PERMISSION_CODE_WRITE LIKE 1002
} else {
pickImageFromGallery()
}
}
}
/* on completion of pickImageFromGallery or takePicture this
function will store the image in the appropriate array to be
later uploaded */
override fun onActivityResult(requestCode: Int, resultCode: Int,
data: Intent?) {
val filePath: Uri?
/* reference to storagebase for photos */
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
CAMERA_REQUEST_CODE -> {
if (resultCode == Activity.RESULT_OK && data != null) {
val imageBitmap = data.extras?.get("data") as
Bitmap)
val baos = ByteArrayOutputStream()
imageBitmap.compress(Bitmap.CompressFormat.JPEG,
100, baos)
val datar = baos.toByteArray() // <- the picture is
ready to upload here
// adding photo bytearray to a array
campics.add(datar)
}
}
GALLERY_REQUEST_CODE -> {
if (resultCode == Activity.RESULT_OK && data != null) {
filePath = data.data
val imageBitmap =
MediaStore.Images.Media.getBitmap(contentResolver,
filePath)
// adding gallery pic Uri to array
filePath?.let { galpics.add(it) }
}
}
}
}