Implementing ViewModel to seekbars and are stuck - android

I am currently making a loan app where the user can use seekbar for how large the rent is going to be int how many years they want to pay down the loan.
We are supposed to use viewmodel, live data and databinding to store data between fragments. Iam stuck when it comes to use viewmodel to find progress int inside the seekbar.
I am not sure how to call the startPoint and endPoint that is going to determinate the "var" I need to calculate the loan plan in the next fragment?
Please look past that the file contains comments since it older code I am rewriting.
Thanks for the help.
AnnuitetFragment.kt:
package com.example.lnognedbetalingsplan
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.SeekBar
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import com.example.lnognedbetalingsplan.databinding.FragmentAnnuitetBinding
import com.example.lnognedbetalingsplan.viewmodel.AnnuitetViewModel
class AnnuitetFragment : Fragment() {
private var _binding: FragmentAnnuitetBinding? = null
private val binding get() = _binding!!
private lateinit var viewModel: AnnuitetViewModel
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
_binding = FragmentAnnuitetBinding.inflate(inflater, container, false)
return binding.root
}
val viewAnnuitet = inflater.inflate(R.layout.fragment_annuitet, container, false)
val buttonTilbake = viewAnnuitet.findViewById<Button>(R.id.tilbakeTilVelkommen)
val buttonBeregn = viewAnnuitet.findViewById<Button>(R.id.BeregnLaanAnnuitet)
val seekbarRenter = viewAnnuitet.findViewById<SeekBar>(R.id.RenterAnnSeekBar)
val seekBarAar = viewAnnuitet.findViewById<SeekBar>(R.id.AarSerieSeekBar)
val renterTall = viewAnnuitet.findViewById<TextView>(R.id.RenterTall)
val aarTall = viewAnnuitet.findViewById<TextView>(R.id.AarTall)
// var startPoint = 0
// var endPoint = 0
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.tilbakeTilVelkommen.setOnClickListener {
findNavController().navigate(R.id.action_velkommenFragment_to_annuitetFragment)
}
binding.BeregnLaanAnnuitet.setOnClickListener {
findNavController().navigate(R.id.action_velkommenFragment_to_serieFragment)
}
binding.RenterAnnSeekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
binding.RenterTall.text = progress.toString()
}
override fun onStartTrackingTouch(p0: SeekBar?) {
if (p0 != null){
viewModel =
}
}
override fun onStopTrackingTouch(p0: SeekBar?) {
TODO("Not yet implemented")
}
}
// seekbarRenter.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
// override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
// RenterTall
// }
//
// override fun onStartTrackingTouch(seekBar: SeekBar?) {
// if (seekBar != null){
// startPoint = seekBar.progress
// }
//
// }
//
// override fun onStopTrackingTouch(seekBar: SeekBar?) {
// if (seekBar != null){
// endPoint = seekBar.progress
// }
// }
// })
//
// seekBarAar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
// override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
// aarTall.text = progress.toString()
// }
//
// override fun onStartTrackingTouch(seekBar: SeekBar?) {
// if (seekBar != null){
// startPoint = seekBar.progress
// }
//
// }
//
// override fun onStopTrackingTouch(seekBar: SeekBar?) {
// if (seekBar != null){
// endPoint = seekBar.progress
// }
// }
// })
return viewAnnuitet
}
}
fragment_annuitet.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">
<SeekBar
android:id="#+id/RenterAnnSeekBar"
android:layout_width="300dp"
android:layout_height="30dp"
android:max="50"
android:min="0"
android:progress="5"
app:layout_constraintBottom_toTopOf="#+id/AarSerieSeekBar"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.306"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.84" />
<SeekBar
android:id="#+id/AarSerieSeekBar"
android:layout_width="300dp"
android:layout_height="30dp"
android:max="50"
android:min="0"
android:progress="5"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.306"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.499" />
<EditText
android:id="#+id/laanebelop"
android:layout_width="196dp"
android:layout_height="56dp"
android:autofillHints=""
android:ems="10"
android:hint="#string/hint"
android:inputType="numberDecimal"
android:textColorHint="#757575"
android:visibility="visible"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.641"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.248" />
<TextView
android:id="#+id/Laanebelop"
android:layout_width="103dp"
android:layout_height="40dp"
android:layout_marginTop="184dp"
android:text="#string/laaneBeløp"
android:textSize="20sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.11"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/AarTall"
android:layout_width="35dp"
android:layout_height="30dp"
android:text="#string/_5"
android:textSize="20sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.619"
app:layout_constraintStart_toEndOf="#+id/AarSerieSeekBar"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.499" />
<TextView
android:id="#+id/RenterTall"
android:layout_width="35dp"
android:layout_height="30dp"
android:text="#string/_5"
android:textSize="20sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.633"
app:layout_constraintStart_toEndOf="#+id/RenterAnnSeekBar"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.383" />
<TextView
android:id="#+id/Rentenummer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/velg_rente"
app:layout_constraintBottom_toTopOf="#+id/RenterAnnSeekBar"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.097"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/Laanebelop"
app:layout_constraintVertical_bias="0.692" />
<TextView
android:id="#+id/antallAar"
android:layout_width="62dp"
android:layout_height="21dp"
android:text="#string/antall_aar"
app:layout_constraintBottom_toTopOf="#+id/AarSerieSeekBar"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.097"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/RenterAnnSeekBar"
app:layout_constraintVertical_bias="0.666" />
<Button
android:id="#+id/BeregnLaanAnnuitet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="264dp"
android:text="#string/bergen_l_net"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.757"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/AarSerieSeekBar"
app:layout_constraintVertical_bias="1.0" />
<Button
android:id="#+id/tilbakeTilVelkommen"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:layout_marginEnd="68dp"
android:text="#string/tilbake"
app:layout_constraintBottom_toTopOf="#+id/laanebelop"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0" />
<TextView
android:id="#+id/textView2"
android:layout_width="180dp"
android:layout_height="40dp"
android:layout_marginStart="32dp"
android:layout_marginTop="24dp"
android:text="#string/annuitet_l_n"
android:textStyle="bold"
android:textSize="30sp"
app:layout_constraintBottom_toTopOf="#+id/Laanebelop"
app:layout_constraintEnd_toStartOf="#+id/tilbakeTilVelkommen"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.066" />
</androidx.constraintlayout.widget.ConstraintLayout>

Related

Why the data from firebase database is not showing in my recyclerview while searching?

MainActivity.kt Code
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
val db = Firebase.firestore
val firebaseFirestore : FirebaseFirestore = FirebaseFirestore.getInstance()
private var searchList: List<dataClass> = ArrayList()
private val adapter = adapter(searchList)
override fun onCreate(savedInstanceState: Bundle?) {
binding = ActivityMainBinding.inflate(layoutInflater)
super.onCreate(savedInstanceState)
setContentView(binding.root)
supportActionBar?.hide()
val search_list :RecyclerView = findViewById(R.id.search_list)
search_list.hasFixedSize()
search_list.layoutManager = LinearLayoutManager(this)
search_list.adapter = adapter
binding.searchField.addTextChangedListener(object : TextWatcher{
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
}
override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
val search : String = binding.searchField.text.toString()
//Search in Firestore
searchInFirestore(search.toLowerCase())
}
override fun afterTextChanged(p0: Editable?) {
}
})
}
private fun searchInFirestore(search: String) {
firebaseFirestore.collection("mechanic").orderBy("city").startAt(search).endAt("$search\uf8ff").get()
.addOnCompleteListener {
if(it.isSuccessful){
searchList = it.result!!.toObjects(dataClass::class.java)
adapter.searchlist =searchList
adapter.notifyDataSetChanged()
}
else{
Log.d(TAG,"Error:${it.exception!!.message}")
}
}
}
}
Adapter.kt code
class adapter(var searchlist: List<dataClass> ) : RecyclerView.Adapter<adapter.viewholder>(){
inner class viewholder(itemView: View):RecyclerView.ViewHolder(itemView) {
val mname: TextView = itemView.findViewById(R.id.name)
val mphone : TextView = itemView.findViewById(R.id.phone)
val addres: TextView = itemView.findViewById(R.id.address)
fun bind(dataClass: dataClass){
mname.text = dataClass.name
mphone.text = dataClass.phone
addres.text = dataClass.address
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): viewholder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.single_search,parent,false)
return viewholder(view)
}
override fun onBindViewHolder(holder: viewholder, position: Int) {
holder.bind(searchlist[position])
}
override fun getItemCount(): Int {
return searchlist.size
}
}
the view in which i have to bind data
<?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">
<TextView
android:id="#+id/name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="TextView"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.022" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Phone no"
app:layout_constraintBaseline_toBaselineOf="#+id/phone"
app:layout_constraintStart_toStartOf="parent" />
<TextView
android:id="#+id/phone"
android:layout_width="144dp"
android:layout_height="19dp"
android:layout_marginTop="12dp"
android:layout_marginBottom="20dp"
android:text="TextView"
app:layout_constraintBottom_toTopOf="#+id/address"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.088"
app:layout_constraintStart_toEndOf="#+id/textView2"
app:layout_constraintTop_toBottomOf="#+id/name" />
<TextView
android:id="#+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Address"
app:layout_constraintBaseline_toBaselineOf="#+id/address"
app:layout_constraintStart_toStartOf="parent" />
<TextView
android:id="#+id/address"
android:layout_width="260dp"
android:layout_height="65dp"
android:layout_marginTop="86dp"
android:text="TextView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.229"
app:layout_constraintStart_toEndOf="#+id/textView5"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Mainactivity.xml file
<?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">
<EditText
android:id="#+id/search_field"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:paddingTop="20sp"
android:text="Search here"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<androidx.recyclerview.widget.RecyclerView
android:layout_width="408dp"
android:layout_height="642dp"
android:id="#+id/search_list"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/search_field" />
</androidx.constraintlayout.widget.ConstraintLayout>
i want to implement a live search view in my app using firestore database but when i running the above code it doesn't showing any thing to me. I think there is a mistake in my adapter.kt and mainactivity.kt file. Please help me to correct it.
I am expecting to see the data while searching but it is not showing the data from firestore. I want it to be appear in search result.
dataclass.kt data class dataClass ( val name: String ="",val phone:String = "", val address : String ="" )
I think the issue is that you're setting content to binding and then not referencing the RecyclerLayout from that binding. Try using val search_list = binding.searchList instead of val search_list :RecyclerView = findViewById(R.id.search_list)

NullPointerException on RecyclerView setLayoutManager

I have faced the problem that my application will keep stopping when clicking search page fragments. I do not understand why this problem will happen? I directly used my other success code in another fragment but in this fragment suddenly appear this problem. Can somebody help me? Thank you for your help!!
My problem error :
java.lang.NullPointerException: Attempt to invoke virtual method
'void androidx.recyclerview.widget.RecyclerView.setLayoutManager(androidx.recyclerview.widget.RecyclerView$LayoutManager)'
on a null object reference at com.example.assignment_mad.Search_Page_Fragment.onViewCreated(Search_Page_Fragment.kt:153)
My main frgment ( Search_Page_Fragment ) :
package com.example.assignment_mad
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.fragment_notification_.*
class Search_Page_Fragment : Fragment() {
private lateinit var newRecyclerView: RecyclerView
private lateinit var newArrayList: ArrayList<Company_Search>
private lateinit var tempArrayList: ArrayList<Company_Search>
lateinit var imageId:Array<Int>
lateinit var job_name:Array<String>
lateinit var saveicon:Array<Int>
lateinit var company_name:Array<String>
lateinit var place:Array<String>
lateinit var salary:Array<String>
lateinit var news:Array<String>
private var layoutManager: RecyclerView.LayoutManager? = null
private var adapter: RecyclerView.Adapter<Search_Page_Adapter.MyViewHolder>? = null
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
var views =inflater.inflate(R.layout.fragment_search__page_, container, false)
newRecyclerView=views.findViewById(R.id.recyclerView_Search)
// Inflate the layout for this fragment
return views
}
override fun onViewCreated(itemView: View, savedInstanceState: Bundle?) {
imageId= arrayOf(
R.drawable.company_logo_1,
R.drawable.company_logo_2,
R.drawable.company_logo_3,
R.drawable.company_logo_4,
R.drawable.company_logo_5,
R.drawable.company_logo_6,
R.drawable.company_logo_7,
R.drawable.company_logo_8,
R.drawable.company_logo_9,
R.drawable.company_logo_10
)
job_name= arrayOf(
"Engineer",
"Computer",
"Coder",
"Teacher",
"Engineer",
"Engineer",
"Engineer",
"Engineer",
"Engineer",
"Engineer"
)
saveicon= arrayOf(
R.drawable.ic_baseline_bookmark_added_24,
R.drawable.ic_baseline_bookmark_added_24,
R.drawable.ic_baseline_bookmark_added_24,
R.drawable.ic_baseline_bookmark_added_24,
R.drawable.ic_baseline_bookmark_added_24,
R.drawable.ic_baseline_bookmark_added_24,
R.drawable.ic_baseline_bookmark_added_24,
R.drawable.ic_baseline_bookmark_added_24,
R.drawable.ic_baseline_bookmark_added_24,
R.drawable.ic_baseline_bookmark_added_24
)
company_name= arrayOf(
"Phonix Sdn Bhd",
"Computer Sdn Bhd",
"Coder",
"Teacher",
"Engineer",
"Engineer",
"Engineer",
"Engineer",
"Engineer",
"Engineer"
)
place= arrayOf(
"Kuala Lumpur",
"Kuala Lumpur",
"Selangor",
"Rimbunan",
"Kuala Lumpur",
"Kuala Lumpur",
"Kuala Lumpur",
"Kuala Lumpur",
"Kuala Lumpur",
"Kuala Lumpur"
)
salary= arrayOf(
"RM3000",
"RM4000",
"RM3500",
"RM2000",
"RM1000",
"RM3000",
"RM3000",
"RM3000",
"RM3000",
"RM3000",
)
news= arrayOf(
getString(R.string.news_a),
getString(R.string.news_b),
getString(R.string.news_c),
getString(R.string.news_d),
getString(R.string.news_e),
getString(R.string.news_f),
getString(R.string.news_g),
getString(R.string.news_h),
getString(R.string.news_i),
getString(R.string.news_j)
)
newArrayList= arrayListOf<Company_Search>()
tempArrayList= arrayListOf<Company_Search>()
getUserdata()
super.onViewCreated(itemView, savedInstanceState)
newRecyclerView.apply {
layoutManager= LinearLayoutManager(activity)
newRecyclerView.setHasFixedSize(true)
}
recyclerView.apply {
// set a LinearLayoutManager to handle Android
// RecyclerView behavior
layoutManager= LinearLayoutManager(activity)
// set the custom adapter to the RecyclerView
adapter = Search_Page_Adapter(newArrayList)
}
}
private fun getUserdata() {
for (i in imageId.indices){
val companySearch=Company_Search(imageId[i],job_name[i],saveicon[i],company_name[i],place[i],salary[i])
newArrayList.add(companySearch)
}
// tempArrayList.addAll(newArrayList)
//
// val adapter = Notification_Fragment(tempArrayList)
var adapter=Search_Page_Adapter(newArrayList)
newRecyclerView.adapter=adapter
adapter.setOnItemClickListener(object :Search_Page_Adapter.onItemClickListener{
override fun onItemClick(position: Int) {
Toast.makeText(context,"You clicked in item no . $position",Toast.LENGTH_SHORT).show()
val intent= Intent(context,Search_Page_Detail::class.java)
intent.putExtra("name",newArrayList[position].job_name)
intent.putExtra("imageId",newArrayList[position].titleImage)
intent.putExtra("news",news[position])
startActivity(intent)
}
})
}
}
The page adapter :
package com.example.assignment_mad
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.imageview.ShapeableImageView
class Search_Page_Adapter(private val companysList:ArrayList<Company_Search>):RecyclerView.Adapter<Search_Page_Adapter.MyViewHolder>() {
private var mListener:onItemClickListener?=null
interface onItemClickListener{
fun onItemClick(position: Int)
}
fun setOnItemClickListener(listener: onItemClickListener){
mListener=listener
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val itemView=LayoutInflater.from(parent.context).inflate(R.layout.list_item_search,parent,false)
return MyViewHolder(itemView,mListener)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val currentItem=companysList[position]
holder.titleImage.setImageResource(currentItem.titleImage)
holder.job_name.text=currentItem.job_name
holder.save_icon.setImageResource(currentItem.save_icon)
holder.company_name.text=currentItem.company_name
holder.place.text=currentItem.place
holder.salary.text=currentItem.salary
}
override fun getItemCount(): Int {
return companysList.size
}
//to insert the post detail
class MyViewHolder(itemView: View,listener: onItemClickListener?):RecyclerView.ViewHolder(itemView){
val titleImage:ShapeableImageView=itemView.findViewById(R.id.title_image2)
val job_name:TextView=itemView.findViewById(R.id.job_name)
val save_icon:ShapeableImageView=itemView.findViewById(R.id.save_icon)
val company_name:TextView=itemView.findViewById(R.id.company_name)
val place:TextView=itemView.findViewById(R.id.detail_place)
val salary:TextView=itemView.findViewById(R.id.detail_salary)
init {
itemView.setOnClickListener{
listener?.onItemClick(adapterPosition)
}
}
}
}
The xml file for Search_Page_Fragment :
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
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="#color/white"
tools:context=".Search_Page_Fragment">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/search_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Search Job"
android:inputType="text"
android:minHeight="48dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
<TextView
android:id="#+id/place_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/black"
android:text="Area, City or Town"
android:textSize="16sp"
android:layout_marginStart="16dp"
android:layout_marginEnd="32dp"
android:layout_marginTop="8dp"
app:layout_constraintTop_toBottomOf="#+id/search_bar"
app:layout_constraintStart_toStartOf="parent"/>
<Spinner
android:id="#+id/spinner_job"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minWidth="200dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/place_name" />
<TextView
android:id="#+id/job_specialize"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/black"
android:text="Job Specialize"
android:textSize="16sp"
android:layout_marginStart="16dp"
android:layout_marginEnd="32dp"
android:layout_marginTop="8dp"
app:layout_constraintTop_toBottomOf="#+id/search_bar"
app:layout_constraintEnd_toEndOf="parent" />
<Spinner
android:id="#+id/spinner_place"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minWidth="200dp"
app:layout_constraintTop_toBottomOf="#+id/job_specialize"
app:layout_constraintEnd_toEndOf="parent"
/>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView_Search"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="108dp"
app:layout_constraintTop_toBottomOf="#+id/spinner_job"
tools:layout_editor_absoluteX="-16dp"
tools:listitem="#layout/list_item_search" />
</androidx.constraintlayout.widget.ConstraintLayout>
</FrameLayout>
The list_item_search_xml :
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_margin="8dp">
<com.google.android.material.imageview.ShapeableImageView
android:layout_width="80dp"
android:layout_height="80dp"
android:id="#+id/title_image2"
android:scaleType="centerCrop"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:shapeAppearanceOverlay="#style/RoundCorner"
android:src="#drawable/company_logo_1"/>
<TextView
android:id="#+id/job_name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textColor="#color/blue"
android:text="Gradute Engineer"
android:textSize="20sp"
android:textStyle="bold"
android:layout_marginStart="16dp"
android:layout_marginEnd="32dp"
android:layout_marginTop="8dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/title_image2"/>
<ImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:id="#+id/save_icon"
android:scaleType="centerCrop"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="#+id/title_image2"
android:layout_marginEnd="32dp"
app:shapeAppearanceOverlay="#style/RoundCorner"
android:src="#drawable/ic_baseline_bookmark_added_24"/>
<TextView
android:id="#+id/company_name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textColor="#color/black"
android:text="Neric Compat"
android:textSize="18sp"
android:layout_marginStart="16dp"
android:layout_marginEnd="32dp"
android:layout_marginTop="8dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/job_name"/>
<TextView
android:id="#+id/detail_place"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textColor="#color/black"
android:text="Petaling Jaya"
android:textSize="16sp"
android:textStyle="bold"
android:layout_marginStart="16dp"
android:layout_marginEnd="32dp"
android:layout_marginTop="8dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/company_name"/>
<TextView
android:id="#+id/detail_salary"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:textColor="#color/black"
android:text="MYR 3,700 - 4,300 /Month"
android:textSize="16sp"
android:layout_marginStart="16dp"
android:layout_marginEnd="32dp"
android:layout_marginTop="8dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/detail_place"/>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_margin="8dp"
style="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/detail_salary"
android:background="#color/underline"/>
</androidx.constraintlayout.widget.ConstraintLayout>
Your NullPointerException indicates that when this line of code is reached...
layoutManager= LinearLayoutManager(activity)
...that your newRecyclerView is null. Are you sure that you have the right resource ID here when you attempt to set it?
newRecyclerView=views.findViewById(R.id.recyclerView_Search)
Try using the debugger and set a breakpoint on these two lines to confirm is newRecyclerView is indeed null.
You must assign the RecyclerView a LayoutManager. Since you have both of them, place this line as the last statement of recyclerView.apply { … } block(s):
setLayoutManager(layoutManager)
// ↑↑↑↑↑↑↑↑↑↑↑↑↑
// Your LayoutManager

Spinner doesn't display items. I'm making program for inventorization now. I get data from API. And I have the problem. Spinner doesn't show items

Spinner doesn't display items. I'm making program for inventorization now. I get data from API. And I have the problem. Spinner doesn't show items. I add items to ArrayList and then add this list to spinner adapter. I've tried a lot of thing that i found at stackoverflow and another sites. But nothing helps me.
Code:
activity_add_classes.xml:
<pre><code>
<TextView
android:id="#+id/add_class_label"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Добавить кабинет"
android:textAlignment="center"
android:textColor="#color/black"
android:textSize="25sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="25dp"
/>
<EditText
android:id="#+id/class_number_add"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="#id/add_class_label"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:layout_margin="16dp"
android:hint="Номер класса"
android:textSize="20sp"
android:singleLine="true"
android:maxLength="3"
android:digits="1234567890"
/>
<Spinner
android:id="#+id/corps_spinner"
app:layout_constraintTop_toBottomOf="#id/class_number_add"
app:layout_constraintEnd_toEndOf="parent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="#array/corps"
app:layout_constraintStart_toStartOf="parent"
android:layout_margin="16dp"
/>
<Spinner
android:id="#+id/inventories_spinner"
android:layout_width="match_parent"
android:layout_height="75dp"
app:layout_constraintTop_toBottomOf="#id/corps_spinner"
app:layout_constraintStart_toStartOf="parent"
android:layout_margin="16dp"
android:spinnerMode="dropdown"
app:layout_constraintEnd_toEndOf="parent"
/>
<EditText
android:id="#+id/count_of_inventory"
android:layout_width="100dp"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="#id/inventories_spinner"
app:layout_constraintStart_toStartOf="parent"
android:layout_margin="16dp"
android:maxLength="2"
android:digits="1234567890"
android:singleLine="true"
/>
<Button
android:id="#+id/add_inventory_list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Добавить"
app:layout_constraintTop_toBottomOf="#id/inventories_spinner"
android:layout_margin="16dp"
app:layout_constraintEnd_toEndOf="parent"
/>
AddClassesActivity.kt:
enter code here
package com.example.inventorizationmpt
class AddClassesActivity : AppCompatActivity() {
lateinit var inventoriesSpinner: Spinner
lateinit var listInventory : ArrayList
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_add_classes)
listInventory = ArrayList()
inventoriesSpinner = findViewById(R.id.inventories_spinner)
getInventories()
spinAdapt()
}
fun spinAdapt(){
val spinnerAdapter = ArrayAdapter(this#AddClassesActivity, android.R.layout.simple_spinner_item,listInventory)
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spinnerAdapter.notifyDataSetChanged()
inventoriesSpinner.adapter = spinnerAdapter
}
fun getInventories(){
val inventorizationService = ServiceBuilder.buildService(InventorizationService::class.java)
val requestCall = inventorizationService.getInventoriesList()
requestCall.enqueue(object : Callback>{
override fun onResponse(
call: Call>,
response: Response>
) {
if (response.isSuccessful){
val listForSpinner = response!!.body()
for (i in 0..listForSpinner!!.size - 1){
listInventory.add(
ItemOfInventory(
listForSpinner[i].id_Inventory,
listForSpinner[i].inventory_Name
)
)
}
}else {
Toast.makeText(this#AddClassesActivity, "Что-то пошло не так. Ошибка со стороны сервера", Toast.LENGTH_LONG).show()
}
}
override fun onFailure(call: Call>, t: Throwable) {
Toast.makeText(this#AddClassesActivity, "Что-то пошло не так. Ошибка со стороны сервера", Toast.LENGTH_LONG).show()
}
})
}
}

How to fix Parameter specified as non-null is null on rotating screen in a Fragment while creating a Spinner in Kotlin?

Hello everyone in my fragment, i have added a spinner in my fragment and little bit of code to calculate moles but when i rotate screen it crashes and throw an error by i don't know why it crashes , When try to check for Non-null object i don't What that is the cause of error , Here is the error :
java.lang.IllegalArgumentException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull
Here is my first fragment file :
private var mListener: OnFragmentInteractionListener? = null
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
return inflater!!.inflate(R.layout.fragment_first, container, false)
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
//activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
/*Find the id of spinner*/
val spinner = lol
/*set an adapter with strings array*/
spinner.adapter = ArrayAdapter(activity, R.layout.support_simple_spinner_dropdown_item, resources.getStringArray(R.array.atoms)) as SpinnerAdapter
/*set click listener*/
spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
val num = when (spinner.selectedItem.toString()) {
"H" -> editText.setText("1")
"He" -> editText.setText("4")
"C" -> editText.setText("12")
"O" -> editText.setText("16")
else -> editText.setText("")
}
}
override fun onNothingSelected(parent: AdapterView<*>) {
/*Do something if nothing selected*/
}
}
button.setOnClickListener {
if (
editText2.text.toString().length > 0 &&
editText.text.toString().length > 0) {
val num2 = editText.text.toString().toDouble()
val num1 = editText2.text.toString().toDouble()
val num = num1/num2
textView.setText("$num moles")
}
else {
textView.setText("Please Enter a correct value")
}
}
}
Here is my fragment_first.xml file :
<android.support.constraint.ConstraintLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="#+id/textView"
android:layout_width="294dp"
android:layout_height="80dp"
android:layout_weight="1"
android:text="Amswer : No of Moles"
android:textAlignment="center"
android:textSize="20sp"
app:layout_anchorGravity="right|top"
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.556" />
<TextView
android:id="#+id/textView1"
android:layout_width="143dp"
android:layout_height="46dp"
android:layout_weight="1"
android:text="Amount in Grams "
android:textAlignment="center"
android:textSize="20sp"
app:layout_anchorGravity="left|bottom"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.066"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.305" />
<Spinner
android:id="#+id/lol"
android:layout_width="145dp"
android:layout_height="57dp"
app:layout_anchorGravity="left|top"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.07"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.136" />
<Button
android:id="#+id/button"
android:layout_width="138dp"
android:layout_height="43dp"
android:text="Calculate"
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.788" />
<EditText
android:id="#+id/editText"
android:layout_width="148dp"
android:layout_height="57dp"
android:ems="10"
android:hint="Gram"
android:inputType="numberDecimal|number"
app:layout_anchorGravity="bottom|center"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.762"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.137" />
<EditText
android:id="#+id/editText2"
android:layout_width="148dp"
android:layout_height="57dp"
android:ems="10"
android:hint="Gram"
android:inputType="numberDecimal|number"
app:layout_anchorGravity="center_horizontal|center"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.716"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.288" />
</android.support.constraint.ConstraintLayout>
Add ? in
view = View?
Here is code
spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>, view: View?, position: Int, id: Long) {
val num = when (spinner.selectedItem.toString()) {
"H" -> editText.setText("1")
"He" -> editText.setText("4")
"C" -> editText.setText("12")
"O" -> editText.setText("16")
else -> editText.setText("")
}
}
It is correct, annotating the "view" parameter as nullable does appear to correct the issue.
It appears that the Kotlin generated code is incorrect as the auto-generated code marks "view" without the nullable attribute.

How to use an ArrayAdapter in a Fragment with Kotlin

I am trying to to create a Spinner inside a Fragment but I am getting error in the ArrayAdapter constructor call. I don't know why, but it has a red underline. Other than that, there is no error. When I'm using the same ArrayAdapter in an Activity it works, but in a Fragment, it gives an error.
My FirstFragment.kt:
class FirstFragment : Fragment() {
private var mListener: OnFragmentInteractionListener? = null
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
return inflater!!.inflate(R.layout.fragment_first, container, false)
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
/*Find the id of spinner*/
val spinner = lol
/*set an adapter with strings array*/
spinner.adapter = ArrayAdapter(this, R.layout.support_simple_spinner_dropdown_item, resources.getStringArray(R.array.atoms)) as SpinnerAdapter?
/*set click listener*/
spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
val num = when (spinner.selectedItem.toString()) {
"H" -> editText.setText("1")
"He" -> editText.setText("4")
"C" -> editText.setText("12")
"O" -> editText.setText("16")
else -> editText.setText("")
}
}
override fun onNothingSelected(parent: AdapterView<*>) {
/*Do something if nothing selected*/
}
}
button.setOnClickListener {
if (
editText2.text.toString().length > 0 &&
editText.text.toString().length > 0) {
val num2 = editText.text.toString().toDouble()
val num1 = editText2.text.toString().toDouble()
val num = num1/num2
textView.setText("$num moles")
}
else {
textView.setText("Please Enter a correct value")
}
}
}
}
My fragment_first.xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="com.a3.aakap.ftrial.FirstFragment">
<android.support.constraint.ConstraintLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="#+id/textView"
android:layout_width="294dp"
android:layout_height="80dp"
android:layout_weight="1"
android:text="Amswer : No of Moles"
android:textAlignment="center"
android:textSize="20sp"
app:layout_anchorGravity="right|top"
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.556" />
<TextView
android:id="#+id/textView1"
android:layout_width="143dp"
android:layout_height="46dp"
android:layout_weight="1"
android:text="Amount in Grams "
android:textAlignment="center"
android:textSize="20sp"
app:layout_anchorGravity="left|bottom"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.066"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.305" />
<Spinner
android:id="#+id/lol"
android:layout_width="145dp"
android:layout_height="57dp"
app:layout_anchorGravity="left|top"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.07"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.136" />
<Button
android:id="#+id/button"
android:layout_width="138dp"
android:layout_height="43dp"
android:text="Calculate"
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.788" />
<EditText
android:id="#+id/editText"
android:layout_width="148dp"
android:layout_height="57dp"
android:ems="10"
android:hint="Gram"
android:inputType="numberDecimal|number"
app:layout_anchorGravity="bottom|center"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.762"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.137" />
<EditText
android:id="#+id/editText2"
android:layout_width="148dp"
android:layout_height="57dp"
android:ems="10"
android:hint="Gram"
android:inputType="numberDecimal|number"
app:layout_anchorGravity="center_horizontal|center"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.716"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.288" />
</android.support.constraint.ConstraintLayout>
</FrameLayout>
The problem is in this constructor call:
spinner.adapter = ArrayAdapter(
this,
R.layout.support_simple_spinner_dropdown_item,
resources.getStringArray(R.array.atoms)
) as SpinnerAdapter
The argument this must be a reference to a Context, and a Fragment is not a Context. In an Activity it works because an Activity is a Context.
The solution is to replace this with activity:
spinner.adapter = ArrayAdapter(
activity,
R.layout.support_simple_spinner_dropdown_item,
resources.getStringArray(R.array.atoms)
)
i came here looking for some answers but i found my solution better and shorter i guess and complete the mission i'll just drop it here in case
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
getCates()
}
the function
private fun getCates() {
val categories = MyApplication().getCategories()
val adapter = ArrayAdapter(requireContext(), R.layout.list_item, categories)
(binding.autocomplete as? AutoCompleteTextView)?.setAdapter(adapter)
binding.autocomplete.setOnItemClickListener { _, _, i, _ ->
category = categories[i]
Log.d(TAG,"$category")
}
}
PS : i get the list items from firebase you can add items lovaly

Categories

Resources