There is a type mismatch when initializing b as intent.extra. Though b is of type Bundle? and intent.extra doesn't take null values and also Bundle can't be null.
Please suggest a solution for this issue. The app keeps on crashing when installed on an android phone and ready to run.
The following code snippet present in the code body is showing only warning but ends up in application crash on start only.
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.drawable.BitmapDrawable
import android.os.Bundle
import android.provider.MediaStore
import android.support.design.widget.Snackbar
import android.support.design.widget.NavigationView
import android.support.v4.view.GravityCompat
import android.support.v7.app.ActionBarDrawerToggle
import android.support.v7.app.AppCompatActivity
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.Toast
import com.example.debo.kickv01.R.id.lvTweets
import kotlinx.android.synthetic.main.activity_navig.*
import kotlinx.android.synthetic.main.app_bar_navig.*
import com.example.debo.kickv01.saved
import com.example.debo.kickv01.login as lg
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.storage.FirebaseStorage
import kotlinx.android.synthetic.main.activity_login.*
import kotlinx.android.synthetic.main.activity_saved.view.*
import java.io.ByteArrayOutputStream
import java.text.SimpleDateFormat
import java.util.*
class navig : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {
private var mAuth: FirebaseAuth?=null
private var database= FirebaseDatabase.getInstance()
private var myRef = database.reference
var list_T=ArrayList<ticket>()
var adaptor:MyPrjAdaptor?=null
var UserUID:String?=null
var myEmail:String?=null
// var b:Bundle= intent.extras
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_navig)
val toolbar= null
var b:Bundle = intent.extras
myEmail = b.getString("email")
UserUID = b.getString("uid")
list_T.add(ticket("0","him","url","add"))
list_T.add(ticket("0","him","url","debo"))
list_T.add(ticket("0","him","url","debo_2"))
adaptor=MyPrjAdaptor(this,list_T)
lvTweets.adapter=adaptor
fab.setOnClickListener { view ->
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show()
}
val toggle = ActionBarDrawerToggle(
this, drawer_layout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close)
drawer_layout.addDrawerListener(toggle)
toggle.syncState()
nav_view.setNavigationItemSelectedListener(this)
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
// Handle navigation view item clicks here.
when (item.itemId) {
R.id.nav_home -> {
// Handle the camera action
var intent = Intent(this, navig::class.java)
startActivity(intent)
}
R.id.nav_explore -> {
var intent = Intent(this, explore::class.java)
startActivity(intent)
}
R.id.nav_Saved -> {
var intent = Intent(this, saved::class.java)
startActivity(intent)
}
R.id.nav_actions -> {
var intent = Intent(this, actions::class.java)
startActivity(intent)
}
R.id.nav_login -> {
var intent = Intent(this, com.example.debo.kickv01.login::class.java)
startActivity(intent)
}
}
drawer_layout.closeDrawer(GravityCompat.START)
return true
}
inner class MyPrjAdaptor: BaseAdapter{
var listNotesAdaptor= ArrayList<ticket>()
var context:Context?=null
constructor(context: Context,listNotesAdaptor: ArrayList<ticket>):super(){
this.listNotesAdaptor=listNotesAdaptor
this.context=context
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
var myTweet=listNotesAdaptor[position]
if (myTweet.tweetPersonUID.equals("add")) {
var myView = layoutInflater.inflate(R.layout.activity_saved, null)
myView.etAttach.setOnClickListener {
loadImage()
}
myView.etPost.setOnClickListener {
myRef.child("posts").push().setValue(PostInfo(UserUID!!,
myView.etProject.text.toString(),
myView.etDescription.text.toString(),
DownloadURL!!))
}
return myView
}else{
var myView = layoutInflater.inflate(R.layout.activity_explore, null)
return myView
}
}
override fun getItem(position: Int): Any {
return listNotesAdaptor[position]
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun getCount(): Int {
return listNotesAdaptor.size
}
}
override fun onBackPressed() {
if (drawer_layout.isDrawerOpen(GravityCompat.START)) {
drawer_layout.closeDrawer(GravityCompat.START)
} else {
super.onBackPressed()
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.navig, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
when (item.itemId) {
R.id.action_settings -> return true
else -> return super.onOptionsItemSelected(item)
}
}
var PICK_IMAGE_CODE=123
fun loadImage(){
var intent=Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
startActivityForResult(intent, PICK_IMAGE_CODE)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?)
{
super.onActivityResult(requestCode, resultCode, data)
if(requestCode==PICK_IMAGE_CODE && resultCode== Activity.RESULT_OK && data!=null){
val selectedImage=data.data
val filePathColum = arrayOf(MediaStore.Images.Media.DATA)
val cursor= contentResolver.query(selectedImage,filePathColum,null,null,null)
cursor.moveToFirst()
val columIndex= cursor.getColumnIndex(filePathColum[0])
val picturepath= cursor.getString(columIndex)
cursor.close()
UploadImage(BitmapFactory.decodeFile(picturepath))
}
}
var DownloadURL:String?=null
fun UploadImage(bitmap: Bitmap){
var currentUser= mAuth!!.currentUser
val storage = FirebaseStorage.getInstance()
val storageRef= storage.getReferenceFromUrl("gs://kick-13840.appspot.com")
val df= SimpleDateFormat("ddMMyyHHmmss")
val dataobj= Date()
val imagePath= SplitString(myEmail!!) + "."+ df.format(dataobj)+ ".jpg"
val ImageRef= storageRef.child("imagePost/"+imagePath)
val baos= ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.JPEG,100,baos)
val data=baos.toByteArray()
val uploadTask=ImageRef.putBytes(data)
uploadTask.addOnFailureListener{
Toast.makeText(applicationContext,"fail to upload", Toast.LENGTH_LONG).show()
}.addOnSuccessListener { taskSnapshot ->
DownloadURL = taskSnapshot.storage.downloadUrl.toString()
}
}
fun SplitString(email: String):String{
val split= email.split("#")
return split[0]
}
}
b is of type Bundle whereas intent.extras returns Bundle? (Intent.getExtras() is annotated with #Nullable if you look at the code for it) as indicated by the IDE. You need to either use the not-null assertion operator, !!, or change b to type Bundle?.
Related
I am simply trying to setup the ClickListener for changing the user name. Google's tutorials emphasize fragments, which I will do later. Based on what I've seen in other examples and the Android documentation, I thought I had the View Binding set up properly. I don't have enough information to understand why I see a list of copies of the activity screen inside the RecyclerView.
UserListAdapter.kt
package com.neillbarrett.debitsandcredits
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.neillbarrett.debitsandcredits.database.UsersTable
import com.neillbarrett.debitsandcredits.databinding.ActivityManageUsersBinding
val inAdapter: String = "In UserListAdapter "
class UserListAdapter(private val userSelect: (UsersTable?) -> Unit) :
ListAdapter<UsersTable, UserListAdapter.UserViewHolder>(UsersComparator()) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UserListAdapter.UserViewHolder {
Log.w(inAdapter,"OnCreateViewHolder started")
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.activity_manage_users, parent, false)
return UserViewHolder.create(parent)
}
class UserViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bind(usersTable: UsersTable?, userSelect: (UsersTable?) -> Unit) {
Log.w(inAdapter,"UserViewHolder started")
itemView.setOnClickListener { View.OnClickListener {
/* if (View.) { }*/
val nameSelected = userSelect(usersTable)
//userSelect(usersTable)
//need to assign the result of the clicklistener to the editText
//binding.etEditName.setText(R.layout.activity_list_of_users.toString())
}}
}
companion object {
fun create(parent: ViewGroup) : UserViewHolder {
Log.w(inAdapter,"Companion object 'Create' function started")
val view: View = LayoutInflater.from(parent.context)
.inflate(R.layout.activity_manage_users, parent, false)
return UserViewHolder(view)
}
}
}
override fun onBindViewHolder(holder: UserViewHolder, position: Int) {
Log.w(inAdapter,"OnBindViewHolder started")
val current = getItem(position)
holder.bind(current, userSelect)
}
class UsersComparator : DiffUtil.ItemCallback<UsersTable>() {
override fun areItemsTheSame(oldItem: UsersTable, newItem: UsersTable): Boolean {
Log.w(inAdapter,"areItemsTheSame function started")
return oldItem == newItem
}
override fun areContentsTheSame(oldItem: UsersTable, newItem: UsersTable): Boolean {
Log.w(inAdapter,"areContentsTheSame function started")
return oldItem.userName == newItem.userName
}
}
}
ManageUsers.kt
package com.neillbarrett.debitsandcredits
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.activity.viewModels
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.neillbarrett.debitsandcredits.database.CreditsAndDebitsApp
import com.neillbarrett.debitsandcredits.database.UsersTable
import com.neillbarrett.debitsandcredits.databinding.ActivityManageUsersBinding
class ManageUsers : AppCompatActivity() {
lateinit var binding: ActivityManageUsersBinding
lateinit var recyclerView: RecyclerView
lateinit var editTextAddUser: EditText
lateinit var editTextChangeUser: EditText
lateinit var newUser: String
var userSelect: ((UsersTable?) -> Unit) = {}
var position: Long = 0
val inWhichActivity: String = "In ManageUsers"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityManageUsersBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
//setContentView(R.layout.activity_manage_users)
Log.w(inWhichActivity, "Setting up userViewModel & repository")
val userViewModel: UserViewModel by viewModels {
UserViewModelFactory((application as CreditsAndDebitsApp).repository)
}
recyclerView = findViewById(R.id.rec_view_userList)
editTextAddUser = findViewById(R.id.et_AddUser)
editTextChangeUser = findViewById(R.id.et_Edit_Name)
val adapter = UserListAdapter(userSelect)
binding.recViewUserList.adapter = adapter
recyclerView.adapter = adapter
recyclerView.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
userViewModel.allUsers.observe(this, Observer() {user ->
Log.w(inWhichActivity,"Starting Observer")
user?.let { adapter.submitList(it) }
Log.w(inWhichActivity, "Started Observer")
})
val btnAddUser = findViewById<Button>(R.id.btn_AddUser)
btnAddUser.setOnClickListener {
Log.w(inWhichActivity,"Started btnAddUser.setOnClickListener")
if (TextUtils.isEmpty(editTextAddUser.text)) {
Toast.makeText(this, "User name cannot be empty", Toast.LENGTH_SHORT).show()
} else {
newUser = editTextAddUser.text.toString()
// Log.w("Add user button", "Username put into newUser")
userViewModel.insertUser(UsersTable(0, newUser))
// Toast.makeText(this, "Username added to table", Toast.LENGTH_SHORT).show()
// Log.w("Add user button", "Username added to table")
}
}
val btnChangeUser = findViewById<Button>(R.id.btn_ChangeUserName)
btnChangeUser.setOnClickListener {
Log.w(inWhichActivity,"Started btnChangeUser.setOnClickListener")
Toast.makeText(this, "Selected position is ${recyclerView.getChildAdapterPosition(it)}", Toast.LENGTH_SHORT).show()
/* if (recyclerView.getChildAdapterPosition(it) == -1) {
Toast.makeText(this, "Select a name.", Toast.LENGTH_SHORT).show()
} else {
if (editTextChangeUser.text.toString() == recyclerView.adapter.toString()) {
Toast.makeText(this, "Name has not been changed.", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(this, "Name would have been changed.", Toast.LENGTH_SHORT).show()
val rvItemRecId: Long
rvItemRecId = adapter.getItemId(position.toInt())
userViewModel.updateUser(UsersTable(rvItemRecId.toInt(), adapter.toString()))
}
}*/
}
}
}
UserViewModel.kt
package com.neillbarrett.debitsandcredits
import android.util.Log
import androidx.lifecycle.*
import com.neillbarrett.debitsandcredits.database.UsersTable
import kotlinx.coroutines.launch
import java.lang.IllegalArgumentException
val inViewModel: String = "In UserViewModel "
class UserViewModel(private val repository: UserRepository) : ViewModel() {
// Using LiveData and caching what allWords returns has several benefits:
// - We can put an observer on the data (instead of polling for changes) and only update the
// the UI when the data actually changes.
// - Repository is completely separated from the UI through the ViewModel.
val allUsers: LiveData<List<UsersTable>> = repository.allUsers.asLiveData()
/**
* Launching a new coroutine to insert the data in a non-blocking way
*/
fun insertUser(user: UsersTable) = viewModelScope.launch {
repository.insertUser(user)
Log.w(inViewModel,"insertUser called")
//repository.insertUser(usersTable = List<UsersTable>())
//repository.insertUser(UsersTable(0, userName = user.userName))
}
fun updateUser(user: UsersTable) = viewModelScope.launch {
repository.updateUser(user)
Log.w(inViewModel, "updateUser called")
}
fun deleteUser(user: UsersTable) = viewModelScope.launch {
repository.deleteUser(user)
Log.w(inViewModel, "deteUser called")
}
}
class UserViewModelFactory(private val repository: UserRepository) : ViewModelProvider.Factory{
override fun <T : ViewModel> create(modelClass: Class<T>): T {
Log.w(inViewModel,"UserViewModelFactory called")
if (modelClass.isAssignableFrom(UserViewModel::class.java)) {
#Suppress("UNCHECKED_CAST")
return UserViewModel(repository) as T
}
throw IllegalArgumentException("Unknown ViewModel class")
}
}
I have been trying to call a function from fragment to adapter, but I can't approach it right.
I want to invisible the button present in the fragment from adapter.
**My Adapter Code:**
package com.littleboo.brandlogo.Adapters
import android.R
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.net.Uri
import android.os.Build
import android.os.VibrationEffect
import android.os.Vibrator
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.core.content.ContextCompat.getSystemService
import androidx.recyclerview.widget.RecyclerView
import com.littleboo.brandlogo.Fragments.QuizFragment
import com.littleboo.brandlogo.MainActivity
import com.littleboo.brandlogo.Models.Question
import com.littleboo.brandlogo.databinding.ActivityMainBinding.inflate
import com.littleboo.brandlogo.databinding.FragmentQuizBinding
import kotlinx.coroutines.NonDisposableHandle.parent
class QuestionAdap(val context: Context, val question: Question) :
RecyclerView.Adapter<QuestionAdap.OptionViewHolder>() {
var index = 1
var score = 0
val animShake: Animation = AnimationUtils.loadAnimation(context, com.littleboo.brandlogo.R.anim.shake)
private var options: List<String> = listOf(question.option1, question.option2, question.option3, question.option4)
inner class OptionViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView){
var optionView = itemView.findViewById<TextView>(com.littleboo.brandlogo.R.id.quiz_option)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): OptionViewHolder {
val view = LayoutInflater.from(context).inflate(com.littleboo.brandlogo.R.layout.quizoptions, parent, false)
return OptionViewHolder(view)
}
override fun onBindViewHolder(holder: OptionViewHolder, position: Int) {
holder.optionView.text = options[position]
holder.itemView.setOnClickListener {
question.userAnswer = options[position]
notifyDataSetChanged()
}
if(question.userAnswer == options[position] && question.userAnswer == question.answer){
holder.itemView.setBackgroundResource(com.littleboo.brandlogo.R.drawable.option_item_selected_bg)
score += 10
Toast.makeText(context,"Score is $score", Toast.LENGTH_SHORT).show()
}
else if(question.userAnswer == options[position] && question.userAnswer != question.answer){
holder.itemView.setBackgroundResource(com.littleboo.brandlogo.R.drawable.wrong_option_item_selected_bg)
holder.itemView.startAnimation(animShake)
}
else{
holder.itemView.setBackgroundResource(com.littleboo.brandlogo.R.drawable.non_option_item_selected_bg)
}
}
override fun getItemCount(): Int {
return options.size
}
}
My Quiz Fragment Code:
package com.littleboo.brandlogo.Fragments
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.CircularProgressDrawable
import com.bumptech.glide.Glide
import com.google.firebase.firestore.FirebaseFirestore
import com.littleboo.brandlogo.Adapters.QuestionAdap
import com.littleboo.brandlogo.Models.Question
import com.littleboo.brandlogo.Models.quizmodel
import com.littleboo.brandlogo.R
import com.littleboo.brandlogo.databinding.FragmentQuizBinding
class QuizFragment : Fragment(){
lateinit var binding: FragmentQuizBinding
var quizzes: MutableList<quizmodel>? = null
private var questions = mutableMapOf<String, Question>()
private lateinit var mArraylist: ArrayList<Question>
var index = 1
private lateinit var mfirestore: FirebaseFirestore
private lateinit var mrecycler: RecyclerView
lateinit var myadapter: QuestionAdap
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentQuizBinding.inflate(layoutInflater)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
mrecycler = binding.optionList
mrecycler.layoutManager
myadapter = QuestionAdap(requireContext(),Question())
mArraylist = arrayListOf()
questions.map { it.key to it.value }.shuffled().toMap()
setUpFirestore()
setUpEventListener()
}
override fun onDestroy() {
super.onDestroy()
mfirestore.terminate()
// finish()
}
private fun setUpEventListener() {
binding.nextbtn.setOnClickListener {
index++
bindViews()
}
// binding.btnSubmit.setOnClickListener {
// Log.d("FINALQUIZ", questions.toString())
// val intent = Intent(this, ResultActivity::class.java)
// val json = Gson().toJson(quizzes!![0])
// intent.putExtra("QUIZ", json)
// startActivity(intent)
// finish()
// }
}
private fun setUpFirestore() {
mfirestore = FirebaseFirestore.getInstance()
val quizTitle = activity?.intent?.getStringExtra("title")
if (quizTitle != null) {
mfirestore.collection("Quizes").whereEqualTo("title", quizTitle)
.get()
.addOnSuccessListener {
if (it != null && !it.isEmpty) {
quizzes = it.toObjects(quizmodel::class.java)
questions = quizzes!![0].questions
shuffle()
bindViews()
}
}
}
}
private fun bindViews() {
// btnPrevious.visibility = View.GONE
// binding.btnSubmit.visibility = View.GONE
// binding.btnNext.visibility = View.GONE
// if (index == 1) { //first question
// binding.btnNext.visibility = View.VISIBLE
// } else if (index == questions!!.size) { // last question
// binding.btnSubmit.visibility = View.VISIBLE
//// btnPrevious.visibility = View.VISIBLE
// } else { // Middle
//// btnPrevious.visibility = View.VISIBLE
// binding.btnNext.visibility = View.VISIBLE
// }
val circularProgressDrawable = CircularProgressDrawable(requireContext())
circularProgressDrawable.strokeWidth = 8f
// circularProgressDrawable.colorFilter = ("#ac5fe1")
circularProgressDrawable.centerRadius = 30f
circularProgressDrawable.start()
val question = questions!!["question$index"]
question?.let {
Glide.with(this).load(it.imagequiz).placeholder(circularProgressDrawable).into(binding.imagequiz)
val optionAdapter = QuestionAdap(requireContext(), it)
mrecycler.layoutManager = LinearLayoutManager(requireContext())
mrecycler.adapter = optionAdapter
mrecycler.setHasFixedSize(true)
}
}
private fun shuffle() {
val keys = questions.keys.toMutableList().shuffled()
val values = questions.values.toMutableList().shuffled()
keys.forEachIndexed { index, key ->
questions[key] = values[index]
}
}
}
I tried calling fragment in adapter like:
QuizFragment().binding.btnxt.visibility = View.Visible
in BindViewHolder function.
Thank You
You can use kotlin lambda function to achieve it. Like this
class QuestionAdap(val context: Context, val question: Question, var onItemClicked: ((boolean) -> Unit))
call onItemClicked in your adapter where you want it
and in fragment
myadapter = QuestionAdap(requireContext(),Question()) { boolean ->
if (boolean) {
//hide/show
} else {
//hide/show
}
}
You can use the Callback functions of kotlin in your fragment, which will be passed into your adapter. So whenever you invoke that callback from your adapter, it will be triggered in your fragment.
Step 1: Create a method like the one below in your fragment.
private fun showHideButtonFromAdapter (
isButtonVisible: Boolean
) {
// set your button visibility according to isButtonVisible value.
}
Step 2: pass a method from your fragment to adapter as argument
val adapter = YourAdapter(::showHideButtonFromAdapter)
// set above adapter in your recycler view.
Step 3: In your adapter invoke that callback function like the one below.
class ColorPickerAdapter constructor(
private val onItemClicked: (Boolean) -> Unit
) : RecyclerView.Adapter<YourAdapter.ViewHolder>() {
// your other adapter methods here
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
onItemClicked.invoke(pass true or false as per your requirement)
// above invocation will trigger an event in the fragment.
}
}
In your adapter there need to be instance of your fragment, so change it like:
class QuestionAdap(val context: Context, val question: Question, fragment: Fragment) :
RecyclerView.Adapter<QuestionAdap.OptionViewHolder>() {
Then you can call your fragment by simply writing fragment in your adapter like:
override fun onBindViewHolder(holder: OptionViewHolder, position: Int) {
holder.optionView.text = options[position]
holder.itemView.setOnClickListener {
question.userAnswer = options[position]
notifyDataSetChanged()
}
//Example
fragment.shuffle()
And you need to send this fragment instance when you create it's adapter, so in your fragment use this:
myadapter = QuestionAdap(requireContext(),Question(), this)
I am trying to build an app that uses the youtube API. I need to call the search API, whenever the user searches for something and then display the results in a new activity(SearchResultsActivity). However the scenario I get is that my app, rather than opening the SearchResultsActivity gets redirected to the MainActivity.
The scenario is recorded, and can be better understood through this https://drive.google.com/file/d/1WESzXbRbjhmKCY1gfUq1d2gllIEsILCf/view?usp=sharing.
I want to know what is causing the SearchResultsActivity to be paused by itself and MainActivity being restarted instead. I tried logging the lifecycles to know what was happening and I found this:
Also Search box activity here means the SearchActivity:
package com.example.mytube.UI
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.mytube.R
import com.example.mytube.adapters.SearchedHistoryAdapter
import com.example.mytube.db.SearchDatabase
import com.example.mytube.repository.VideosRepository
class SearchActivity : AppCompatActivity() {
lateinit var searchAdapter: SearchedHistoryAdapter
lateinit var viewModel: VideosViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_search)
val repository = VideosRepository(SearchDatabase.getSearchDatabase(this))
val viewModelFactory = VideosViewModelProviderFactory(repository)
viewModel = ViewModelProvider(this,viewModelFactory).get(VideosViewModel::class.java)
val recyclerView = findViewById<RecyclerView>(R.id.searched_terms)
searchAdapter = SearchedHistoryAdapter()
recyclerView.apply {
adapter = searchAdapter
layoutManager = LinearLayoutManager(this#SearchActivity)
}
val backButton = findViewById<ImageView>(R.id.ivGoback)
backButton.apply {
setOnClickListener {
finish()
}
}
val searchBar = findViewById<EditText>(R.id.search_box)
val searchBtn = findViewById<ImageView>(R.id.ivSearch)
searchBtn.setOnClickListener {
if (searchBar.text.toString().isNotEmpty()) {
viewModel.insertSearchItem(searchBar.text.toString())
val intent = Intent(applicationContext, SearchResultsActivity::class.java)
intent.putExtra("searchQuery", searchBar.text)
startActivity(intent)
}
}
searchBar.setOnKeyListener(View.OnKeyListener{v, keyCode, event ->
if (event.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) {
if (searchBar.text.toString().isNotEmpty()) {
viewModel.insertSearchItem(searchBar.text.toString())
}
return#OnKeyListener true
}
return#OnKeyListener false
})
viewModel.getSearchHistory().observe(this, Observer { searchItems ->
searchAdapter.differ.submitList(searchItems)
})
}
override fun onPause() {
super.onPause()
Log.d("searched", "Search box activity paused")
}
override fun onStop() {
super.onStop()
Log.d("searched", "Search box activity stopped")
}
override fun onDestroy() {
super.onDestroy()
Log.d("searched", "Search box activity destroyed")
}
}
The SearchResultsActivity:
package com.example.mytube.UI
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.AbsListView
import android.widget.ProgressBar
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.mytube.R
import com.example.mytube.adapters.VideosAdapter
import com.example.mytube.db.SearchDatabase
import com.example.mytube.repository.VideosRepository
import com.example.mytube.util.Resource
class SearchResultsActivity : AppCompatActivity() {
lateinit var viewModel: VideosViewModel
lateinit var videosAdapter: VideosAdapter
var searchQuery = ""
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_search_results)
searchQuery = intent.getStringExtra("searchQuery").toString()
val repository = VideosRepository(SearchDatabase.getSearchDatabase(this))
val viewModelFactory = VideosViewModelProviderFactory(repository)
viewModel = ViewModelProvider(this,viewModelFactory).get(VideosViewModel::class.java)
videosAdapter = VideosAdapter(viewModel)
val recyclerView = findViewById<RecyclerView>(R.id.videos)
recyclerView.apply {
layoutManager = LinearLayoutManager(this#SearchResultsActivity)
adapter = videosAdapter
addOnScrollListener(this#SearchResultsActivity.scrollListener)
}
val progressBar = findViewById<ProgressBar>(R.id.paginationProgressBar)
viewModel.getSearchResults(searchQuery)
viewModel.searchResults.observe(this, Observer { resource ->
when(resource) {
is Resource.Success -> {
hideProgressBar(progressBar)
resource.data?.let { videoResponse ->
if (viewModel.nextSearchPageId != videoResponse.nextPageToken) {
viewModel.nextSearchPageId = videoResponse.nextPageToken
viewModel.searchedVideos.addAll(videoResponse.items)
// videoResponse.items.forEach { viewModel.getChannel(it.snippet.channelId) }
Log.d("Channels", viewModel.channels.toString())
videosAdapter.differ.submitList(viewModel.searchedVideos.toList())
}
else {
Log.d("Videos", "next token dekh ${viewModel.nextPageId}")
videosAdapter.differ.submitList(viewModel.searchedVideos.toList())
}
}
}
is Resource.Error -> {
hideProgressBar(progressBar)
Log.e("Videos", resource.message.toString())
}
is Resource.Loading -> {
showProgressBar(progressBar)
}
}
})
viewModel.channelResponse.observe(this, Observer { resource ->
when (resource) {
is Resource.Success -> {
resource.data?.let { channels ->
viewModel.channels.set(channels.items[0].id, channels.items[0])
// videosAdapter.differ.submitList(viewModel.videos.toList())
}
}
is Resource.Error -> {
Log.e("Channels", resource.message.toString())
}
is Resource.Loading -> {
Log.d("Channels", "Waiting")
}
}
})
}
private fun hideProgressBar(bar: ProgressBar) {
bar.visibility = View.INVISIBLE
isLoading = false
}
private fun showProgressBar(bar: ProgressBar){
bar.visibility = View.VISIBLE
isLoading = true
}
var isScrolling = false
var isLoading = false
val scrollListener = object: RecyclerView.OnScrollListener() {
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
super.onScrollStateChanged(recyclerView, newState)
if (newState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
isScrolling = true
}
}
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
val manager = recyclerView.layoutManager as LinearLayoutManager
val currentItems = manager.childCount
val totaltItems = manager.itemCount
val scrolledItems = manager.findFirstVisibleItemPosition()
if (isScrolling && totaltItems == currentItems + scrolledItems && !isLoading && viewModel.searchedVideos.size <= 1_000_000) {
viewModel.getNextSearchResults(searchQuery)
isScrolling = false
} else {
videosAdapter.differ.submitList(viewModel.searchedVideos.toList())
recyclerView.setPadding(0, 0, 0, 0)
Log.d("Videos", viewModel.searchedVideos.size.toString())
}
}
}
override fun onPause() {
super.onPause()
Log.d("searched", "Search Results Activity paused")
}
override fun onStop() {
super.onStop()
Log.d("searched", "Search Results Activity stopped")
}
override fun onDestroy() {
super.onDestroy()
Log.d("searched", "Search Results Activity destroyed")
}
}
The logcat shows the following error:
2021-09-28 12:51:06.200 1207-2988/? W/ActivityTaskManager: Force finishing activity com.example.mytube/.UI.SearchResultsActivity
For recreating the error, here is the gitHub repo to the app: https://github.com/AkhilrajNambiar/MyTube-1
Thanks in advance!
I have an image gallery on a Fragment and I want to create a program that, once the user clicks on a certain image, the program redirects the user to an Activity where more details are presented. However, after implementing the Intent, the program just crashes when the Activity opens.
I don't know what I might be doing wrong as I do not have much experience with fragments (I believe it is something I'm doing wrong in the fragment intent)
Here's the code:
Fragment
package cm.a12872_a18797.favlist.fragments
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.fragment.app.Fragment
import cm.a12872_a18797.favlist.ImageDetailActivity
import cm.a12872_a18797.favlist.Modal
import cm.a12872_a18797.favlist.R
class HomeFragment : Fragment() {
lateinit var rootView: View
public val modalList = ArrayList<Modal>()
lateinit var gridView: GridView
private var descriptions = arrayOf(
"Golden Bridge", "Tampa Bay Buccaneers", "Chevrolet Camaro",
"Vegetable Casserole", "Sweet and Sour Chicken", "Design Vector",
"Pork Loin", "Sidney's Opera House", "Pasta Dish",
"Dope Setup", "Singapore", "Tacos Dish",
"Toquio", "Warm Salad Dish"
)
private var images = intArrayOf(
R.drawable.bridge, R.drawable.buccaneers, R.drawable.camaro,
R.drawable.casserole, R.drawable.chicken, R.drawable.design,
R.drawable.lombo, R.drawable.operahouse, R.drawable.pasta,
R.drawable.setup, R.drawable.singapore, R.drawable.tacos,
R.drawable.toquio, R.drawable.warmsalad
)
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
rootView = inflater.inflate(R.layout.fragment_home, container, false)
gridView = rootView.findViewById(R.id.home_grid)
for (i in descriptions.indices){
modalList.add(Modal(descriptions[i], images[i]))
}
var customAdapter = GridAdapter(modalList, this#HomeFragment.requireContext())
gridView.adapter = customAdapter
gridView.setOnItemClickListener() { adapterView, view, position, l ->
var intent = Intent(this#HomeFragment.requireContext(), ImageDetailActivity::class.java)
intent.putExtra("data", modalList[position])
startActivity(intent)
}
return rootView
}
class GridAdapter(var itemModel : ArrayList<Modal>, var context: Context): BaseAdapter(){
var layoutInflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
var view = convertView
if (view == null){
view = layoutInflater.inflate(R.layout.home_grid_row, parent, false)
}
var imageViewName = view?.findViewById<ImageView>(R.id.grid_image)
imageViewName?.setImageResource(itemModel[position].image!!)
return view!!
}
override fun getItem(position: Int): Any {
return itemModel[position]
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun getCount(): Int {
return itemModel.size
}
}
}
Activity:
package cm.a12872_a18797.favlist
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.ImageView
import android.widget.TextView
import androidx.fragment.app.Fragment
import cm.a12872_a18797.favlist.fragments.HomeFragment
import cm.a12872_a18797.favlist.fragments.ListsFragment
import cm.a12872_a18797.favlist.fragments.SearchFragment
import com.google.android.material.bottomnavigation.BottomNavigationView
class ImageDetailActivity : AppCompatActivity() {
val TAG = "ImageDetailActivity"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_image_detail)
//region Bottom Navigation Menu =====================================
val bottomNavigation: BottomNavigationView = findViewById(R.id.bottom_navigation)
val homeFragment = HomeFragment()
val listsFragment = ListsFragment()
val searchFragment = SearchFragment()
bottomNavigation.setOnNavigationItemSelectedListener {
when (it.itemId) {
R.id.nav_home -> {
setCurrentFragment(homeFragment)
Log.i(TAG, "Home Selected")
}
R.id.nav_lists -> {
setCurrentFragment(listsFragment)
Log.i(TAG, "My Lists Selected")
}
R.id.nav_search -> {
setCurrentFragment(searchFragment)
Log.i(TAG, "Search Selected")
}
}
true
}
//endregion ==
val detailText = findViewById<TextView>(R.id.detailText)
val detailImage = findViewById<ImageView>(R.id.detailImage)
var modalItems: Modal = intent.getSerializableExtra("data") as Modal
detailText.text = modalItems.name
detailImage.setImageResource(modalItems.image!!)
}
private fun setCurrentFragment(fragment : Fragment) =
supportFragmentManager.beginTransaction().apply {
replace(R.id.fl_wrapper, fragment)
commit()
}
}
Modal Class:
package cm.a12872_a18797.favlist
import java.io.Serializable
class Modal : Serializable {
var name:String? = null
var image:Int? = null
constructor(name:String, image:Int){
this.name = name
this.image = image
}
}
I have Fragment and i want to add option menu. I have tried a lot but not found any solution.
Here is my code.
package com.code2hack.milkledger.fragment
import android.app.AlertDialog
import android.os.Bundle
import android.view.*
import androidx.appcompat.view.ActionMode
import androidx.appcompat.widget.Toolbar
import androidx.core.content.ContextCompat
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.navigation.findNavController
import androidx.navigation.fragment.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.NavigationUI
import androidx.navigation.ui.setupWithNavController
import androidx.recyclerview.widget.LinearLayoutManager
import com.code2hack.milkledger.BaseActivity
import com.code2hack.milkledger.MainActivityViewModel
import com.code2hack.milkledger.R
import com.code2hack.milkledger.actionmode.ActionModeCallback
import com.code2hack.milkledger.adapter.CustomerAdapter
import com.code2hack.milkledger.dialog.AddUserDialog
import com.code2hack.milkledger.handler.ItemClickListener
import com.code2hack.milkledger.model.Customer
import com.code2hack.milkledger.util.Event
import com.google.android.material.card.MaterialCardView
import com.google.android.material.snackbar.Snackbar
import kotlinx.android.synthetic.main.fragment_customer_list.*
class CustomerListFragment : BaseFragment() {
private val baseActivity: BaseActivity by lazy { activity as BaseActivity };
private var selectMode = false
val selectedCustomers = mutableSetOf<Customer>()
val selectedViews = mutableSetOf<View>()
private lateinit var actionMode: ActionMode
private val list = mutableListOf<Customer>()
private val model: MainActivityViewModel by activityViewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_customer_list, container, false)
}
private val customerAdapter: CustomerAdapter by lazy { CustomerAdapter(list,ClickHandler()) }
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.menu_main, menu)
super.onCreateOptionsMenu(menu, inflater)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return NavigationUI.onNavDestinationSelected(item,
findNavController())
|| super.onOptionsItemSelected(item)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val navController = findNavController()
val appBarConfiguration = AppBarConfiguration(navController.graph)
view.findViewById<Toolbar>(R.id.toolbar)
.setupWithNavController(navController, appBarConfiguration)
//baseActivity.setSupportActionBar(toolbar)
fab.setOnClickListener {
baseActivity.showDialog(AddUserDialog(null))
}
customer_view.apply {
layoutManager = LinearLayoutManager(activity)
adapter = customerAdapter
}
model.loadCustomers(userInfo().user_name,token())
observe();
}
private fun observe() {
with(model){
customers.observe(viewLifecycleOwner, Observer { items ->
if(items.isEmpty()){
baseActivity.showDialog(AddUserDialog(null))
}
list.clear();
list.addAll(items);
customerAdapter.notifyDataSetChanged();
})
customerSaved.observe(viewLifecycleOwner, Observer {
if(!it.handled){
Snackbar.make(requireView(),getString(R.string.message_customer_create),Snackbar.LENGTH_LONG).show()
list.add(it.getContentIfNotHandled()!!)
customerAdapter.notifyDataSetChanged()
}
})
customerDeleted.observe(viewLifecycleOwner, Observer {
if(!it.handled){
handleDeleteEvent(it, requireView(), customerAdapter)
}
})
}
}
private fun handleDeleteEvent(
it: Event<Boolean>,
view: View,
customerAdapter: CustomerAdapter
) {
it.getContentIfNotHandled()
Snackbar.make(view, getString(R.string.message_customer_delete), Snackbar.LENGTH_LONG).show()
model.loadCustomers(userInfo().user_name, token())
selectMode = false
selectedCustomers.clear()
selectedViews.clear()
actionMode.finish()
list.clear()
customerAdapter.notifyDataSetChanged()
}
private fun deleteCustomers(){
val dialog = AlertDialog.Builder(requireActivity())
.setMessage(R.string.delete_confirm_message)
.setPositiveButton(R.string.delete){ dialogInterface, _ ->
model.deleteCustomer(selectedCustomers, token(), userInfo().user_name)
clearSelectMode()
dialogInterface.cancel()
}.setNegativeButton(R.string.cancel){ dialogInterface, _ ->
clearSelectMode()
dialogInterface.cancel()
}
.create()
dialog.setOnShowListener {
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(ContextCompat.getColor(requireContext(),R.color.colorAccent))
dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(ContextCompat.getColor(requireContext(),R.color.cancel_text_red))
}
dialog.show();
}
val actionModeCallback = ActionModeCallback({
when(it) {
R.id.action_logout -> {
(baseActivity).logout();
true
}
R.id.delete -> {
deleteCustomers()
true
}
R.id.edit -> {
baseActivity.showDialog(AddUserDialog(selectedCustomers.first()))
true
}
else -> false
}
},{
selectMode = false
selectedCustomers.clear()
selectedViews.forEach{
(it as MaterialCardView).setCardBackgroundColor(ContextCompat.getColor(requireActivity(),android.R.color.white))
}
selectedViews.clear()
},{
it.findItem(R.id.delete).isVisible = selectedCustomers.size > 0
it.findItem(R.id.edit).isVisible = selectedCustomers.size == 1
})
inner class ClickHandler : ItemClickListener<Customer>() {
val TAG = "ClickHandler"
override fun onItemClick(item: Customer, view:View?) {
if(selectMode){
processSelection(item,view)
} else {
val action = CustomerListFragmentDirections.recordFragment(item.id)
action.setCowMilkRate(item.cowMilkRate)
action.setBuffaloMilkRate(item.buffaloMilkRate)
view!!.findNavController().navigate(action)
}
}
override fun onLongClick(item: Customer, view: View?){
selectMode = true
actionMode = baseActivity.startSupportActionMode(actionModeCallback)!!
processSelection(item,view)
}
private fun processSelection(customer: Customer, view: View?){
if(selectedCustomers.indexOf(customer) < 0) {
selectedCustomers.add(customer)
selectedViews.add(view!!)
(view as MaterialCardView).setCardBackgroundColor(ContextCompat.getColor(requireActivity(),R.color.background_light_green))
}
else {
selectedCustomers.remove(customer)
selectedViews.remove(view!!)
(view as MaterialCardView).setCardBackgroundColor(ContextCompat.getColor(requireActivity(),android.R.color.white))
}
if(selectedCustomers.size == 0){
clearSelectMode();
} else {
actionMode.invalidate()
}
}
}
private fun clearSelectMode() {
actionMode.finish()
selectMode = false
selectedCustomers.clear()
selectedViews.clear()
}
}
The method onCreateOptionsMenu is not getting executed.
What i am missing i have no idea. There is no actionbar in my activity. I have put action bar in the fragment_customer_list. Action bar is displayed properly. But not able to add menu to the toolbar
Since you are not calling the setSupportActionBar you should use the Toolbar APIs directly.
Something like:
toolbar.inflateMenu(R.menu.menu_main)
toolbar.setOnMenuItemClickListener {
it.onNavDestinationSelected(navController)
}
NavigationUI.setupWithNavController(
toolbar, navController, appBarConfiguration)