Horizontal circular RecyclerView in Kotlin? - android-studio

I am using a horizontal RecyclerView and showing images using the CircleImageView widget (See image below).
I am really struggling on how to make the list of items loop around, so that if you are in the last item, you will move to the first item in the list?
I have tried quite a few similar examples but I can’t make them work as they are in Java, or are quite complex. following is my code
MainActivity.kt
class MainActivity : AppCompatActivity() {
lateinit var adapter: ConcatAdapter
lateinit var userVerticalAdapter: UsersAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setupDataInRecyclerView()
}
private fun setupDataInRecyclerView() {
recyclerView.layoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
userVerticalAdapter = UsersAdapter(DataSource.getUser())
val listOfAdapters = listOf(userVerticalAdapter)
adapter = ConcatAdapter(listOfAdapters)
recyclerView.adapter = adapter
}
}
Adapter.kt
class UsersAdapter(
private val users: ArrayList<User>
) : RecyclerView.Adapter<UsersAdapter.DataViewHolder>() {
class DataViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bind(user: User) {
itemView.textViewUserName.text = user.name
Glide.with(itemView.imageViewAvatar.context)
.load(user.avatar)
.into(itemView.imageViewAvatar)
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
DataViewHolder(LayoutInflater.from(parent.context)
.inflate(R.layout.item_layout, parent,false))
override fun getItemCount(): Int = users.size
override fun onBindViewHolder(holder: DataViewHolder, position: Int) =
holder.bind(users[position])
}
}
DataSource.kt
object DataSource {
fun getUser() = ArrayList<User>().apply {
add(User(1, "Chillis", R.drawable.chilli))
add(User(2, "Tomato", R.drawable.tomatoe))
add(User(3, "Sweetcorn", R.drawable.sweeetcorn))
add(User(4, "Potatoe", R.drawable.potatoe))
add(User(5, "Aubergine", R.drawable.aubmain))
add(User(12, "Onion", R.drawable.onion))
}
}
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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:listitem="#layout/item_layout_banner"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
item_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_margin="1dp">
<androidx.cardview.widget.CardView
android:layout_width="120dp"
android:layout_height="120dp"
app:cardCornerRadius="4dp"
app:cardMaxElevation="2dp"
app:cardElevation="1dp"
android:layout_centerInParent="true">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<de.hdodenhof.circleimageview.CircleImageView
android:layout_width="90dp"
android:layout_height="90dp"
android:scaleType="centerCrop"
android:layout_centerHorizontal="true"
app:civ_border_width= "3dp"
app:civ_border_color= "#color/colorPrimary"
android:id="#+id/imageViewAvatar"
android:src="#drawable/ic_launcher_background"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="20dp"
android:text="Veg"
android:layout_below="#+id/imageViewAvatar"
android:id="#+id/textViewUserName"
android:gravity="center"
android:layout_marginTop="5dp"
android:layout_centerHorizontal="true"
android:textColor="#000"
android:layout_marginBottom="5dp"
android:autoSizeTextType="uniform"
android:autoSizeMinTextSize="8sp"
android:autoSizeMaxTextSize="15sp"/>
</RelativeLayout>
</androidx.cardview.widget.CardView>
</RelativeLayout>

To achieve this first you have to override the getItemCount function of UsersAdapter to return a very large value such as Int.MAX_VALUE
// This enables your adapter to scroll past the actual list size
override fun getItemCount(): Int = Int.MAX_VALUE
Now change your onBindViewHolder to calculate actual position
// Lets say your list had 100 items
override fun onBindViewHolder(holder: DataViewHolder, position: Int) {
// position can be larger than 100 (ex 101), because our getItemCount doesn't return actual list size
// so if we receive position as 101, which item should we display?
// that should be item 1. (for 102 -> 2, 201 -> 1) and so on
// this suggests use of modules
val pos = position % users.size
holder.bind(users[pos]) // bind the actual item
}
Now in your MainActivity after recyclerView.adapter = adapter line, add following line
// When RV is loaded scroll it to middle, so that user doesn't hit limit on both ends(easily)
rv.scrollToPosition(Int.MAX_VALUE/2)

Related

I suddenly get an unresolved reference error in my adapter class for the RecyclerView

everyone. I suddenly get an Unresolved reference error displayed in my layouts in RecyclerView. I've already restarted Android Studio, rebuilt and cleaned the project. All without success.
AddNewHomeFragment.kt:
class AddNewHomeFragment : Fragment() {
listImg = ArrayList()
var rv_img:RecyclerView = view.findViewById(R.id.recyclerViewImgs)
rv_img.layoutManager = GridLayoutManager(requireContext(),3)
adapter = CustomerAdapter(requireContext(),listImg){
var intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
startActivityForResult(intent,IMAGE_REQUEST)
}
rv_img.adapter = adapter
...
}
My CustomAdapter for RecyclerView:
class CustomerAdapter(val context: Context,
private val listImg:ArrayList<Int>, private val onClickFunction: ((Any?) -> Unit)? = null):RecyclerView.Adapter<CustomerAdapter.MyCustomViewHolder>() {
class MyCustomViewHolder(view: View):RecyclerView.ViewHolder(view) {
//Unresolved reference: customImg
val customImg:ImageView = view.findViewById(R.id.customImg)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyCustomViewHolder {
//Unresolved reference: single_img
val inflate = LayoutInflater.from(context).inflate(R.layout.single_img,parent,false)
return MyCustomViewHolder(inflate)
}
override fun onBindViewHolder(holder: MyCustomViewHolder, position: Int) {
holder.customImg.setImageResource(listImg[position])
holder.customImg.setOnClickListener {
this#CustomerAdapter.onClickFunction?.invoke(listImg[position])
}
}
override fun getItemCount(): Int {
return listImg.size
}
}
fragment_add_new_home.xml:
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerViewImgs"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
</androidx.recyclerview.widget.RecyclerView>
single_img.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"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_marginEnd="5dp"
android:layout_marginBottom="8dp"
android:background="#drawable/layout_for_imgs"
android:id="#+id/customImg"
app:layout_constraintDimensionRatio="1"
android:layout_width="0dp"
android:layout_height="0dp"
android:scaleType="centerCrop"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:src="#drawable/ic_baseline_add_home_24">
</ImageView>
</androidx.constraintlayout.widget.ConstraintLayout>

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

How to drag and drop ListView rows in Android Studio using Kotlin

I’m using Android Studio with Kotlin. I’d like to be able to drag and drop items in a ListView to reorder them. I also want to swipe left to delete. This was pretty straightforward in XCode/Swift for iOS, but I’m having trouble finding examples for Android/Kotlin. I’ve seen some fairly old discussions with Java and with RecyclerView, but it would be great to be able to do it in Kotlin with ListView. I should add that the ListView does everything I need so far – I realise there is much discussion about ListView vs RecyclerView.
I’m not asking for people to solve this for me, but it would be great if you could point me to anything that might get me going.
By way of background, here is my code. It is just a ListView with numbers ‘zero’ to ‘ten’ and the selected row highlighted. I should add that I wrote this code with the help of many discussions here and on YouTube, for which I’m very grateful.
I also have a ListView with sections that needs these options, but I’ve not put the code here for that (happy to do so if required).
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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ListView
android:id="#+id/list_view"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
android:layout_margin="16dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
listview_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/rowText"
android:layout_width="match_parent"
android:layout_height="48dp"
android:textColor="#color/black"
android:paddingLeft="0dp"
android:paddingTop="8dp"
android:paddingRight="0dp"
android:paddingBottom="8dp"
android:autoSizeTextType="uniform"
android:autoSizeMaxTextSize="40sp"
android:autoSizeMinTextSize="8sp"
android:autoSizeStepGranularity="2sp"
android:lines="1" />
</LinearLayout>
listview_selected_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/selectedRowText"
android:layout_width="match_parent"
android:layout_height="48dp"
android:paddingLeft="0dp"
android:paddingRight="0dp"
android:paddingTop="8dp"
android:paddingBottom="8dp"
android:background="#color/teal_200"
android:textColor="#color/black"
android:autoSizeTextType="uniform"
android:autoSizeMaxTextSize="40sp"
android:autoSizeMinTextSize="8sp"
android:autoSizeStepGranularity="2sp"
android:lines="1" />
</LinearLayout>
ListViewAdapter.kt
package com.ijmusic.listviewrearrange
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.TextView
val TYPE_LISTVIEW_ITEM = 0
val TYPE_LISTVIEW_SELECTED_ITEM = 1
class ListViewAdapter(private val context: Context): BaseAdapter() {
private val mData: ArrayList<String> = ArrayList()
private var mIndex: ArrayList<Int> = ArrayList()
private var mSelectedItem = -1
private lateinit var textView: TextView
fun addItem(item: String, index: Int) {
mData.add(item)
mIndex.add(index)
notifyDataSetChanged()
}
fun addSelectedItem(item: String, index: Int) {
mData.add(item)
mIndex.add(index)
mSelectedItem = mData.size - 1
notifyDataSetChanged()
}
fun highlightSelection(int: Int) {
mSelectedItem = int
notifyDataSetChanged()
}
override fun getItemViewType(position: Int): Int {
return if (position == mSelectedItem) TYPE_LISTVIEW_SELECTED_ITEM
else TYPE_LISTVIEW_ITEM
}
override fun getCount(): Int {
return mData.size
}
override fun getItem(position: Int): Any {
return mData[position]
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun getView(position: Int, view: View?, parent: ViewGroup?): View? {
var view = view
var type = getItemViewType(position)
if (position == mSelectedItem) type = TYPE_LISTVIEW_SELECTED_ITEM
when (type) {
TYPE_LISTVIEW_ITEM -> {
view = LayoutInflater.from(context).inflate(R.layout.listview_row, parent, false)
textView = view.findViewById(R.id.rowText)
}
TYPE_LISTVIEW_SELECTED_ITEM -> {
view = LayoutInflater.from(context).inflate(R.layout.listview_selected_row, parent, false)
textView = view.findViewById(R.id.selectedRowText)
}
}
textView.text = mData[position]
return view
}
}
MainActivity.kt
package com.ijmusic.listviewrearrange
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.AdapterView
import com.ijmusic.listviewrearrange.databinding.ActivityMainBinding
val list = listOf("zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten")
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private lateinit var mAdapter: ListViewAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
mAdapter = ListViewAdapter(this)
setListView()
binding.listView.onItemClickListener = object: AdapterView.OnItemClickListener {
override fun onItemClick(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
binding.listView.setSelection(position)
mAdapter.highlightSelection(position)
}
}
}
fun setListView() {
for ( i in 0 until list.count() ) {
if ( i == 0 )
mAdapter.addSelectedItem(list[i], i)
else
mAdapter!!.addItem(list[i], i)
}
binding.listView.adapter = mAdapter
}
}
You can look into a concept called gestures in android Kotlin. It will help.

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.

“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)

Resources