app shutsdown on onclick in androidstudio using kotlin - android-studio

am new in kotlin, i am just now making my first code app
there are 2 inputs & 1 button on which i set onclick sum
(i just drag & drop 2 inputs & 1 button, Don't have much knowledge because i have just started kotlin)
Mainactivity.kt
package com.example.hello
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
fun sum (view: View){
var a = number1.toString().toInt()
var b = number2.toString().toInt()
var result = a + b
textView2.text="Result: $result"
}
}
problem is when i click on sum button, my app automatically shuts down
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/number1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textAlignment="center"
tools:context=".MainActivity"
tools:layout_editor_absoluteX="-82dp"
tools:layout_editor_absoluteY="-24dp">
<Button
android:id="#+id/sum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="1dp"
android:layout_marginBottom="24dp"
android:hint="+"
android:onClick="sum"
app:layout_constraintBottom_toTopOf="#+id/number2"
app:layout_constraintStart_toStartOf="#+id/number2"
app:layout_constraintTop_toBottomOf="#+id/number1" />
<TextView
android:id="#+id/textView2"
android:layout_width="202dp"
android:layout_height="0dp"
android:layout_marginBottom="281dp"
android:text="TextView"
android:textSize="24sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/number2" />
<EditText
android:id="#+id/number2"
android:layout_width="254dp"
android:layout_height="0dp"
android:layout_marginEnd="61dp"
android:layout_marginBottom="96dp"
android:ems="10"
android:inputType="number"
app:layout_constraintBottom_toTopOf="#+id/textView2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="#+id/sum" />
<EditText
android:id="#+id/number1"
android:layout_width="269dp"
android:layout_height="0dp"
android:layout_marginTop="88dp"
android:layout_marginEnd="46dp"
android:layout_marginBottom="52dp"
android:ems="10"
android:inputType="number"
app:layout_constraintBottom_toTopOf="#+id/sum"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
am getting this error in debugs section:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.hello, PID: 23117
java.lang.IllegalStateException: Could not execute method for android:onClick
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:390)

As the comment said, it's hard to see what is wrong but I guess that number1 and number2 are views/EditTexts? in that case toString won't give you the text of those but instead a description of the object which for example could look like this:
"EditText:{ someinfo, 40183}"
And when you call toInt() on that String, kotlin doesn't know how to convert it and your app crashes.
Instead (if number1 and number2 are edittexts)
try:
number1.getText().toInt()

My guess is it's a NumberFormatException.
Solution:
fun sum (view: View){
var a = number1.text.toString().toInt()
var b = number2.text.toString().toInt()
var result = a + b
textView2.text="Result: $result"
}
You need to call text first to get the actual value in the input View. Calling toString on number1 and number2 will give you the string representation of these objects which is most likely a short description of the object and most likely not a number, hence, the NumberFormatException.

Related

How can I pass the checked radio button value into text View in kotlin android studio?

I made a dialogue box and I put radio group in it and I add three radio button 1)male 2)female 3)others if user select male so the selected radio button male should be shown in text View
Here, I would like to share you here a simple app with both the activity and layout code. I hope this will help you.
First the layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:padding="100dp"
tools:context=".TestActivity">
<TextView
android:id="#+id/textView3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="20dp"
android:text="What is your gender?"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="#+id/txtViewGender"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="20dp"
android:text="-- Selected Gender --"
android:textSize="16sp" />
<Button
android:id="#+id/button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Select" />
</LinearLayout>
Second the Main Activity code
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.dialog.MaterialAlertDialogBuilder
class GenderActivity: AppCompatActivity() {
private lateinit var selectedGender: String
private var selectedGenderIndex: Int = 0
private val gender = arrayOf("Male", "Female", "Others")
private lateinit var txtViewGender: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_test4)
txtViewGender = findViewById<TextView>(R.id.txtViewGender)
var androidButton: Button = findViewById<Button>(R.id.button)
androidButton.setOnClickListener {
showRadioDialog()
}
}
private fun showRadioDialog() {
selectedGender = gender[selectedGenderIndex]
MaterialAlertDialogBuilder(this)
.setTitle("Select your gender")
.setSingleChoiceItems(gender, selectedGenderIndex) { dialog, which ->
selectedGenderIndex = which
selectedGender = gender[which]
}
.setPositiveButton("Ok") { dialog, which ->
Toast.makeText(this, "Selected --> $selectedGender ", Toast.LENGTH_SHORT)
.show()
txtViewGender.text = selectedGender
}
.setNegativeButton("Cancel") { dialog, which ->
dialog.dismiss()
}
.show()
}
}
When you run the code, you will get the following two screens.
Screen 1
Screen 2

I have implemented the ability for my app to take a picture. Why is the file path null when I try to save the image locally?

This is my very first simple and almost-complete Android application.
My Goal
I want to take a picture with the device's built-in camera, display it on the ImageButton in that same Fragment, and have it save to the device locally so that I can reference its file path and add it to my custom SQLite Database to display in my RecyclerView on a different Fragment.
Background Info
My app is built on top of a custom SQLite Database backend containing two tables, users and their associated books that they've added to the app to be displayed in a RecyclerView.
The app is built entirely with Kotlin. Navigation is done using Android Jetpack's Navigation with a navigation graph (currently not using SafeArgs), and the entire app is run from a single MainActivity that holds multiple Fragments. I have a Fragment containing a RecyclerView, and this RecyclerView contains an ImageView where I hope to display the thumbnail of the picture that the user took with their device. To display images, I am using the 3rd-party Picasso library. The minimum API that my app is targeting is API 23. I am using the deprecated Camera API because Camera2 and CameraX had pretty much no improvement of my issue, so I fell back on this and it's not helping either.
My manifest contains these bits of code for Write access and Camera access permissions:
<uses-feature android:name="android.hardware.camera"
android:required="false"
/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.CAMERA"/>
My file provider is set up as follows:
<provider
android:authorities="<my_package_authority>.fileprovider"
android:name="androidx.core.content.FileProvider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths"
/>
</provider>
My file_paths.xml file is here:
<?xml version="1.0" encoding="utf-8" ?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-files-path
name="my_images"
path="Android/data/<my_package_authority>/files/Pictures">
</external-files-path>
<external-files-path
name="my_debug_images"
path="/storage/emulated/0/Android/data/<my_package_authority>/files/Pictures">
</external-files-path>
<external-files-path
name="my_root_images"
path="/">
</external-files-path>
</paths>
Here is my MainActivity.kt, which I use basically to store the request codes as well as the userID and bookID of the users and their books to upload to my database (patch-up solution to be better implemented later):
class MainActivity : AppCompatActivity() {
companion object {
val REQUEST_CAMERA_PERMISSIONS_CODE = 1
val REQUEST_CAMERA_USAGE = 2
var userID: Int? = null
var bookID: Int? = null
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
The .xml is completely unchanged and default.
Below is the .xml and .kt files for CreateBookFragment, the Fragment on which the user is going to add a book to their personal library.
fragment_create_book.xml (I am aware some of the bottom buttons clip out of the screen, depending on screen size. I plan to fix after the camera functionality is implemented)
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/clCreateBookRoot"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/grey"
tools:context=".CreateBookFragment">
<TextView
android:id="#+id/tvCreateBookTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:fontFamily="cursive"
android:shadowColor="#color/deep_red"
android:shadowDx="1.5"
android:shadowDy="1.5"
android:shadowRadius="1.5"
android:text="#string/add_book"
android:textColor="#color/deep_red"
android:textSize="55sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.024" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="3dp"
android:orientation="vertical"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/tvCreateBookTitle">
<ImageButton
android:id="#+id/ibCreateBookImage"
android:layout_width="75dp"
android:layout_height="75dp"
android:layout_gravity="center"
android:backgroundTint="#color/deep_red"
android:contentDescription="#string/add_a_picture_to_the_book"
android:src="#android:drawable/ic_menu_camera" />
<EditText
android:id="#+id/etCreateBookTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="50dp"
android:layout_marginTop="3dp"
android:layout_marginEnd="50dp"
android:layout_marginBottom="5dp"
android:ems="10"
android:hint="#string/title"
android:importantForAutofill="no"
android:inputType="textPersonName"
android:minHeight="48dp"
android:textColorHint="#color/black"
tools:ignore="TextContrastCheck" />
<EditText
android:id="#+id/etCreateBookAuthor"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="50dp"
android:layout_marginTop="3dp"
android:layout_marginEnd="50dp"
android:layout_marginBottom="5dp"
android:ems="10"
android:hint="#string/author"
android:importantForAutofill="no"
android:inputType="textPersonName"
android:minHeight="48dp"
android:textColorHint="#color/black"
tools:ignore="TextContrastCheck" />
<EditText
android:id="#+id/etCreateBookPages"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="50dp"
android:layout_marginTop="3dp"
android:layout_marginEnd="50dp"
android:layout_marginBottom="5dp"
android:ems="10"
android:hint="#string/total_pages"
android:importantForAutofill="no"
android:inputType="number"
android:minHeight="48dp"
android:textColorHint="#color/black"
tools:ignore="TextContrastCheck" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="50dp"
android:layout_marginTop="3dp"
android:layout_marginEnd="50dp"
android:layout_marginBottom="5dp"
android:orientation="horizontal">
<TextView
android:id="#+id/tvCreateBookGenre"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginStart="4dp"
android:layout_marginEnd="10dp"
android:text="#string/genre"
android:textColor="#color/black"
android:textSize="18sp" />
<Spinner
android:id="#+id/spinCreateBookGenre"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/genre"
android:importantForAutofill="no"
android:inputType="textPersonName"
android:minHeight="48dp"
android:textColorHint="#color/black"
tools:ignore="TextContrastCheck,SpeakableTextPresentCheck" />
</LinearLayout>
<EditText
android:id="#+id/etCreateBookPublisher"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="50dp"
android:layout_marginTop="3dp"
android:layout_marginEnd="50dp"
android:layout_marginBottom="5dp"
android:ems="10"
android:hint="#string/publisher"
android:importantForAutofill="no"
android:inputType="textPersonName"
android:minHeight="48dp"
android:textColorHint="#color/black"
tools:ignore="TextContrastCheck" />
<EditText
android:id="#+id/etCreateBookYearPublished"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="50dp"
android:layout_marginTop="3dp"
android:layout_marginEnd="50dp"
android:layout_marginBottom="5dp"
android:ems="10"
android:hint="#string/year_published"
android:importantForAutofill="no"
android:inputType="number"
android:minHeight="48dp"
android:textColorHint="#color/black"
tools:ignore="TextContrastCheck" />
<EditText
android:id="#+id/etCreateBookISBN"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="50dp"
android:layout_marginTop="3dp"
android:layout_marginEnd="50dp"
android:layout_marginBottom="5dp"
android:ems="10"
android:hint="#string/isbn_code"
android:importantForAutofill="no"
android:inputType="textPersonName"
android:minHeight="48dp"
android:textColorHint="#color/black" />
<EditText
android:id="#+id/etCreateBookStarRating"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="50dp"
android:layout_marginTop="3dp"
android:layout_marginEnd="50dp"
android:layout_marginBottom="5dp"
android:ems="10"
android:hint="#string/star_rating_1_5"
android:importantForAutofill="no"
android:inputType="number"
android:minHeight="48dp"
android:textColorHint="#color/black"
tools:ignore="TextContrastCheck" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="3dp"
android:gravity="center"
android:orientation="horizontal">
<Button
android:id="#+id/btnCancelCreateBook"
style="#style/cancel_button_style"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#android:string/cancel" />
<Button
android:id="#+id/btnSaveCreateBook"
style="#style/save_button_style"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/add" />
</LinearLayout>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
CreateBookFragment.kt
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import androidx.navigation.NavController
import androidx.navigation.Navigation
import com.squareup.picasso.MemoryPolicy
import com.squareup.picasso.NetworkPolicy
import com.squareup.picasso.Picasso
import java.io.File
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*
class CreateBookFragment : Fragment(), View.OnClickListener, AdapterView.OnItemSelectedListener {
private var photoFilePath: String? = "" // This is returning null!
private var navigationController: NavController? = null
private lateinit var etCreateBookTitle: EditText
private lateinit var etCreateBookAuthor: EditText
private lateinit var etCreateBookPages: EditText
private lateinit var spinCreateBookGenre: Spinner
private lateinit var etCreateBookPublisher: EditText
private lateinit var etCreateBookYearPublished: EditText
private lateinit var etCreateBookISBN: EditText
private lateinit var etCreateBookStarRating: EditText
private lateinit var ibCreateBookImage: ImageButton
private lateinit var btnCancelCreateBook: Button
private lateinit var btnSaveCreateBook: Button
private lateinit var genres: Array<out String>
private lateinit var spinnerText: String
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_create_book, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
navigationController = Navigation.findNavController(view)
initialiseUIElements(view)
setUpButtonClickListeners()
setUpGenreSpinner()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == MainActivity.REQUEST_CAMERA_USAGE && resultCode == Activity.RESULT_OK) {
val photoUri: Uri = Uri.parse(photoFilePath)
Picasso.with(requireContext())
.load(photoUri)
.memoryPolicy(MemoryPolicy.NO_CACHE)
.networkPolicy(NetworkPolicy.NO_CACHE)
.error(R.drawable.ic_custom_bookshelf)
.fit()
.centerInside()
.noFade()
.into(ibCreateBookImage)
}
}
private fun initialiseUIElements(view: View) {
etCreateBookTitle = view.findViewById(R.id.etCreateBookTitle)
etCreateBookAuthor = view.findViewById(R.id.etCreateBookAuthor)
etCreateBookPages = view.findViewById(R.id.etCreateBookPages)
spinCreateBookGenre = view.findViewById(R.id.spinCreateBookGenre)
etCreateBookPublisher = view.findViewById(R.id.etCreateBookPublisher)
etCreateBookYearPublished = view.findViewById(R.id.etCreateBookYearPublished)
etCreateBookISBN = view.findViewById(R.id.etCreateBookISBN)
etCreateBookStarRating = view.findViewById(R.id.etCreateBookStarRating)
ibCreateBookImage = view.findViewById(R.id.ibCreateBookImage)
btnCancelCreateBook = view.findViewById(R.id.btnCancelCreateBook)
btnSaveCreateBook = view.findViewById(R.id.btnSaveCreateBook)
}
private fun setUpButtonClickListeners() {
ibCreateBookImage.setOnClickListener(this)
btnCancelCreateBook.setOnClickListener(this)
btnSaveCreateBook.setOnClickListener(this)
}
private fun setUpGenreSpinner() {
genres = resources.getStringArray(R.array.book_genres)
val spinnerAdapter: ArrayAdapter<CharSequence> = ArrayAdapter(requireContext(), android.R.layout.simple_spinner_item, genres)
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spinCreateBookGenre.adapter = spinnerAdapter
spinCreateBookGenre.onItemSelectedListener = this
}
private fun addBook(view: View) {
if (checkEmpty(etCreateBookTitle) || checkEmpty(etCreateBookAuthor) ||
(checkEmpty(etCreateBookPages) || !isNumeric(etCreateBookPages.text.toString().trim())) ||
spinnerText.isEmpty() || checkEmpty(etCreateBookPublisher) ||
(checkEmpty(etCreateBookYearPublished) || !isNumeric(etCreateBookYearPublished.text.toString().trim())) ||
checkEmpty(etCreateBookISBN) ||
(checkEmpty(etCreateBookStarRating) || !isNumeric(etCreateBookStarRating.text.toString().trim()))) {
Toast.makeText(requireContext(), "Fields cannot be blank", Toast.LENGTH_SHORT).show()
}
else {
val bookTitle: String = etCreateBookTitle.text.toString().trim()
val bookAuthor: String = etCreateBookAuthor.text.toString().trim()
val bookPages: Int = etCreateBookPages.text.toString().trim().toInt()
val bookGenre: String = spinnerText
val bookPublisher: String = etCreateBookPublisher.text.toString().trim()
val bookYearPublished: Int = etCreateBookYearPublished.text.toString().trim().toInt()
val ISBN: String = etCreateBookISBN.text.toString().trim()
val bookStarRating: Float = etCreateBookStarRating.text.toString().trim().toFloat()
val bookImage: String? = if (photoFilePath != "")
photoFilePath
else
null
val dbHandler: DBHandler = DBHandler(requireContext())
val status = dbHandler.addBook(BookModelClass(null, bookTitle, bookAuthor, bookPages,
bookGenre, bookPublisher, bookYearPublished, ISBN, bookStarRating, 0, bookImage, MainActivity.userID!!))
if (status > -1) {
Toast.makeText(requireContext(), "Successfully added book to list", Toast.LENGTH_SHORT).show()
etCreateBookTitle.text.clear()
etCreateBookAuthor.text.clear()
etCreateBookPages.text.clear()
etCreateBookPublisher.text.clear()
etCreateBookYearPublished.text.clear()
etCreateBookISBN.text.clear()
etCreateBookStarRating.text.clear()
}
}
}
private fun checkEmpty(editText: EditText): Boolean {
if (editText.text.toString().trim() == "") {
return true
}
return false
}
override fun onClick(p0: View?) {
when (p0) {
ibCreateBookImage -> {
if (ContextCompat.checkSelfPermission(requireContext(), android.Manifest.permission.CAMERA)
== PackageManager.PERMISSION_GRANTED)
startCamera()
else {
ActivityCompat.requestPermissions(requireActivity(), arrayOf(android.Manifest.permission.CAMERA),
MainActivity.REQUEST_CAMERA_PERMISSIONS_CODE)
}
}
btnCancelCreateBook -> {
navigationController!!.navigate(R.id.action_createBookFragment_to_bookListFragment)
Toast.makeText(requireContext(), "Changes discarded", Toast.LENGTH_SHORT).show()
}
btnSaveCreateBook -> {
addBook(p0)
navigationController!!.navigate(R.id.action_createBookFragment_to_bookListFragment)
}
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == MainActivity.REQUEST_CAMERA_USAGE) {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)
startCamera()
else {
Toast.makeText(requireContext(), "Oops! Camera permission denied", Toast.LENGTH_SHORT).show()
return
}
}
}
private fun startCamera() {
val cameraIntent: Intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
var photoFile: File? = null
try {
photoFile = createPictureFile()
} catch (exception: IOException) {
Toast.makeText(requireContext(), "Error: Cannot save photo", Toast.LENGTH_SHORT).show()
return
}
if (photoFile != null) {
val photoUri = FileProvider.getUriForFile(requireContext(), requireActivity().packageName + ".fileprovider", photoFile)
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri)
startActivityForResult(cameraIntent, MainActivity.REQUEST_CAMERA_USAGE)
}
}
private fun createPictureFile(): File {
val timeStamp: String = SimpleDateFormat("ddMMyyyy_HHmmss", Locale.UK).format(Date().time)
val photoFileName: String = "IMG_" + timeStamp + "_"
val storageDirectory: File = requireContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES)!!
return File.createTempFile(photoFileName, ".jpg", storageDirectory).apply {
photoFilePath = absolutePath
}
}
private fun isNumeric(string: String): Boolean {
return string.all { char -> char.isDigit() }
}
override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
spinnerText = genres[p2].toString()
}
override fun onNothingSelected(p0: AdapterView<*>?) {
spinnerText = ""
}
}
The Issue
In reality, when trying to save the picture to the device, Android Studio registers the picture/path as "null", and I used to get a NullPointerException when trying to load the pictures on the RecyclerView before I started using Picasso, even when I can see the picture was indeed saved to local storage on the emulator (API 30) and on a physical device (API 24) with the path set to: "/storage/emulated/0/Android/data/<my_package_authority>/files/Pictures/IMG_01062022_164449_8511882897552656984.jpg" for the emulator and a similar path for the physical device (file_paths.xml included below). I got this path by using an application called DBBrowser for Sqlite, which I used to confirm that my database is indeed getting the path.
Picasso is only displaying the error image that I have set for the thumbnail, despite trying so many different sources such as the official Android docs and some other forums, videos and other StackOverflow questions/answers of a similar topic. When the user tries to add a picture to their book when creating it at first, it doesn't even actually show the picture after they've taken a camera picture. What appears to happen is that the file is never "officially" created, but the file does exist at the specified location on device memory. I am currently using the deprecated startActivityForResult() function for testing purposes and trying to set things in onActivityResult() inside the Fragment, but it's not working. I am using the deprecated function because the newer functions that replace it aren't helping either, so it was kind of a last-resort thing. An answer on StackOverflow suggested that the startActivityForResult() function is actually sending the data to the MainActivity instead of localising that data in the Fragment, which has pretty much caused the biggest headaches. It's been days, if not an entire week with this issue, send help...
I do not need any help with trying to display images or even trying to get the image path from my database, I only need help figuring out how to stop the file path from returning null so that Picasso can display the image preview when the user first adds the image on CreateBookFragment. If the file path can stop returning null, I can get this entire functionality going. I debated putting my database here with the two model classes, but it's like 1 000 lines of code and StackOverflow doesn't allow more than 40 000 characters.
A Few Sources (definitely not all of them)
https://developer.android.com/training/camera/photobasics
onActivityResult is not being called in Fragment
One of the MANY Youtube videos I've watched: https://www.google.com/search?q=how+to+save+an+image+from+camera+onto+device+android+studio&rlz=1C1CHBF_enZA979ZA979&oq=how+to+save+an+image+from+camera+onto+device+android+studio&aqs=chrome..69i57j0i22i30l2j0i390.10856j0j7&sourceid=chrome&ie=UTF-8#kpvalbx=_fW2YYqCeCJq6gAbewp2gCA22
Edit:
As a quick and dirty solution, I ended up saving the captured images as blobs in my SQLite database and converting them to bitmaps when it came time to displaying them on my ImageViews. I am still looking for a more efficient way to do this, as storing images as blobs in SQLite database isn't best practice.

Kotlin "D/skia: --- Failed to create image decoder with message 'unimplemented'" Error preventing functionality of button at login/registration screen

Hello I am currently facing an issue with my Kotlin code in Android SDK. For the purposes of a small personal project I am trying to get a simple change password functionality working with a nodeJS file and mongoDB. However I've run into the issue while writting up some code to this end. It seems that my change_password function doesn't want to launch the sequence to input the new password due to the following error "D/skia: --- Failed to create image decoder with message 'unimplemented'" which is only visible in the debug mode. I am not even certain where to start debugging this issue, so I'm hoping someone here might be able to help. Bellow I have provided my MainActivity file where the change_password function is present. Additionally I have provided the xml layout files involved in these operations.
MainActivity File
import android.Manifest
import android.app.Activity
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import com.afollestad.materialdialogs.MaterialDialog
import com.example.accentus_login.R.id.*
import com.example.accentus_login.Retrofit.INodeJS
import com.example.accentus_login.Retrofit.RetrofitClient
import com.github.javiersantos.materialstyleddialogs.MaterialStyledDialog
import com.rengwuxian.materialedittext.MaterialEditText
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.home_page.*
import org.jetbrains.anko.toast
class MainActivity : AppCompatActivity() {
lateinit var myAPI: INodeJS
var compositeDisposable = CompositeDisposable()
var m_bluetoothAdapter: BluetoothAdapter? = null
lateinit var m_pairedDevices: Set<BluetoothDevice>
val REQUEST_ENABLE_BLUETOOTH=1
internal lateinit var change_pass_confirm_button: Button
companion object{
val EXTRA_ADDRESS: String = "Device_address"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//Init API
val retrofit = RetrofitClient.instance
myAPI = retrofit.create(INodeJS::class.java)
//m_bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
//if (m_bluetoothAdapter==null){
// toast("this device doesn't support bluetooth")
// return
//}
//if(!m_bluetoothAdapter!!.isEnabled) {
// val enableBluetoothIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
// if (ActivityCompat.checkSelfPermission(
// this,
// Manifest.permission.BLUETOOTH_CONNECT
// ) != PackageManager.PERMISSION_GRANTED
// ) {
// ActivityCompat.requestPermissions(
// this#MainActivity,
// arrayOf(Manifest.permission.BLUETOOTH, Manifest.permission.BLUETOOTH_ADMIN),REQUEST_ENABLE_BLUETOOTH)
// }
// startActivityForResult(enableBluetoothIntent, REQUEST_ENABLE_BLUETOOTH)
//}
//select_device_refresh.setOnClickListener{ pairedDeviceList() }
//change_pass_confirm_button = findViewById(R.id.change_pass_confirm_button);
login_button.setOnClickListener{
login(edt_email.text.toString(),edt_password.text.toString())
}
register_button.setOnClickListener{
register(edt_email.text.toString(),edt_password.text.toString())
}
change_pass_button.setOnClickListener{
change_password(edt_email.text.toString())
}
}
private fun login(email: String, password: String) {
compositeDisposable.add(myAPI.loginUser(email, password)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe{ message ->
if (message.contains("encrypted_password"))
Toast.makeText(this#MainActivity,"Login Successful",Toast.LENGTH_SHORT).show()
else
Toast.makeText(this#MainActivity,message,Toast.LENGTH_SHORT).show()
setContentView(R.layout.home_page);
})
}
private fun change_password(email: String) {
val change_pass_view = LayoutInflater.from(this#MainActivity)
.inflate(R.layout.change_pass, null)
MaterialStyledDialog.Builder(this#MainActivity)
.setTitle("Change Password")
.setDescription("Enter New Password")
.setCustomView(change_pass_view)
.setNegativeText("Cancel")
.onNegative { materialDialog: MaterialDialog -> materialDialog.dismiss() }
.setPositiveText("Confirm")
.onPositive { materialDialog: MaterialDialog ->
val password = change_pass_view.findViewById(R.id.new_pass) as MaterialEditText
//val con_password = change_pass_view.findViewById(R.id.con_new_pass) as MaterialEditText
if (password != password)
Toast.makeText(this#MainActivity, "Password Doesn't Match", Toast.LENGTH_SHORT)
.show()
else
compositeDisposable.add(myAPI.ChangePass(email, password)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { message ->
Toast.makeText(this#MainActivity, message, Toast.LENGTH_SHORT).show()
})
}
}
private fun register(email: String, password: String) {
val enter_name_view = LayoutInflater.from(this#MainActivity)
.inflate(R.layout.enter_name_layout,null)
MaterialStyledDialog.Builder(this#MainActivity)
.setTitle("Register")
.setDescription("Last Step: Enter your Name")
.setCustomView(enter_name_view)
.setIcon(R.drawable.ic_user)
.setNegativeText("Cancel")
.onNegative{ materialDialog: MaterialDialog-> materialDialog.dismiss() }
.setPositiveText("Register")
.onPositive { materialDialog: MaterialDialog ->
val edt_name = enter_name_view.findViewById<View>(edt_name) as MaterialEditText
compositeDisposable.add(myAPI.registerUser(email,edt_name.text.toString(), password)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe{ message ->
Toast.makeText(this#MainActivity,message,Toast.LENGTH_SHORT).show()
})
}.show()
}
private fun pairedDeviceList(){
if (ActivityCompat.checkSelfPermission(
this,
Manifest.permission.BLUETOOTH_CONNECT
) != PackageManager.PERMISSION_GRANTED
) {
ActivityCompat.requestPermissions(
this#MainActivity,
arrayOf(Manifest.permission.BLUETOOTH, Manifest.permission.BLUETOOTH_ADMIN),REQUEST_ENABLE_BLUETOOTH)
}
m_pairedDevices = m_bluetoothAdapter!!.bondedDevices
val list : ArrayList<BluetoothDevice> = ArrayList()
if(m_pairedDevices.isNotEmpty()) {
for(device : BluetoothDevice in m_pairedDevices) {
list.add(device)
Log.i("device", ""+device) // device logged as string
}
} else {
toast("no paired bluetooth devices found")
}
val adapter = ArrayAdapter(this,android.R.layout.simple_list_item_1,list)
select_device_list.adapter=adapter
select_device_list.onItemClickListener= AdapterView.OnItemClickListener{ _, _, position, _ ->
val device: BluetoothDevice= list[position]
val address: String = device.address
val intent = Intent(this, ControlActivity::class.java)
intent.putExtra(EXTRA_ADDRESS,address)
startActivity(intent)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode==REQUEST_ENABLE_BLUETOOTH){
if(resultCode== Activity.RESULT_OK) {
if (m_bluetoothAdapter!!.isEnabled) {
toast("Bluetooth has been enabled")
} else {
toast("Bluetooth has been disabled")
}
} else if (resultCode == Activity.RESULT_CANCELED)
toast("Bluetooth enabling has been canceled")
}
}
override fun onStop() {
compositeDisposable.clear()
super.onStop()
}
override fun onDestroy() {
compositeDisposable.clear()
super.onDestroy()
}
XML Login Page
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/gradient_bg"
tools:context=".MainActivity">
<LinearLayout
android:layout_margin="16dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" >
<TextView
android:text="#string/accentus"
android:textSize="30sp"
android:textColor="#android:color/white"
android:layout_gravity="center_horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<com.rengwuxian.materialedittext.MaterialEditText
android:id="#+id/edt_email"
android:hint="#string/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
app:met_iconLeft="#drawable/ic_user"
app:met_baseColor="#android:color/white"
app:met_textColorHint="#android:color/white"
app:met_primaryColor="#android:color/white"
app:met_iconPadding="0dp"/>
<com.rengwuxian.materialedittext.MaterialEditText
android:id="#+id/edt_password"
android:hint="#string/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
app:met_iconLeft="#drawable/ic_lock"
app:met_baseColor="#android:color/white"
app:met_textColorHint="#android:color/white"
app:met_primaryColor="#android:color/white"
app:met_iconPadding="0dp"/>
<LinearLayout
android:orientation="horizontal"
android:weightSum="2"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.button.MaterialButton
android:id="#+id/register_button"
android:text="#string/register_account"
android:layout_marginEnd="8dp"
android:textSize="11sp"
style="#style/Widget.MaterialComponents.Button"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content">
</com.google.android.material.button.MaterialButton>
<com.google.android.material.button.MaterialButton
android:id="#+id/login_button"
android:text="#string/login"
android:layout_marginStart="8dp"
android:textSize="11sp"
style="#style/Widget.MaterialComponents.Button.UnelevatedButton"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content">
</com.google.android.material.button.MaterialButton>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:weightSum="2"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.button.MaterialButton
android:id="#+id/change_pass_button"
android:text="#string/forgot_password"
android:layout_marginStart="125dp"
android:textSize="11sp"
style="#style/Widget.MaterialComponents.Button.UnelevatedButton"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content">
</com.google.android.material.button.MaterialButton>
</LinearLayout>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
XML Change Password Page
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/gradient_bg"
tools:context=".MainActivity">
<LinearLayout
android:layout_margin="16dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" >
<TextView
android:text="#string/change_password"
android:textSize="30sp"
android:textColor="#android:color/white"
android:layout_gravity="center_horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<com.rengwuxian.materialedittext.MaterialEditText
android:id="#+id/login_email"
android:hint="#string/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
app:met_baseColor="#android:color/white"
app:met_textColorHint="#android:color/white"
app:met_primaryColor="#android:color/white"
app:met_iconPadding="0dp"/>
<com.rengwuxian.materialedittext.MaterialEditText
android:id="#+id/new_pass"
android:hint="#string/new_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
app:met_baseColor="#android:color/white"
app:met_textColorHint="#android:color/white"
app:met_primaryColor="#android:color/white"
app:met_iconPadding="0dp"/>
<com.rengwuxian.materialedittext.MaterialEditText
android:id="#+id/con_new_pass"
android:hint="#string/confirm_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
app:met_iconLeft="#drawable/ic_lock"
app:met_baseColor="#android:color/white"
app:met_textColorHint="#android:color/white"
app:met_primaryColor="#android:color/white"
app:met_iconPadding="0dp"/>
<LinearLayout
android:orientation="horizontal"
android:weightSum="2"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</LinearLayout>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
Please let me know if you think there is any other information necessary to understand why this is going on.

“Unresolved reference” in MainActivity.kt calling a TextView? [duplicate]

This question already has answers here:
Why do I get "unresolved reference" error for my view's name/ID when I type it in Kotlin?
(2 answers)
Closed 1 year ago.
when I try to use a TextView in my activity_main.xml, I get a “Unresolved reference” in my MainActivity.kt (even before try building)? I just can’t see what I’m doing wrong!
I've highlighted the error at the end of the MainActivity.
Any help appreciated.
MainActivity.kt
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val carouselRecyclerview = findViewById<CarouselRecyclerview>(R.id.recycler)
val list = ArrayList<DataModel>()
list.add(DataModel(R.drawable.ad_astra, "Adastra"))
list.add(DataModel(R.drawable.beach_bum, "Beach Bum"))
list.add(DataModel(R.drawable.dark_phoenix, "Dark Phoenix"))
list.add(DataModel(R.drawable.glass, "Glass"))
val adapter = DataAdapter(list)
carouselRecyclerview.adapter = adapter
carouselRecyclerview.set3DItem(true)
carouselRecyclerview.setAlpha(true)
val carouselLayoutManager = carouselRecyclerview.getCarouselLayoutManager()
val currentlyCenterPosition = carouselRecyclerview.getSelectedPosition()
carouselRecyclerview.setItemSelectListener(object : CarouselLayoutManager.OnSelected {
override fun onItemSelected(position: Int) {
//Cente item
Toast.makeText(this#MainActivity, list[position].text, Toast.LENGTH_LONG).show()
ShowMeIt.text = "Why does cause a Unresolved reference?"
ShowMeIt.text = list[position].text
}})
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.jackandphantom.carouselrecyclerview.CarouselRecyclerview
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/recycler"/>
<TextView
android:id="#+id/ShowMeIt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"
android:layout_marginEnd="186dp"
android:layout_marginRight="186dp"
android:layout_marginBottom="106dp"
android:text="Hello" />
</RelativeLayout>
I think you need to define on MainActivity.kt like this
val ShowMeIt= findViewById<TextView>(R.id.ShowMeIt)

Get a view in an object using kotlin

I try to get a reference to an EditText in an object.
The import import kotlinx.android.synthetic.main.dialog_save_recording.dialog_save_recording_edittext_name doesn't work in the object.
My code:
object Dialog {
fun createDialog(context: Context, layoutId: Int? = null) {
val builder = AlertDialog.Builder(context)
if (layoutId != null) {
builder.setView(layoutId)
builder.setPositiveButton(context.getString(R.string.dialog_save_button_text)) { _, _ ->
//get the input of the editText here
}
... //not important for my question
The layout I want to reference:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_gravity="center"
android:padding="#dimen/dialog_padding"
android:layout_margin="#dimen/dialog_margin">
<TextView
android:id="#+id/dialog_save_recording_textview_name"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="#string/dialog_save_recording_name"
android:textSize="#dimen/text_size_normal" />
<EditText
android:id="#+id/dialog_save_recording_edittext_name"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:hint="#string/dialog_save_recording_name_hint"
android:importantForAutofill="no"
android:inputType="text"/>
</LinearLayout>
I tried it with findViewById or working with the layoutId but had no success for now. I'm searching for a solution without inherit the object from Activity().
Anyone an idea how to do this?
You first need to build the dialog:
val dialog = builder.build()
Then you can use:
val editText = dialog.requireViewById(R.id.dialog_save_recording_edittext_name)
After you apply changes, don't forget to display the dialog:
dialog.show()

Resources