What is Error reading Sqlite database: Database 'LiveSqliteDatabaseId>? - android

Sorry for including this long code. I try to learn from the tutorial on youtube but the video tutorial lacks an explanation.Tutorial video use java, but i try to implement it for my kotlin app. but when i try to take a picture, i get this error:
Error reading Sqlite database: Database 'LiveSqliteDatabaseId(path=/data/data/com.example.b1/databases/google_app_measurement_local.db,name=google_app_measurement_local.db, connectionId=1) not found
Why i get this error? What is wrong with my code?
I also make TextView that can be clicked to sellect category but is doesn't work. it seems the categoryDialog() function in my code has a problem. Is this what causes the error above?
My code:
class AddProductActivity : AppCompatActivity() {
private val CAMERA_REQUEST_CODE:Int =200
private val STORAGE_REQUEST_CODE:Int =300
private val IMAGE_PICK_GALLERY_CODE:Int =400
private val IMAGE_PICK_CAMERA_CODE:Int =500
lateinit var cameraPermission: Array<String>
lateinit var storagePermission: Array<String>
lateinit var image_Uri:Uri
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_add_product)
cameraPermission= arrayOf(android.Manifest.permission.CAMERA, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
storagePermission= arrayOf(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
item_image.setOnClickListener{
showImagePickDialog()
}
tv_kategori.setOnClickListener{
categoryDialog()
}
tambahkan_barang.setOnClickListener{
inputData()
}
}
private lateinit var kategori: String
private lateinit var berat_sampah: String
private lateinit var deskripsi: String
private fun inputData(){
kategori=tv_kategori.text.toString().trim({it<=' '})
berat_sampah=et_berat_sampah.text.toString().trim({it<=' '})
deskripsi=et_deskripsi.toString().trim({it<=' '})
if(TextUtils.isEmpty(kategori)){
Toast.makeText(
this#AddProductActivity,
"Harap memilih kategori",
Toast.LENGTH_SHORT)
.show()
return
}
if(TextUtils.isEmpty(berat_sampah)){
Toast.makeText(
this#AddProductActivity,
"Harap mengisi berat sampah",
Toast.LENGTH_SHORT)
.show()
return
}
if(TextUtils.isEmpty(deskripsi)){
Toast.makeText(
this#AddProductActivity,
"Harap mengisi deskripsi singkat",
Toast.LENGTH_SHORT)
.show()
return
}
addProduct()
}
private fun addProduct(){
val timeStamp:String=""+System.currentTimeMillis()
if(image_Uri==null){
val hashMap:HashMap<String,String> = HashMap<String,String>()
hashMap.put("productId",timeStamp)
hashMap.put("productCategory",kategori)
hashMap.put("productWeight",berat_sampah)
hashMap.put("productDescription",deskripsi)
hashMap.put("productIcon","")
//hashMap.put("uid",""+firebaseAuth.uid)
}
}
private fun categoryDialog(){
val builder= AlertDialog.Builder(this)
builder.setTitle("Kategori Sampah").setItems(Constants.KATEGORI_BARANG){dialog,which ->{
val category= Constants.KATEGORI_BARANG[which]
tv_kategori.setText(category)
}}.show()
}
private fun showImagePickDialog(){
val options: Array<String> = arrayOf("Kamera","Gallery")
val builder= AlertDialog.Builder(this)
builder.setTitle("Pilih Gambar").setItems(options) { dialog, which ->
// put your logic in here
if(which==0){
if(checkCameraPermission()){
pickFromCamera()
}
else{
requestCameraPermission()
}
}
else{
if(checkStoragePermission()){
pickFromGallery()
}
else{
requestStoragePermission()
}
}
}.show()
}
private fun pickFromGallery(){
val intent= Intent(Intent.ACTION_PICK)
intent.setType("image/*")
startActivityForResult(intent,IMAGE_PICK_GALLERY_CODE)
}
private fun pickFromCamera(){
val contentValues= ContentValues()
contentValues.put(MediaStore.Images.Media.TITLE,"Temp_Image_Title")
contentValues.put(MediaStore.Images.Media.DESCRIPTION,"Temp_Image_Description")
image_Uri= contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)!!
intent= Intent(MediaStore.ACTION_IMAGE_CAPTURE)
intent.putExtra(MediaStore.EXTRA_OUTPUT,image_Uri)
startActivityForResult(intent, IMAGE_PICK_CAMERA_CODE)
}
private fun checkStoragePermission(): Boolean{
val result :Boolean=ContextCompat.checkSelfPermission(this#AddProductActivity, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)==(PackageManager.PERMISSION_GRANTED)
return result
}
private fun requestStoragePermission(){
ActivityCompat.requestPermissions(this,storagePermission,STORAGE_REQUEST_CODE)
}
private fun checkCameraPermission(): Boolean{
val result :Boolean=ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA)==(PackageManager.PERMISSION_GRANTED)
val result1 :Boolean=ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)==(PackageManager.PERMISSION_GRANTED)
return result && result1
}
private fun requestCameraPermission(){
ActivityCompat.requestPermissions(this,cameraPermission,STORAGE_REQUEST_CODE)
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
when (requestCode){
CAMERA_REQUEST_CODE->{
if(grantResults.size>0){
val cameraAccepted:Boolean=grantResults[0]==PackageManager.PERMISSION_GRANTED
val storageAccepted:Boolean=grantResults[1]==PackageManager.PERMISSION_GRANTED
if(cameraAccepted && storageAccepted){
pickFromCamera()
}
else{
Toast.makeText(
this#AddProductActivity,
"Akses Kamera dan Penyimpanan dibutuhkan",
Toast.LENGTH_SHORT)
.show()
}
}
}
STORAGE_REQUEST_CODE->{
if(grantResults.size>0){
val storageAccepted:Boolean=grantResults[0]==PackageManager.PERMISSION_GRANTED
if(storageAccepted){
pickFromGallery()
}
else{
Toast.makeText(
this#AddProductActivity,
"Akses Penyimpanan dibutuhkan",
Toast.LENGTH_SHORT)
.show()
}
}
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if(resultCode== RESULT_OK){
if(requestCode == IMAGE_PICK_GALLERY_CODE){
//img pick from gallery
//save picked img
image_Uri= data!!.getData()!!
//set IMG
item_image.setImageURI(image_Uri)
}
else if(requestCode==IMAGE_PICK_CAMERA_CODE){
item_image.setImageURI(image_Uri)
}
}
super.onActivityResult(requestCode, resultCode, data)
}
}

Turns out the problem was with the lamda. I'm following a tutorial with java language and when i try with kotlin i fail to manage the changes. I change my categoryDialog() function to:
private fun categoryDialog(){
val builder= AlertDialog.Builder(this)
builder.setTitle("Kategori Sampah").setItems(Constants.KATEGORI_BARANG){dialog,which ->
val category= Constants.KATEGORI_BARANG[which]
tv_kategori.setText(category)
}.show()
}

Related

Kotlin - com.miui.gallery.provider.GalleryOpenProvider Error

basically i have a fragment and in this fragment user can pick a image or use camera to take photo and i am taking the photo as uri and save to the local DB as string . And show the photo in this fragment.
This code works fine until i destroy my app in my xiaomi device. After i try to reach the uri from db and show in the fragment, app crashes. Btw this is not happening in emulator, everything is fine. I read some blogs and this could be happen in Mi devices but did not find a solution. The code;
class ProfilePageFragment : Fragment() {
private var _binding : FragmentProfilePageBinding? = null
private val binding get() = _binding!!
private lateinit var routineTasksViewModel: RoutineTasksViewModel
private var userName : String? = null
private var userProfilePhotoUri : String? = null
private lateinit var cameraPermissions : Array<String>
private lateinit var storagePermissions : Array<String>
private var imageUri : Uri? = null
private companion object {
private const val CAMERA_REQUEST_CODE = 100
private const val STORAGE_REQUEST_CODE = 101
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentProfilePageBinding.inflate(layoutInflater,container,false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
routineTasksViewModel = (activity as MainActivity).routineTasksViewModel
cameraPermissions = arrayOf(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)
storagePermissions = arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE)
getUserProfileInformations()
binding.apply {
profilePhotoIV.setOnClickListener{
showInputImageDialog()
}
}
}
//popUp menu and item click funcs
private fun showInputImageDialog() {
val popUpMenu = PopupMenu(requireContext(),binding.profilePhotoIV)
popUpMenu.menu.add(Menu.NONE,1,1, R.string.camera)
popUpMenu.menu.add(Menu.NONE,2,2, R.string.gallery)
popUpMenu.show()
popUpMenu.setOnMenuItemClickListener { menuItem ->
val id = menuItem.itemId
if (id ==1){
if (checkCameraPermission()){
pickImageCamera()
}else{
requestCameraPermission()
}
}else if(id == 2){
if (checkStoragePermission()){
pickImageGallery()
}else{
requestStoragePermission()
}
}
return#setOnMenuItemClickListener true
}
}
//two funcs check the permissions
private fun checkStoragePermission() : Boolean { //permissionGranted -> true
return ContextCompat.checkSelfPermission(requireContext(),
Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
}
private fun checkCameraPermission() : Boolean{ //permissionGranted -> true
val cameraResult = ContextCompat.checkSelfPermission(requireContext(),
Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
val storageResult = ContextCompat.checkSelfPermission(requireContext(),
Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
return cameraResult && storageResult
}
//
private fun pickImageGallery(){
val intent = Intent(Intent.ACTION_PICK)
intent.type = "image/*"
galleryActivityResultLauncher.launch(intent)
}
private fun pickImageCamera(){
val values = ContentValues()
values.put(MediaStore.Images.Media.TITLE, "Sample Title")
values.put(MediaStore.Images.Media.DESCRIPTION, "Sample Description")
imageUri = activity?.contentResolver?.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri)
cameraActivityResultLauncher.launch(intent)
}
//launcher to camera
private val cameraActivityResultLauncher =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()){ result ->
if ( result.resultCode == Activity.RESULT_OK){
//image came from camera
binding.profilePhotoIV.setImageURI(imageUri)
updateProfilePhotoToDB(imageUri)
}else{
//Toast.makeText(requireContext(), R.string.permissions_required, Toast.LENGTH_SHORT).show()
}
}
//launcher to gallery
private val galleryActivityResultLauncher =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()){ result ->
if ( result.resultCode == Activity.RESULT_OK){
val data = result.data
imageUri = data!!.data
binding.profilePhotoIV.setImageURI(imageUri)
updateProfilePhotoToDB(imageUri)
}else{
//Toast.makeText(requireContext(), R.string.permissions_required, Toast.LENGTH_SHORT).show()
}
}
private fun requestStoragePermission() {
ActivityCompat.requestPermissions(requireActivity(),storagePermissions, STORAGE_REQUEST_CODE)
}
private fun requestCameraPermission() {
ActivityCompat.requestPermissions(requireActivity(),cameraPermissions, CAMERA_REQUEST_CODE)
}
//when we request to take permission, according to request code pickImageCamera or pickImageGallery will work.
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
when (requestCode){
CAMERA_REQUEST_CODE -> {
if (grantResults.isNotEmpty()){
val cameraAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED
val storageAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED
if (cameraAccepted && storageAccepted){
pickImageCamera()
}
}
}
STORAGE_REQUEST_CODE -> {
if (grantResults.isNotEmpty()){
val storageAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED
if (storageAccepted){
pickImageGallery()
}
}
}
}
}
}

After addOnSuccessListener() the app is redirected to other activity

In my app I have implemented image upload to firebase storage, after upload url of the image is stored in realtime database for future use. Everything is working perfectly except whenever the url of the image is stored in realtime database the app move towards the BottomNavigation. below is my code
Adapter Class from which the app is redirected towards the pictureTakingActivity
class PrintAdapter(val data:ArrayList<PrintModel>) : RecyclerView.Adapter<PrintAdapter.MyViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
var view = LayoutInflater.from(parent.context).inflate(R.layout.single_row_home, parent, false)
return MyViewHolder(view)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.name.setText(data.get(position).name)
Picasso.get().load(data[position].image).into(holder.image)
Log.d("TAG", "The image is: " + data[position].catName)
var cat = data.get(position).catName
holder.itemView.setOnClickListener{
if (cat.equals("photo")){
val intent = Intent(it.context, PictureTakingActivity::class.java)
it.context.startActivity(intent)
}
}
}
override fun getItemCount(): Int {
return data.size
}
class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
// Both of these can be used to find id
var name: TextView = itemView.findViewById(R.id.printName)
var image = itemView.findViewById<ImageView>(R.id.circleImageView1)
}
}
PictureTakingActivity
class PictureTakingActivity : AppCompatActivity() {
lateinit var uri: Uri
lateinit var binding: ActivityPictureTakingBinding
lateinit var databaseReference: DatabaseReference
lateinit var firebaseUser: FirebaseUser
lateinit var id: String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityPictureTakingBinding.inflate(layoutInflater)
setContentView(binding.root)
databaseReference = FirebaseDatabase.getInstance().reference
firebaseUser = FirebaseAuth.getInstance().currentUser!!
id = firebaseUser.uid
binding.takePhoto.setOnClickListener {
ImagePicker.with(this)
.crop()
.galleryMimeTypes(
mimeTypes = arrayOf(
"image/png",
"image/jpg",
"image/jpeg"
)
)
.cameraOnly()
.compress(1024)
.maxResultSize(1080, 1080)
.start()
}
binding.uploadGallery.setOnClickListener {
ImagePicker.with(this)
.crop()
.galleryMimeTypes(
mimeTypes = arrayOf(
"image/png",
"image/jpg",
"image/jpeg"
)
)
.galleryOnly()
.compress(1024)
.maxResultSize(1080, 1080)
.start()
}
binding.ok.setOnClickListener {
uploadImage()
}
binding.notOk.setOnClickListener {
ImagePicker.with(this)
.crop()
.galleryMimeTypes(
mimeTypes = arrayOf(
"image/png",
"image/jpg",
"image/jpeg"
)
)
.compress(1024)
.maxResultSize(1080, 1080)
.start()
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == Activity.RESULT_OK) {
//Image Uri will not be null for RESULT_OK
uri = data?.data!!
binding.userImage.setImageURI(uri)
binding.takePhoto.visibility = View.INVISIBLE
binding.uploadGallery.visibility = View.INVISIBLE
binding.ok.visibility = View.VISIBLE
binding.notOk.visibility = View.VISIBLE
Log.d("TAG", "The uri inside is: $" )
} else if (resultCode == ImagePicker.RESULT_ERROR) {
Toast.makeText(this, ImagePicker.getError(data), Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(this, "Task Cancelled", Toast.LENGTH_SHORT).show()
}
}
private fun uploadImage(){
val progressBar = ProgressDialog(this)
progressBar.setMessage("Uploading file...")
progressBar.setCancelable(false)
progressBar.show()
val formatter = SimpleDateFormat("yyyy_MM_dd_HH_mm_ss", Locale.getDefault())
val now = Date()
val fileName = formatter.format(now)
val storageRefrence = FirebaseStorage.getInstance().reference.child(id).child("images/$fileName")
storageRefrence.putFile(uri).addOnSuccessListener {
progressBar.dismiss()
storageRefrence.downloadUrl.addOnSuccessListener {
databaseReference.child("Users").child(id).child("image").setValue(it.toString()).addOnSuccessListener { // After this line is executed app redirect towards MainActivity
Toast.makeText(this, "File uploaded successfully", Toast.LENGTH_SHORT).show()
}
}
}.addOnFailureListener{
progressBar.dismiss()
}
}
}
BottomNavigationActivity
class BottomNavigationActivity : AppCompatActivity() {
lateinit var binding:ActivityBottomNavigationBinding
private val fragment1: Fragment = HomeFragment()
private val fragment2: Fragment = DocumentsFragment()
private val fragment3: Fragment = OrdersFragment()
private val fragment4: Fragment = ProfileFragment()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityBottomNavigationBinding.inflate(layoutInflater)
setContentView(binding.root)
replaceFrameLayout(fragment1)
binding.bottomNavigation.setOnItemSelectedListener {
when(it.itemId){
R.id.home -> replaceFrameLayout(fragment1)
R.id.documents -> replaceFrameLayout(fragment2)
R.id.orders -> replaceFrameLayout(fragment3)
R.id.profile -> replaceFrameLayout(fragment4)
else ->{
}
}
true
}
}
private fun replaceFrameLayout(fragment: Fragment){
val fragmentManager = supportFragmentManager
val fragmentTransaction = fragmentManager.beginTransaction()
fragmentTransaction.replace(R.id.flFragment, fragment)
fragmentTransaction.commit()
}
}
I am new in Kotlin so please pardon if this is a simple issue. Thanks in advance

Adding user profile picture in Kotlin

I've recently started programming in Kotlin and cannot seem to add a profile picture to a user when registering it.
According to the code here, I can access to the gallery and retrieve the image information. The picture will appear on screen, but after registering the user the image url will not appear anywhere.
class RegisterUser : AppCompatActivity() {
private val database = FirebaseDatabase.getInstance()
private val auth: FirebaseAuth = FirebaseAuth.getInstance()
private val UserCreation = database.getReference("Usuarios")
private val pickImage = 100
private var imageUri: Uri? = null
lateinit var imageView: ImageView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_register_user)
Goback.setOnClickListener {
val Gobackou = Intent(this, MainActivity::class.java)
startActivity(Gobackou)
}
RegisterConfirm.setOnClickListener {
val SetUser = SetUser.text.toString()
val SetPass = setPass.text.toString()
val SetEmail = SetEmail.text.toString()
if (SetUser.isEmpty() && SetPass.isEmpty() && SetEmail.isEmpty()) {
Toast.makeText(this, "Faltan Campos", Toast.LENGTH_SHORT).show()
} else {
RegisterUserv2(SetEmail, SetPass, SetUser)
}
}
selectPP.setOnClickListener {
val intent = Intent(Intent.ACTION_PICK)
intent.type = "image/*"
startActivityForResult(intent, pickImage)
}
}
var selectedPhotoUri: Uri? = null
//guardar la foto de perfil
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == RESULT_OK && requestCode == pickImage) {
val selectedPhotoUri = data?.data
val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, selectedPhotoUri)
val bitmapDrawable = BitmapDrawable(bitmap)
userimg.setBackgroundDrawable(bitmapDrawable)
}
}
private fun RegisterUserv2(email: String, password: String, user: String) {
auth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
uploadimage()
UltrasaveUsuario(Usuarios(auth.currentUser!!.uid, user, password, email))
val Gobackou = Intent(this, MainActivity::class.java)
startActivity(Gobackou)
} else {
Toast.makeText(this, "Registro ERROR", Toast.LENGTH_LONG).show()
}
}
}
private fun UltrasaveUsuario(usuario: Usuarios) {
val mensajeFirebase = UserCreation.push()
usuario.id = mensajeFirebase.key ?: ""
mensajeFirebase.setValue(usuario)
}
private fun uploadimage(imageurl: String){
if (selectedPhotoUri == null) return
val filename = UUID.randomUUID().toString()
val ref = FirebaseStorage.getInstance().getReference("/images/$filename/")
ref.putFile(selectedPhotoUri!!)
.addOnSuccessListener {
ref.downloadUrl.addOnSuccessListener{
}
}
}
}
Since you are using firebase I will show you how to save firebase storage.
private fun uploadImage() {
if (mSelectedImageFileUri != null) {
val sRef: StorageReference = FirebaseStorage.getInstance().reference.child(
"users/ $uid/profile.jpg"
)
sRef.putFile(mSelectedImageFileUri!!)
.addOnSuccessListener { taskSnapshot ->
taskSnapshot.metadata!!.reference!!.downloadUrl
.addOnSuccessListener { url ->
}
}.addOnFailureListener {
//error
}
} else {
}
}
then you will take this picture using the user id to take .
firebase>storage to view the image
getImage
val sRef: StorageReference = FirebaseStorage.getInstance().reference.child(
"users/ $uid/profile.jpg"
)
sRef.downloadUrl.addOnSuccessListener {
Picasso.get().load(it).into(globalprofileImage)
}
Build.gradle
implementation 'com.squareup.picasso:picasso:2.71828'
https://www.youtube.com/watch?v=nNYLQcmB7AU&t=449s&ab_channel=SmallAcademy

How to compress Image byte size and convert it to WEBP in Android using zetbaitsu/Compressor

Ive been trying to reverse engineer this project to understand more about zetbaitsu's Image Compression on github. Sad thing is, the code wont even compile. And I cant understand some of the code since its written in Java and not Kotlin.
Its been days since I started looking for a clear and straight to the point tutorial that tells how to compress image size. Can anyone tell me how I can compress Image file size and format.
If you have another way, please do include it bellow.
class MainActivity : AppCompatActivity() {
private lateinit var mainBinding: ActivityMainBinding
private lateinit var imageUri: Uri
// For Image Compression
private lateinit var actualImageFile: File
private lateinit var compressedImageFile: File
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main)
fetchDataInFirebaseDatabase()
buttonFunctions()
}
class CardView(val text: String, val imageUrl: String, val dataUuid: String) {
constructor(): this("", "", "")
}
class MainAdapter(val cardView: ArrayList<CardView>): RecyclerView.Adapter<CustomViewHolder>() {
class CustomViewHolder(val view: View): RecyclerView.ViewHolder(view)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CustomViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.cardview_main, parent, false)
return CustomViewHolder(view)
}
override fun onBindViewHolder(holder: CustomViewHolder, position: Int) {
holder.view.apply {
cardView_textView.text = cardView[position].text
Picasso.get().load(cardView[position].imageUrl).into(holder.view.cardView_imageView)
}
}
override fun getItemCount(): Int {
return cardView.count()
}
}
private fun fetchDataInFirebaseDatabase() {
val databaseRef = FirebaseDatabase.getInstance().getReference("/")
val cardView = ArrayList<CardView>()
val mainAdapter = MainAdapter(cardView)
databaseRef.addChildEventListener(object : ChildEventListener{
override fun onChildAdded(snapshot: DataSnapshot, previousChildName: String?) {
snapshot.children.forEach {
val dataValue = it.getValue(CardView::class.java)
if (dataValue != null) cardView.add(dataValue)
mainAdapter.notifyDataSetChanged()
}
Log.d("MainFragment", "Number of children ${snapshot.key} = ${snapshot.childrenCount}")
}
override fun onChildChanged(snapshot: DataSnapshot, previousChildName: String?) {}
override fun onChildRemoved(snapshot: DataSnapshot) {
snapshot.children.forEach {
mainAdapter.notifyDataSetChanged()
}
}
override fun onChildMoved(snapshot: DataSnapshot, previousChildName: String?) {}
override fun onCancelled(error: DatabaseError) {}
})
mainBinding.activityMainGridRecyclerView.adapter = mainAdapter
}
private fun buttonFunctions() {
mainBinding.apply {
// Upload Text & Image in Firebase
activityMainUploadButton.setOnClickListener {
Log.d("MainActivity", "Uploading Data...")
//storeDataInFirebaseDatabase()
storeImageInFirebaseStorage()
}
// Choose an image in album
activityMainSelectPhotoButton.setOnClickListener {
Log.d("MainActivity", "Selecting Image...")
val intent = Intent(Intent.ACTION_PICK)
intent.type = "image/*"
startActivityForResult(intent, 0)
}
}
}
// Apply chosen image as button background
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == 0 && resultCode == RESULT_OK && data != null) {
Log.d("MainActivity", "Image Selected")
val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, imageUri)
mainBinding.activityMainSelectPhotoButton.apply {
text = ""
setBackgroundDrawable(BitmapDrawable(bitmap))
}
}
}
private var randomUUID: String? = null
private fun storeImageInFirebaseStorage() {
randomUUID = UUID.randomUUID().toString()
val storageRef = FirebaseStorage.getInstance().getReference("/FirebaseGridView/$randomUUID/")
storageRef.putFile(imageUri) // Store image URI in Firebase Storage
.addOnSuccessListener {
Log.d("MainActivity", "Image successfully stored in Firebase Storage")
Log.d("MainActivity", "Image size: ${it.metadata!!.sizeBytes}bytes / ${it.metadata!!.sizeBytes / 1000}kb")
storageRef.downloadUrl.addOnSuccessListener { // Get the image URL from Firebase Storage
storeDataInFirebaseDatabase(it.toString())
}
return#addOnSuccessListener
}.addOnFailureListener {
Log.d("MainActivity", "Image failed to store in Firebase Storage")
return#addOnFailureListener
}
}
// Stores data of CardView text/imageUrl/UUID in Firebase Database
private fun storeDataInFirebaseDatabase(imageUrl: String) {
val editText = mainBinding.activityMainInputEditText.text.toString()
val cardView = CardView(editText, imageUrl, randomUUID!!)
val databaseRef = FirebaseDatabase.getInstance().getReference("FirebaseGridView/$randomUUID/")
// Upload Data in FirebaseGridView/$randomUUID/ directory with the format/value of cardView
databaseRef.setValue(cardView)
.addOnSuccessListener {
Log.d("MainActivity", "Data successfully stored in Firebase Database")
Log.d("MainActivity", "\n \n Data Text: ${cardView.text} \n Data UUID: ${cardView. dataUuid} \n Image URL: ${cardView.imageUrl}")
Toast.makeText(this, "Data is stored", Toast.LENGTH_SHORT).show()
return#addOnSuccessListener
}.addOnFailureListener {
Log.d("MainActivity", "Data failed to be stored in Firebase Database")
Toast.makeText(this, "Data failed to store", Toast.LENGTH_SHORT).show()
return#addOnFailureListener
}
}
}
This is my failed attempt at trying to use Image Compress.
// TODO Compress Image file here
private fun customCompressImage() {
actualImageFile.let { imageFile ->
lifecycleScope.launch {
compressedImageFile = Compressor.compress(this#MainActivity, imageFile) {
//resolution(int)
quality(40)
format(Bitmap.CompressFormat.WEBP)
size(1_090_000) // 1mb
}
}
}
}
private fun setCompressedImage() {
compressedImageFile.let {
}
}

Activity going back to Main Activity after choosing a file from file chooser

In my case, I open the file chooser and choose a text file to import data to database. For now I am testing for counting lines. I get the exact line numbers but the problem is after choosing a file and counting lines, my application is going back to main page automatically. And the alert dialog is also dismissed. I have no idea what is happening. Here is my current code.
class Admin : AppCompatActivity() {
internal lateinit var lbl: TextView
internal lateinit var db: DataBaseHelper
internal lateinit var btnimport: ImageView
val requestcode=1
internal lateinit var scan: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_admin)
val btn_pw = findViewById<Button>(R.id.btn_pwd)
val btn_location = findViewById<Button>(R.id.btn_location)
val btn_import = findViewById<Button>(R.id.btn_import)
val btn_export = findViewById<Button>(R.id.btn_export)
btn_pw.setOnClickListener{
dialogLogin()
}
btn_location.setOnClickListener {
val intent = Intent(this,Search::class.java)
startActivity(intent)
}
btn_import.setOnClickListener {
importDialog(R.style.DialogSlide,this)
}
}
private fun dialogLogin(){
val builder = AlertDialog.Builder(this)
val inflater = this.layoutInflater
val view = inflater.inflate(R.layout.activity_password,null)
builder.setView(view)
val dialog: AlertDialog = builder.create()
dialog.window?.attributes?.windowAnimations = R.style.DialogSlide
dialog.setMessage("Please Fill The Branch Name")
dialog.show()
val brn_save =view.findViewById<Button>(R.id.btn_save)
val edt_pw = view.findViewById<EditText>(R.id.edt_pw)
brn_save.setOnClickListener{
branch = edt_pw.text.toString()
if(edt_pw.text == null){
Toast.makeText(this,"Please fill the branch",Toast.LENGTH_SHORT).show()
}
else{
password = edt_pw.text.toString()
dialog.dismiss()
setpwd(password.toString())
real_pwd = password.toString()
}
}
}
private fun setpwd( v:String) {
var editor=getSharedPreferences("yo", MODE_PRIVATE).edit()
editor.putString("val", v)
editor.apply()
}
/*import text file to database*/
private fun importDialog(type: Int,context: Context) {
val builder=AlertDialog.Builder(this)
val inflater=this.layoutInflater
val view=inflater.inflate(R.layout.import__dialog, null)
builder.setView(view)
val dialog: AlertDialog=builder.create()
dialog.window?.attributes?.windowAnimations=type
dialog.setMessage(context.getString(R.string.open_master))
lbl=EditText(this)
lbl=view.findViewById(R.id.edit_master)
lbl.text=noti.toString()
dialog.show()
dialog.setCancelable(false)
db=DataBaseHelper(this)
btnimport=view.findViewById(R.id.img_import)
btnimport.setOnClickListener {
val fileintent=Intent(Intent.ACTION_GET_CONTENT)
fileintent.type="txt/csv"
try {
startActivityForResult(fileintent, requestcode)
dialog.show()
} catch (e: ActivityNotFoundException) {
lbl.text="No activity can handle picking a file. Showing alternatives."
}
}
}
#SuppressLint("MissingSuperCall")
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (data == null)
return
if (requestCode==requestcode) {
val intent=Intent(this, MainActivity::class.java)
startActivity(intent)
val filepath=data.data
val cursor=contentResolver.openInputStream(android.net.Uri.parse(filepath.toString()))
lbl.text=filepath.toString()
master_path=filepath.toString()
noti=cursor.toString()
val db=this.openOrCreateDatabase("database.db", Context.MODE_PRIVATE, null)
val tableName="Master"
db.execSQL("delete from $tableName")
val text = StringBuilder()
try {
println("gg")
if (resultCode == Activity.RESULT_OK) {
try {
val file=InputStreamReader(cursor)
var lineCount = 0
val buffer=BufferedReader(file)
buffer.readLine()
val contentValues=ContentValues()
db.beginTransaction()
while(true) {
val line=buffer.readLine()
if (line == null) break
lineCount++
}
println(lineCount.toString())
db.setTransactionSuccessful()
db.endTransaction()
} catch (e: IOException) {
if (db.inTransaction())
db.endTransaction()
val d=Dialog(this)
d.setTitle(e.message.toString() + "first")
d.show()
}
} else {
if (db.inTransaction())
db.endTransaction()
val d=Dialog(this)
d.setTitle("Only CSV files allowed")
d.show()
}
} catch (ex: Exception) {
if (db.inTransaction())
db.endTransaction()
val d=Dialog(this)
d.setTitle(ex.message.toString() + "second")
d.show()
}
}
}
}
Looks like you are going there intentionally at
if (requestCode==requestcode) {
val intent=Intent(this, MainActivity::class.java)
startActivity(intent)
...
...

Categories

Resources