Lateinit property does not initialize - android

In this Tab (Hence why its a fragment) the user can choose to either upload a picture or take a new one from camera.
Once he clicks the button whether to decide for an option the App closes and the Logcat gives me this error:
2021-06-01 12:49:45.680 16355-16355/com.example.nlp_expense_tracker E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.nlp_expense_tracker, PID: 16355
kotlin.UninitializedPropertyAccessException: lateinit property receiptsViewModel has not been initialized
at com.example.nlp_expense_tracker.fragments.Scanner.getReceiptsViewModel(Scanner.kt:56)
at com.example.nlp_expense_tracker.fragments.Scanner.onCreateView$lambda-2$lambda-0(Scanner.kt:84)
at com.example.nlp_expense_tracker.fragments.Scanner.lambda$swyIeEDCHOralrhRcI5ZMLiEfwM(Unknown Source:0)
at com.example.nlp_expense_tracker.fragments.-$$Lambda$Scanner$swyIeEDCHOralrhRcI5ZMLiEfwM.onClick(Unknown Source:2)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:174)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
I am not quite sure where else to initiate the property.
Here is the Fragment code:
class Scanner : Fragment() {
private lateinit var imageView: ImageView
private lateinit var photoImage: Bitmap
private lateinit var mlkitImage: InputImage
private lateinit var editLocation: EditText
private lateinit var editVAT: EditText
private lateinit var editTotal: EditText
private val REQUEST_CODE_KAMERA = 42
private val REQUEST_CODE_GALLERY = 69
private val CAMERA_PERMISSION_CODE = 100
#Inject
lateinit var receiptsViewModel: ReceiptsViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,savedInstanceState: Bundle?):
View? {val view: View = inflater.inflate(R.layout.fragment_scan, container, false)
val btnTakePicture: Button = view.findViewById(R.id.btnTakePicture)
imageView = view.findViewById(R.id.imageView)
editLocation = view.findViewById(R.id.editLocation)
editTotal =view.findViewById(R.id.editTotal)
editVAT = view.findViewById(R.id.editVAT)
//Button Picture
btnTakePicture.setOnClickListener {
checkPermission(Manifest.permission.CAMERA,
CAMERA_PERMISSION_CODE)
val builder: AlertDialog.Builder = AlertDialog.Builder(requireActivity())
builder.setTitle("Choose a Receipt")
builder.setMessage("Either upload a Receipt or take a picture of one")
// add the buttons
builder.setPositiveButton("Use camera", DialogInterface.OnClickListener { dialog, which ->
startActivityForResult(receiptsViewModel.uploadIntent(), REQUEST_CODE_KAMERA)
})
builder.setNegativeButton("Upload from gallery", DialogInterface.OnClickListener { dialog, which ->
startActivityForResult(receiptsViewModel.cameraIntent(activity!!), REQUEST_CODE_GALLERY)
})
val dialog: AlertDialog = builder.create()
dialog.show()
}
return view
}
private fun uploadAction(data: Intent) {
try {
val resolver = requireActivity().contentResolver
val stream = resolver!!.openInputStream(data.getData()!!)
if (::photoImage.isInitialized) photoImage.recycle()
photoImage = BitmapFactory.decodeStream(stream)
mlkitImage = InputImage.fromBitmap(photoImage,0)
imageView.setImageBitmap(photoImage)
} catch (e: FileNotFoundException) {
e.printStackTrace()
}
}
private fun cameraAction() {
try {
Picasso.get().load(receiptsViewModel.imageURI).into(imageView)
mlkitImage = InputImage.fromFilePath(activity!!, receiptsViewModel.imageURI)
} catch (e: FileNotFoundException) {
e.printStackTrace()
}
}
private fun textRecognitionAction() {
var text = ""
receiptsViewModel.textDetector.process(mlkitImage)
.addOnSuccessListener {
for (block in it.textBlocks) text += block.text + "\n"
val receipts = receiptsViewModel.getReceipts(text)
editTotal.setText(receipts.total, TextView.BufferType.EDITABLE)
editLocation.setText(receipts.type, TextView.BufferType.EDITABLE)
editVAT.setText(receipts.vat, TextView.BufferType.EDITABLE)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (resultCode == Activity.RESULT_OK) {
when (requestCode) {
REQUEST_CODE_GALLERY -> uploadAction(data!!)
REQUEST_CODE_KAMERA -> cameraAction()
}
textRecognitionAction()
}
}
private fun checkPermission(permission: String, requestCode: Int) {
if (ContextCompat.checkSelfPermission(activity!!, permission) == PackageManager.PERMISSION_DENIED) {
// Requesting the permission
ActivityCompat.requestPermissions(activity!!, arrayOf(permission), requestCode)
} else {
Toast.makeText(activity!!, "Permission already granted", Toast.LENGTH_SHORT).show()
}
}
}
class ReceiptsViewModel #Inject constructor() {
lateinit var imageURI: Uri
var textDetector = TextRecognition.getClient(TextRecognizerOptions.DEFAULT_OPTIONS)
fun uploadIntent(): Intent {
val intent = Intent()
intent.type = "image/*"
intent.action = Intent.ACTION_GET_CONTENT
intent.addCategory(Intent.CATEGORY_OPENABLE)
return intent
}
fun cameraIntent(context: Context): Intent {
val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
val imageFileName = "IMG_" + timeStamp + "_"
val storageDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)
val filephoto = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
)
imageURI = FileProvider.getUriForFile(context, "com.example.nlp_expense_tracker.provider", filephoto)
val pictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
pictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageURI)
return pictureIntent
}
fun getReceipts(text: String): Receipts {
val originalResult = text.findFloat()
if (originalResult.isEmpty()) return Receipts()
else {
val receipts = Receipts()
val totalF = Collections.max(originalResult)
val secondLargestF = findSecondLargestFloat(originalResult)
receipts.total = totalF.toString()
receipts.vat = if (secondLargestF == 0.0f) "0" else "%.2f".format(totalF - secondLargestF)
receipts.type = text.firstLine()
return receipts
}
}
private fun findSecondLargestFloat(input: ArrayList<Float>?): Float {
if (input == null || input.isEmpty() || input.size == 1) return 0.0f
else {
try {
val tempSet = HashSet(input)
val sortedSet = TreeSet(tempSet)
return sortedSet.elementAt(sortedSet.size - 2)
} catch (e: Exception) {
return 0.0f
}
}
}
}

Your dependency injection does not seem to be working as implied by the error here
lateinit property receiptsViewModel has not been initialized
Rest of the properties seem okay, this piece of code is not working. You may check whatever it is you are using to see why that is failing.
#Inject
lateinit var receiptsViewModel: ReceiptsViewModel

Related

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

updating storage with the use of io fotoapparat library | Kotlin

I make a mobile application using the "io fotoapparat" library and I want to create a document with a random id and in the document in the id field, add the document id, the photo we will take was updated in the firebase store and in the previously made about the same id in the receipt collection when taking a photo
link from which I took "io fotoapparat"
EDIT
add to firestore document
binding.button.setOnClickListener {
// Inflate the layout for this fragment
val biedronka = "biedronka"
val price = "20"
val img = " "
val identificator = " "
val from = biedronka
val value = price
val image = img
val idd = identificator
val db = Firebase.firestore
val data = hashMapOf(
"from" to from,
"value" to value,
"image" to image,
"id" to idd
)
db.collection("receipts")
.add(data)
.addOnSuccessListener { documentReference ->
Log.d(SCAN_DEBUG, "DocumentSnapshot written with ID: ${documentReference.id}")
db.collection("receipts")
.document(documentReference.id)
.update("id", documentReference.id)
.addOnSuccessListener {
}
}
.addOnFailureListener { e ->
Log.w(SCAN_DEBUG, "Error adding document", e)
}
}
2 add to storage and to document (doesnt work)
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == REQUEST_CAPTURE_IMAGE && resultCode == RESULT_OK) {
val uid = profileVm.user.value?.uid!!
val imageBitmap = data?.extras?.get("data") as Bitmap
val userImage = binding.userImg
val stream = ByteArrayOutputStream()
val result = imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream)
val byteArray = stream.toByteArray()
if (result) profileVm.uploadUserPhoto(byteArray, "$uid.jpg")
}
}
repository to 2
fun uploadReceiptPhoto(bytes: ByteArray) {
storage.getReference("receipts")
.child("${docId}.jpg")
.putBytes(bytes)
.addOnCompleteListener{
Log.d(REPO_DEBUG, "COMPLETE UPLOAD PHOTO")
}
.addOnSuccessListener {
getReceiptPhotoDownloadUrl(it.storage)
}
.addOnFailureListener {
Log.d(REPO_DEBUG, it.message.toString())
}
}
private fun getReceiptPhotoDownloadUrl(storage: StorageReference) {
storage.downloadUrl
.addOnSuccessListener {
updateReceiptPhoto(it.toString())
}
.addOnFailureListener {
Log.d(REPO_DEBUG, it.message.toString())
}
}
private fun updateReceiptPhoto(url: String) {
cloud.collection("receipts")
.document(docId)
.update("image", url)
.addOnSuccessListener {
Log.d(REPO_DEBUG, "UPDATE USER PHOTO")
}
.addOnFailureListener {
Log.d(REPO_DEBUG, it.message.toString())
}
}
THE REST OF THE CODE (camera code "io fotoapparat" and take pictures)
class ScanFragment : Fragment(), OnReceiptsItemAdd {
private var _binding: FragmentScanBinding? = null
private val binding get() = _binding!!
private val scanVm by viewModels<ScanViewModel>()
private val SCAN_DEBUG = "SCAN_DEBUG"
private var fotoapparat: Fotoapparat? = null
private var fotoapparatState: FotoapparatState? = null
private var cameraStatus: CameraState? = null
private var flashState: FlashState? = null
private val permissions = arrayOf(Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE)
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?,
): View {
_binding = FragmentScanBinding.inflate(inflater, container, false)
createFotoapparat()
cameraStatus = CameraState.BACK
flashState = FlashState.OFF
fotoapparatState = FotoapparatState.OFF
binding.fabSwitchCamera.setOnClickListener {
switchCamera()
}
binding.fabFlash.setOnClickListener {
changeFlashState()
}
return binding.root
}
private fun createFotoapparat(){
val cameraView = binding.cameraView
fotoapparat = Fotoapparat(
context = requireContext(),
view = cameraView,
scaleType = ScaleType.CenterCrop,
lensPosition = back(),
logger = loggers(
logcat()
),
cameraErrorCallback = { error ->
println("Recorder errors: $error")
}
)
}
private fun changeFlashState() {
fotoapparat?.updateConfiguration(
CameraConfiguration(
flashMode = if(flashState == FlashState.TORCH) off() else torch()
)
)
flashState = if(flashState == FlashState.TORCH) FlashState.OFF
else FlashState.TORCH
}
private fun switchCamera() {
fotoapparat?.switchTo(
lensPosition = if (cameraStatus == CameraState.BACK) front() else back(),
cameraConfiguration = CameraConfiguration()
)
cameraStatus = if(cameraStatus == CameraState.BACK) CameraState.FRONT
else CameraState.BACK
}
private fun takePhoto() {
if (hasNoPermissions()) {
requestPermission()
}else{
fotoapparat
?.takePicture()
?.toBitmap()
}
}
override fun onStart() {
super.onStart()
if (hasNoPermissions()) {
requestPermission()
}else{
fotoapparat?.start()
fotoapparatState = FotoapparatState.ON
}
}
private fun hasNoPermissions(): Boolean{
return ContextCompat.checkSelfPermission(requireContext(),
Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(requireContext(),
Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(requireContext(),
Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
}
private fun requestPermission(){
ActivityCompat.requestPermissions(requireActivity(), permissions,0)
}
override fun onStop() {
super.onStop()
fotoapparat?.stop()
FotoapparatState.OFF
}
}
enum class CameraState{
FRONT, BACK
}
enum class FlashState{
TORCH, OFF
}
enum class FotoapparatState{
ON, OFF
}

Firebase recyclerview images disappear after reload application

When I just added it, everything is fine, but when I restart the application, only textViews is displayed. There is an empty space instead of an imageView.
My recycler adapter:
class PersonAdapter(options: FirebaseRecyclerOptions<Outfit?>) :
FirebaseRecyclerAdapter<Outfit, personsViewHolder>(options) {
override fun onBindViewHolder(holder: personsViewHolder, position: Int, model: Outfit) {
holder.name.text = model.name
holder.brand.text = model.brand
holder.size.text = model.size
holder.comment.text = model.comment
holder.price.text = model.price
Picasso.get().load(model.imageUrl).into(holder.imageView) //Glide analog
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): personsViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.recycler_item, parent, false)
return personsViewHolder(view)
}
class personsViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var name: TextView = itemView.findViewById(R.id.tv_name_value)
var brand: TextView = itemView.findViewById(R.id.tv_brand_value)
var size: TextView = itemView.findViewById(R.id.tv_size_value)
var comment: TextView = itemView.findViewById(R.id.tv_comment_value)
var price: TextView = itemView.findViewById(R.id.tv_price_value)
var imageView: ImageView = itemView.findViewById(R.id.imageView)
}
}
Class what add to database:
private var dataBase: DatabaseReference? = null
private lateinit var outfitImage: ImageView
private var imageUri: Uri? = null
private var id: Int = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_add_outfit)
nameView = findViewById(R.id.et_outfitName)
brandView = findViewById(R.id.et_outfitBrand)
sizeView = findViewById(R.id.et_outfitSize)
commentView = findViewById(R.id.et_outfitComment)
priceView = findViewById(R.id.et_outfitPrice)
btnAdd = findViewById(R.id.btn_addOutfit)
btnLoad = findViewById(R.id.btn_load)
btnAdd?.setOnClickListener {
onClickSave()
Toast.makeText(this, "Added to database", Toast.LENGTH_SHORT).show()
startActivity(Intent(this, MainActivity::class.java))
}
btnLoad?.setOnClickListener {
onClickRead()
}
outfitImage = findViewById(R.id.iv_upload_image)
outfitImage.setOnClickListener {
chooseImage()
}
}
//SAVE BUTTON
private fun onClickSave() {
dataBase = FirebaseDatabase.getInstance().getReference(UUID.randomUUID().toString())
dataBase?.setValue(
Outfit(
nameView?.text.toString(),
brandView?.text.toString(),
sizeView?.text.toString(),
commentView?.text.toString(),
priceView?.text.toString(),
imageUri.toString()
)
)
uploadImageToFirebase(imageUri!!)
}
//----------------UPLOAD IMAGE-----------------------
private fun chooseImage() {
val intent = Intent()
intent.type = "image/*"
intent.action = Intent.ACTION_GET_CONTENT
startActivityForResult(
Intent.createChooser(intent, "Please select..."), 1
)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == 1 && resultCode == Activity.RESULT_OK && data != null && data.data != null) {
// Get the Uri of data
imageUri = data.data
outfitImage.setImageURI(imageUri)
}
}
private fun uploadImageToFirebase(imageUri: Uri) {
val pd: ProgressDialog = ProgressDialog(this)
pd.setTitle("Uploading image...")
pd.show()
val fileName = UUID.randomUUID().toString()
val refStorage = FirebaseStorage.getInstance().reference.child("images/$fileName")
refStorage.putFile(imageUri)
.addOnSuccessListener { taskSnapshot ->
taskSnapshot.storage.downloadUrl.addOnSuccessListener {
pd.dismiss()
Snackbar.make(
findViewById(android.R.id.content),
"Image uploaded.",
Snackbar.LENGTH_LONG
)
val imageUrl = it.toString()
}
}
.addOnFailureListener { e ->
print(e.message)
pd.dismiss()
}
//progressbar
.addOnProgressListener {
var progressPercents: Double = (100.00 * it.bytesTransferred / it.totalByteCount)
pd.setMessage("Percentage: $progressPercents%")
}
}
}
Logic at MainActivity:
mbase = FirebaseDatabase.getInstance().reference
recyclerView = findViewById(R.id.recycler1)
recyclerView.layoutManager = LinearLayoutManager(this)
val options = FirebaseRecyclerOptions.Builder<Outfit>()
.setQuery(mbase!!, Outfit::class.java)
.build()
// Connecting object of required Adapter class to the Adapter class itself
adapter = PersonAdapter(options)
// Connecting Adapter class with the Recycler view*/
recyclerView.adapter = adapter
swipeRefreshLayout.setOnRefreshListener(this)
Here are screenshots of how everything looks in the backend:
my backend
images storage
private fun uploadToFirebase() {
val pd: ProgressDialog = ProgressDialog(this)
pd.setTitle("Uploading image...")
pd.show()
val fileName = UUID.randomUUID().toString()
val refStorage = FirebaseStorage.getInstance().getReference("/images/$fileName")
refStorage.putFile(selectedPhotoUri!!)
.addOnSuccessListener {
pd.dismiss() //close loading
refStorage.downloadUrl.addOnSuccessListener {
saveDataToDatabase(it.toString()) //get downloading url
}
}
.addOnFailureListener { e ->
print(e.message)
pd.dismiss()
}
//progressbar
.addOnProgressListener {
var progressPercents: Double = (100.00 * it.bytesTransferred / it.totalByteCount)
pd.setMessage("Percentage: $progressPercents%")
}
}
private fun saveDataToDatabase(imageUrl:String) {
dataBase = FirebaseDatabase.getInstance().getReference(UUID.randomUUID().toString())
dataBase?.setValue(
Outfit(
nameView?.text.toString(),
brandView?.text.toString(),
sizeView?.text.toString(),
commentView?.text.toString(),
priceView?.text.toString(),
imageUrl
)
)
}
Here is my solution. Bad url was a ploblem.

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