Why my emulator isn't destroying activity in landscape mode? - android-studio

My android emulator should destroy the contents of textView widget when I turn it to landscape from portrait. But it isn't doing that, WHY? Isn't it destroying the activity?
look in the emulator "this is the first text"-- I added this line in emulator when it was in portrait mode.
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
class MainActivity : AppCompatActivity() {
private var textView: TextView? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//comment
val userInput: EditText = findViewById<EditText>(R.id.editText)
val button: Button = findViewById<Button>(R.id.button)
textView = findViewById<TextView>(R.id.textView)
textView?.text = ""
textView?.movementMethod =
ScrollingMovementMethod() // It allows my text view widget to scroll upward
userInput.text.clear()
button.setOnClickListener(object : View.OnClickListener {
override fun onClick(p0: View?) {
textView?.append(userInput.text)
textView?.append("\n")
userInput.setText("")
}
})
}
}
```[enter image description here][1]
[1]: https://i.stack.imgur.com/oLRr3.png

Related

RecyclerView ItemOnClickListener doesn't work

sorry for the inconvenience, but this is my first time trying this. I've been trying on doing this app which it has a recyclerView which I intent it to open a chrome page. The thing is, I'm not able to implement the itemOnClickListener despite having tried a lot of videos. Could you point out where is my mistake?
My Adapter:
package com.example.practica1.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContentProviderCompat.requireContext
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.example.practica1.R
import com.example.practica1.data.Video
class MainAdapter(private val context: Context, private val videos: List<Video>,
val listener: MyOnClickListener
): RecyclerView.Adapter<MainAdapter.ViewHolder>(){
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MainAdapter.ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_cartoon, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val video = videos[position]
holder.title.text = video.data.short_title
holder.serieTitle.text = video.data.show.title
holder.durationTitle.text = video.data.video.duration + " seg"
Glide.with(context)
.load(video.data.imagepath)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.override(400, 400)
.centerCrop()
.into(holder.imagePrev)
}
override fun getItemCount() = videos.size
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView){
val title: TextView = itemView.findViewById(R.id.videoTitle)
val serieTitle: TextView = itemView.findViewById(R.id.serieTitle)
val durationTitle: TextView = itemView.findViewById(R.id.durationTitle)
val imagePrev: ImageView = itemView.findViewById(R.id.photoPreview)
init{
itemView.setOnClickListener{
val position = adapterPosition
listener.onClick(position)
}
}
}
interface MyOnClickListener{
fun onClick(position: Int)
}
}
The fragment in which I tried to implement the method (The toast message doesn't appear)
package com.example.practica1.fragments
import android.os.Bundle
import android.util.Log
import android.util.Log.d
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.navigation.Navigation
import androidx.recyclerview.widget.RecyclerView
import com.example.practica1.R
import com.example.practica1.adapter.MainAdapter
import com.example.practica1.data.ApiInterface
import com.example.practica1.data.Video
import com.example.practica1.databinding.FragmentMenuBinding
import com.haerul.bottomfluxdialog.BottomFluxDialog
import com.haerul.bottomfluxdialog.BottomFluxDialog.OnInputListener
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
class MenuFragment : Fragment() {
private var _binding: FragmentMenuBinding? = null
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = FragmentMenuBinding.inflate(inflater, container, false)
val view = inflater.inflate(R.layout.fragment_menu, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val retrofit = Retrofit.Builder()
.baseUrl("https://www.cartoonnetwork.com.co")
.addConverterFactory(GsonConverterFactory.create())
.build()
val api = retrofit.create(ApiInterface::class.java)
showProgress()
api.fetchAllVideos().enqueue(object : Callback<List<Video>> {
override fun onResponse(call: Call<List<Video>>, response: Response<List<Video>>) {
if (response.isSuccessful()) {
d("daniel", "onResponse ${response.body()!![0].id}")
if (response.body()!!.size > 0) {
showData(response.body()!!)
getResult(true, "Sucess")
} else
getResult(false, response.message())
hideProgress()
}
}
override fun onFailure(call: Call<List<Video>>, t: Throwable) {
d("daniel", "onFailure")
getResult(false, "Request Timeout. Please Try Again!")
hideProgress()
}
})
binding.search.setOnClickListener { v -> showDialog(v) }
}
fun showData(videos: List<Video>){
val test: RecyclerView = requireActivity().findViewById(R.id.recycler_viewMenu)
test.apply{
adapter = MainAdapter(context, videos, object: MainAdapter.MyOnClickListener{
override fun onClick(position: Int) {
Toast.makeText(requireContext(), position, Toast.LENGTH_SHORT).show()
}
})
}
}
fun showProgress(){
binding.swipeRefresh.setRefreshing(true)
binding.emptyView.setVisibility(View.GONE)
binding.shimmer.startShimmer()
binding.shimmer.setVisibility(View.VISIBLE)
binding.recyclerViewMenu.setVisibility(View.GONE)
}
fun hideProgress(){
binding.swipeRefresh.setRefreshing(false)
binding.shimmer.stopShimmer()
binding.shimmer.setVisibility(View.GONE)
binding.recyclerViewMenu.setVisibility(View.VISIBLE)
}
fun getResult(status: Boolean, message: String){
if(!status) {
binding.emptyView.setVisibility(View.VISIBLE)
binding.textEmptyErr.setText(message)
}
else
binding.emptyView.setVisibility((View.GONE))
}
private fun showDialog(view: View){
BottomFluxDialog.inputDialog(requireActivity())
.setTextTitle("Input Title")
.setTextMessage("This is an input message")
.setRightButtonText("SUBMIT")
.setInputListener(object : OnInputListener {
override fun onSubmitInput(text: String?) {
val bundle = Bundle()
bundle.putString("search", text)
Navigation.findNavController(view)
.navigate(R.id.action_menuFragment_to_listFragment, bundle)
}
override fun onCancelInput() {}
})
.show()
}
}
Thanks!
If your data is showing in the recycler view and you are getting crash on item click than
replace this toast link :-
Toast.makeText(requireContext(), position, Toast.LENGTH_SHORT).show()
with this :-
Toast.makeText(requireContext(), "$position", Toast.LENGTH_SHORT).show()
or if your video list is not visible in recycler view than you need to implement layout manager in recycler view you can add it on xml or in code also.

Android Studio Spinner (in Kotlin) doesn't respond to any clicks

I am trying to get a spinner working with Kotlin, I have spent hours on it but to no avail. Whatever I do, it doesn't respond to items being selected.
Let's start with the code:
This is my xml layout: (only the spinner)
<Spinner
android:id="#+id/unitySelectionSpinner"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="50"
android:gravity="center"
android:textSize="24sp"
/>
My Fragment:
import android.app.Activity
import android.content.Context
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Spinner
import android.widget.Toast
import androidx.databinding.DataBindingUtil
import androidx.navigation.Navigation
import com.epfl.esl.organizer.databinding.FragmentCreateStorageBinding
import com.google.firebase.database.*
import kotlin.collections.ArrayList
class CreateStorageFragment : Fragment(), AdapterView.OnItemSelectedListener {
private lateinit var binding: FragmentCreateStorageBinding
private lateinit var unitID: String
val database: FirebaseDatabase = FirebaseDatabase.getInstance("myDatabase")
val storageRef: DatabaseReference = database.getReference("Units")
var list = ArrayList<String>()
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
Toast.makeText(context, "We got the Key:", Toast.LENGTH_SHORT).show()
var a = 7 / 0
}
override fun onNothingSelected(parent: AdapterView<*>?) {
Toast.makeText(context, "Nothing selected", Toast.LENGTH_SHORT).show()
var b = 7 / 0
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_create_storage, container, false)
// Get the list of names of units from firebase
storageRef.addListenerForSingleValueEvent(object: ValueEventListener{
override fun onDataChange(snapshot: DataSnapshot) {
// Fill an ArrayList with all the unit names
for(unit in snapshot.children) {
list.add(unit.child("unitName").value.toString())
}
}
override fun onCancelled(error: DatabaseError) {}
})
binding.addObjectButton.setOnClickListener{view: View ->
Navigation.findNavController(view).navigate(R.id.action_createStorageFragment_to_createObjectFragment)
}
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val spinner: Spinner = binding.unitySelectionSpinner
val spinnerArrayAdapter = ArrayAdapter<String>(activity as Context, android.R.layout.simple_spinner_dropdown_item, list)
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spinner.adapter = spinnerArrayAdapter
spinner.onItemSelectedListener = this
}
}
I feel that I've tried everything imaginable, including:
-Creating an independent class with the spinner functions (onItemSelected, etc.)
-Put everything in onCreateView, put everything in onViewCreated
-Creating an instance of spinner with AdapterView.OnItemSelectedListener inside onCreateView
Whatever I do the result is always the same: the spinner is populated (all the firebase data is written into it properly) but it doesn't respond when I click on an item in the app. None of the toasts (or the crash that should be caused by the division by zero) are triggered. It simply closes on selection as a normal spinner would do.
I am not sure what I am missing here. Any ideas?

Unresolved Reference Java

class MainActivity : AppCompatActivity() {
lateinit var playbutton : Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
playbutton = findViewById(R.id.play_button)
playbutton.setOnClickListener {
val intent = Intent(this,Frame::class.java)
startActivity(intent)
}
}
}
Showing Error Unreolved Reference Java
my Imports :
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
I am starting another Activity From The Mainactivity and android studio is Showing This Error .

getting adapter type mismatch in Android Studio

basically i am trying to create a recycler view and this the main activity
i am getting error at
recyclerView.adapter = adapter
package com.example.newsorning
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.support.v7.widget.RecyclerView
import androidx.recyclerview.widget.LinearLayoutManager
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
recyclerView.layoutManager = LinearLayoutManager(this)
val items = fetchData()
val adapter = NewsListAdapter(items)
recyclerView.adapter = adapter
}
private fun fetchData():ArrayList<String>{
val list = ArrayList<String>()
for (i in 0 until 100){
list.add("item $i")
}
return list
}
}
this is where i created adpater
//newsListadapter
package com.example.newsorning
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
class NewsListAdapter(private val item:ArrayList<String>):
RecyclerView.Adapter<NewsViewHolder>() {
override fun onCreateViewHolder(p0: ViewGroup, p1: Int): NewsViewHolder {
val view = LayoutInflater.from(p0.context).inflate(R.layout.item_news,p0,false)
return NewsViewHolder(view)
}
override fun getItemCount(): Int {
return item.size
}
override fun onBindViewHolder(p0: NewsViewHolder, p1: Int) {
val currentItem = item[p1]
p0.titleView.text = currentItem
}
}
class NewsViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val titleView : TextView = itemView.findViewById(R.id.titleView)
}
This may be due to you using the old, deprecated support library RecyclerView (android.support.v7) instead of the Jetpack RecyclerView (androidx). Maybe one of the libraries you're using still uses the old support library, so it was in your namespace and you accidentally selected it when choosing which class to import. You need to change the line
import android.support.v7.widget.RecyclerView
to
import androidx.recyclerview.widget.RecyclerView
in both of these files. And you need to enable Jetifier according to these directions.

Make a TabBar inside a specific NavBar fragment

my app use bottomNavBar with 3 fragments [Settings / Home / Gallery].
Now I'm trying to make a TabBar with 3 new Tabs inside of "Settings". [setting01 / setting02 / setting03]
I followed carefully this tutorial : https://www.youtube.com/watch?v=qfFANw7nPMU
and I used viewPager2 when the video uses viewPager.
but I'm still stuck in MainActivity.kt because for some reasons these two line (from the tutorial) didn't work for me :
viewPager2.adapter = PageAdapter(supportFragmentManager)
tabLayout.setupWithViewPager(viewPager2)
here is my entire MainActivity.kt file :
package com.example.appname
import android.os.Bundle
import com.google.android.material.bottomnavigation.BottomNavigationView
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.setupActionBarWithNavController
import androidx.navigation.ui.setupWithNavController
import com.example.appname.ui.settings.PageAdapter
import kotlinx.android.synthetic.main.fragment_settings.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val navView: BottomNavigationView = findViewById(R.id.nav_view)
val navController = findNavController(R.id.nav_host_fragment)
val appBarConfiguration = AppBarConfiguration(setOf(
R.id.navigation_settings, R.id.navigation_swapper, R.id.navigation_gallery))
setupActionBarWithNavController(navController, appBarConfiguration)
navView.setupWithNavController(navController)
viewPager2.adapter = PageAdapter(supportFragmentManager)
tabLayout.setupWithViewPager(viewPager2)
}
}
I'm almost certain that this error exists because these two lines should be somewhere else because of the particular situation of my application.
To find yourself in a situation similar to mine I recommend you to start a new project under android studio using the template "Bottom Navigation Activity" and then follow the tutorial.
A friend of mine give me the solution.
Nothing new in MainActivity.kt like I was thinking.
Here is the new code to make tabBar in the Settings fragment :
settingFragment.kt
class SettingsFragmentAdapter(fragment: Fragment) : FragmentStateAdapter(fragment) {
private val fragments =
listOf(
fragment_setting_teams(),
fragment_setting_general(),
fragment_setting_movies()
)
override fun getItemCount(): Int = fragments.size
override fun createFragment(position: Int): Fragment = fragments[position]
}
class SettingsFragment : Fragment() {
private lateinit var settingsViewModel: SettingsViewModel
private lateinit var settingsAdapter: SettingsFragmentAdapter
private lateinit var viewPager: ViewPager2
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val tabLayout = view.findViewById<TabLayout>(R.id.tabLayout)
settingsAdapter =
SettingsFragmentAdapter(
this
)
viewPager = view.findViewById(R.id.viewPager2)
viewPager.adapter = settingsAdapter
TabLayoutMediator(tabLayout, viewPager) { tab, position ->
when (position) {
0 -> tab.text = "Teams"
1 -> tab.text = "General"
2 -> tab.text = "Movies"
}
}.attach()
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
settingsViewModel =
ViewModelProviders.of(this).get(SettingsViewModel::class.java)
val root = inflater.inflate(R.layout.fragment_settings, container, false)
return root
}
}

Resources