Change activit with Spinner on Android Studio with Kotlin - android-studio

Lets say i have a Spinner with two objects in it Object A and Object B.
And i have two activities named "A activity" and "B activity".
How can i change activity by selecting an item from Spinner.
I know i have to use Spinner on Item Selected Listener but can't do it on my own please help.
Spinner.onItemSelectedListener
Any help would be great.

I solved it by this code if anyone interested
val spinner: Spinner = findViewById(R.id.spinner)
ArrayAdapter.createFromResource(this, R.array.lotto_choices, R.layout.spinner_list
).also { adapter ->
adapter.setDropDownViewResource(R.layout.spinner_list)
spinner.adapter = adapter
}
spinner.setSelection(0)
val spinner: Spinner = findViewById(R.id.spinner)
spinner.onItemSelectedListener = object :
AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
var intent: Intent
if (position == 0) {
return
}
if (position == 1 ) {
intent = Intent(this#SayisalActivity, SuperActivity::class.java)
startActivity(intent)
}
if (position == 2 ) {
intent = Intent(this#SayisalActivity, SansActivity::class.java)
startActivity(intent)
}
if (position == 3 ) {
intent = Intent(this#SayisalActivity, OnnumaraActivity::class.java)
startActivity(intent)
}
}
override fun onNothingSelected(parent: AdapterView<*>?) {
return
}
}

Related

MainActivity is not showing log statements

Hi I am new to android development and the problem is Whenever I am using MainActivity in logcat as a filter it is not showing me Log statements for this Log.i(TAG, "TAG on Fb")(my tag is also MainActivity) and Log.i(TAG, "onitemclick $position") for this it is shown by its function that is onItemClick but the same happen with this statement whenever I am trying to filter it on the basis of MainActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
userMaps = generateSampleData() as MutableList<user>
//set layout manager on the screen => RV
rvmaps.layoutManager = LinearLayoutManager(this)
//set adapter on RV
mapAdapter = mapadapter(this, userMaps, object: mapadapter.OnClickListener{
override fun onitemclick(position: Int) {
Log.i(TAG, "onitemclick $position")
val intent = Intent(this#MainActivity, googlemaps::class.java)
// here we will use putextra which help us to put extra data to another activity through data
intent.putExtra(user_data_map, userMaps[position])
startActivity(intent)
}
})
rvmaps.adapter = mapAdapter
fabcreatemap.setOnClickListener{
Log.i(TAG, "TAG on Fb")
val intent = Intent(this#MainActivity, createmap::class.java)
intent.putExtra(user_map_title, "new map name")
startActivityForResult(intent, requestcode)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if(requestcode == requestCode && resultCode == Activity.RESULT_OK)
{
val usermap = data?.getSerializableExtra(user_data_map) as user
// userMaps.add(usermap)
// mapAdapter.notifyItemChanged(userMaps.size-1)
}
super.onActivityResult(requestCode, resultCode, data)
}
}

Clearing a RecyclerView when User makes a second request (using diffUtils and livedata)

I have made an app that uses an API to make a request and then shows the results in a RecyclerView.
I was following a tutorial and in it they used a differCallback and a liveData so the lists updates and such. However whenever the user makes a second search, the recyclerView should only show the new results but the previous results don't dissapear and the new results just appear below the previous search.
I have debugged it for quite some time now but I don't seem to understand where the list is made and where sure it be updated (or in this case cleared).
I tried using .clear() for the diff (Asynclistdiffer), creating a new list in the onBindViewHolder and then clearing that list every time the "search" is called but without any luck. As im still a beginner I don't have a clue on where or what is happening, all your helo will be greatly appreciated
this is my adapter:
class RecipePreviewAdapter : RecyclerView.Adapter<RecipePreviewAdapter.RecipePreviewViewHolder>() {
inner class RecipePreviewViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
private val differCallback = object : DiffUtil.ItemCallback<Recipe>() {
override fun areItemsTheSame(oldItem: Recipe, newItem: Recipe): Boolean {
return oldItem.sourceUrl == newItem.sourceUrl
}
override fun areContentsTheSame(oldItem: Recipe, newItem: Recipe): Boolean {
return oldItem == newItem
}
}
val differ = AsyncListDiffer(this, differCallback)
lateinit var recipeList: MutableList<Recipe>
var isRecipeListInitialized = false
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecipePreviewViewHolder {
return RecipePreviewViewHolder(
LayoutInflater.from(parent.context).inflate(
R.layout.item_recipe_preview,
parent,
false
)
)
}
override fun onBindViewHolder(holder: RecipePreviewViewHolder, position: Int) {
recipeList = differ.currentList.toMutableList()
isRecipeListInitialized = true
// Log.d(TAG, recipeList.toString())
val recipe = recipeList[position]
holder.itemView.apply {
Glide.with(this).load(recipe.image).into(ivRecipeImagePreview)
tvRecipeTitlePreview.text = recipe.title
tvTimeToMakeTVPreview.text = "${recipe.readyInMinutes} minutes"
tvSummaryPreview.text = Jsoup.parse(recipe.summary).text()
setOnClickListener {
onItemClickListener?.let { it(recipe) }
}
}
}
override fun getItemCount(): Int {
return differ.currentList.size
}
And this is where I call it:
class SearchRecipeFragment : Fragment(R.layout.fragment_search_recipe) {
lateinit var viewModel: RecipeViewModel
lateinit var recipeAdapter: RecipePreviewAdapter
val TAG = "SearchRecipeFragment"
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel = (activity as RecipesActivity).viewModel
setupRecyclerView()
recipeAdapter.setOnItemClickListener {
val bundle = Bundle().apply {
putSerializable("recipe", it)
}
findNavController().navigate(
R.id.action_searchRecipeFragment_to_recipeFragment,
bundle
)
}
etSearch.setOnKeyListener(View.OnKeyListener { _, keyCode, event ->
if (keyCode == KeyEvent.KEYCODE_ENTER && event.action == KeyEvent.ACTION_DOWN) {
if (etSearch.text.toString().isNotEmpty()) {
viewModel.searchRecipe(etSearch.text.toString())
}
return#OnKeyListener true
}
false
})
viewModel.searchRecipeLiveData.observe(viewLifecycleOwner, Observer { response ->
when (response) {
is Resource.Success -> {
hideProgressBar()
response.data?.let { recipeResponse ->
recipeAdapter.differ.submitList(recipeResponse.results.toList())
}
}
is Resource.Error -> {
hideProgressBar()
response.message?.let { message ->
Log.e(TAG, "An error occurred: $message")
Toast.makeText(activity, "An error occurred: $message", Toast.LENGTH_LONG)
.show()
}
}
is Resource.Loading -> {
showProgressBar()
}
}
})
}
Ans this is the part of the ViewModel that I'm not really sure what it does
private fun handleSearchRecipeResponse(response: Response<SearchRecipeResponse>): Resource<SearchRecipeResponse> {
if (response.isSuccessful) {
response.body()?.let { resultResponse ->
searchRecipesPage++
if (searchRecipesResponse == null) {
searchRecipesResponse = resultResponse
} else {
val oldRecipes = searchRecipesResponse?.results
val newRecipes = resultResponse.results
oldRecipes?.addAll(newRecipes)
}
return Resource.Success(searchRecipesResponse ?: resultResponse)
}
}
return Resource.Error(response.message())
}
too late but it is because of "searchRecipesResponse". You have to set it to "null" and reset searchRecipesPage to 1 for each new search in etSearch.setOnKeyListener().

kotlin adapter give me error in mainactivity

I have a class called medicine, I got an error when writing adapter = MedicineAdapter(this, this.medicineList!!) in main activity I saw the error in run window.
My app is crashing when I want to run and I saw one error which is about adapter's line
Also, I have medicine_items it is my custom design I assigned it to the adapter in my adapter also I checked my ids but ı don t know why am I got an error
MainActivity
class MainActivity : AppCompatActivity() {
private var adapter: MedicineAdapter? = null
private var medicineList : ArrayList<Medicine>? = null
private var recyclerView: RecyclerView? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
recyclerView =
findViewById<View>(R.id.recycler) as RecyclerView
adapter = MedicineAdapter(this, this.medicineList!!)
val layoutManager = LinearLayoutManager(applicationContext)
recyclerView!!.layoutManager = layoutManager
recyclerView!!.itemAnimator = DefaultItemAnimator()
// Add a neat dividing line between items in the list
recyclerView!!.addItemDecoration(
DividerItemDecoration(this,
LinearLayoutManager.VERTICAL))
// set the adapter
recyclerView!!.adapter = adapter
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean = when (item.itemId) {
R.id.addBtn -> {
val intent = Intent(this,AddNewMedicine::class.java)
startActivity(intent)
true
}
else -> super.onOptionsItemSelected(item)
}
fun addMedicine(m: Medicine){
medicineList!!.add(m)
adapter!!.notifyDataSetChanged()
}
}
MyAdapter
class MedicineAdapter(
private val mainActivity: MainActivity,
private val medicineList: ArrayList<Medicine>)
: RecyclerView.Adapter<MedicineAdapter.ListItemHolder>(){
override fun onCreateViewHolder(
parent: ViewGroup, viewType: Int): ListItemHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.medicine_items, parent, false)
return ListItemHolder(itemView)
}
inner class ListItemHolder(view: View) :
RecyclerView.ViewHolder(view),
View.OnClickListener {
internal var name = view.findViewById<TextView>(R.id.name)
internal var amount = view.findViewById<TextView>(R.id.amount)
internal var description = view.findViewById<TextView>(R.id.description)
init {
view.isClickable = true
view.setOnClickListener(this)
}
override fun onClick(view: View) {
//val intentToCarPager = Intent(view!!.context, CarPagerActivity::class.java)
//view.context.startActivity(intentToCarPager)
}
}
override fun onBindViewHolder(holder: ListItemHolder, position: Int) {
val medicine = medicineList!![position]
holder.name.text = medicine.name.toString()
holder.amount.text = medicine.amount.toString()
holder.description.text = medicine.desription.toString()
}
override fun getItemCount(): Int {
if (medicineList != null) {
return medicineList.size
}
return -1
}
}
my run window
It's because here:
private var medicineList : ArrayList<Medicine>? = null
you have initialized medicineList as null and you haven't given it a proper value along the way and here:
adapter = MedicineAdapter(this, this.medicineList!!)
you have asserted that it is not null and tried to assign it to the adapter.
If you have no elements to add to your array at first, initialize it this way:
private var medicineList : ArrayList<Medicine> = arrayListOf()
and then you can add elements to it:
medicineList.add(myMedicine)

How To Show Interstitial Ads in The getView Function in Kotlin?

I'm a Beginner in Kotlin and I want a way to display Interstitial Ad every time I click on the button tvName, but on the contrary, the app crashes whenever I click on the button. I searched for the solution for a long time.
Here's MainActivity
import ...
#Suppress("UNREACHABLE_CODE")
class MainActivity : AppCompatActivity() {
lateinit var mAdView : AdView
var adapter:ChaptersAdapter?=null
var listOfChapters= ArrayList<Chapters>()
#SuppressLint("WrongViewCast")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
MobileAds.initialize(this) {}
mAdView = findViewById(R.id.adView)
val adRequest = AdRequest.Builder().build()
mAdView.loadAd(adRequest)
loadChapters()
adapter = ChaptersAdapter(listOfChapters, this)
lvchapters.adapter = adapter
MobileAds.initialize(this,
"ca-app-pub-3940256099942544~3347511713")
mInterstitialAd = InterstitialAd(this)
mInterstitialAd.adUnitId = "ca-app-pub-3940256099942544/1033173712"
mInterstitialAd.loadAd(AdRequest.Builder().build())
}
fun loadChapters(){
listOfChapters.add(Chapters(" Chapter 1 ", applicationContext.assets.open("Chapter0.txt").bufferedReader().use {
it.readText()
}
))
listOfChapters.add(Chapters(" Chapter 2 ", applicationContext.assets.open("Chapter1.txt").bufferedReader().use {
it.readText()
}
))
}
class ChaptersAdapter: BaseAdapter {
var context:Context?=null
var listOfChaptersLocal= ArrayList<Chapters>()
constructor(listOfChapters:ArrayList<Chapters>,context:Context){
listOfChaptersLocal=listOfChapters
this.context=context
}
override fun getView(p0: Int, p1: View?, p2: ViewGroup?): View {
val chapters= listOfChaptersLocal[p0]
var inflator= context!!.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val chaptersView=inflator.inflate(R.layout.list_chapters,null)
chaptersView.tvName.text= chapters.name!!
chaptersView.**tvName.setOnClickListener** {
// **i want to show the Ads in this time frame** but like this example it didn't work
if (mInterstitialAd.isLoaded) {
mInterstitialAd.show()
} else {
Log.d("TAG", "The interstitial wasn't loaded yet.")
}
val intent =Intent(context,ChapterDetails::class.java)
intent.putExtra("name",chapters.name!!)
intent.putExtra("des",chapters.des!!)
context!!.startActivity(intent)
}
return chaptersView
}
override fun getItem(p0: Int): Any {
return listOfChaptersLocal[p0]
}
override fun getItemId(p0: Int): Long {
return p0.toLong()
}
override fun getCount(): Int {
return listOfChaptersLocal.size
}
}
}

OnItem click not working properly after clicking on the item in Recyclerview

I have tried to implement search functionality in the recycler view.for that I have written below code in My "Main.kt" class
search functionality is working fine for me,
the issue is when I am searching the item from the list and clicking on that item I am getting the wrong position.
please help me with this issue.
adapter = DynamicListAdapter(dynamicList)
dynamic_list_recyclerview.layoutManager = LinearLayoutManager(this, LinearLayout.VERTICAL,false) as RecyclerView.LayoutManager
dynamic_list_recyclerview.adapter = adapter
adapter!!.setRecyclerViewItemClickLister(this)
i have taken edit text and added the addTextChangedListener
edt_search_dynamic.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) {
}
override fun afterTextChanged(editable: Editable?) {
filter(editable.toString())
}
})
fun filter(text : String){
var filteredList = mutableListOf<DynamicModel>()
for(list in dynamicList){
if(list.vehicleno.toLowerCase().contains(text.toLowerCase())){
filteredList.add(list)
}
}
adapter?.filterList(filteredList)
}
and this is my adapter class
class DynamicListAdapter (var dynamiclist : List<DynamicModel>) : RecyclerView.Adapter<DynamicListAdapter.DynamicViewHolder>() {
var recyclerViewOnItemClickListener : RecyclerViewOnItemClickListener? = null
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DynamicViewHolder {
val inflatedView = LayoutInflater.from(parent.context)
.inflate(R.layout.singlerowdynamiclist,parent,false)
return DynamicViewHolder(inflatedView,dynamiclist)
}
override fun getItemCount(): Int {
return dynamiclist.size
}
override fun onBindViewHolder(holder: DynamicViewHolder, position: Int) {
holder.bindItem(dynamiclist[position])
}
inner class DynamicViewHolder(itemView : View, var dynamiclists : List<DynamicModel>) : RecyclerView.ViewHolder(itemView), View.OnClickListener
{
private var txtStatus : TextView? = null
init {
txtStatus = itemView.findViewById(R.id.txtStatus)
itemView.setOnClickListener(this)
}
fun bindItem(dynamiclist : DynamicModel){
txtStatus?.text = dynamiclist.vehiclestatus
}
override fun onClick(view: View?) {
when(view){
itemView -> if(recyclerViewOnItemClickListener!= null){
recyclerViewOnItemClickListener!!.onItemClick(adapterPosition,view)
}
}
}
}
// method of outer class
fun setRecyclerViewItemClickLister(onRecyclerviewItemClickListener : RecyclerViewOnItemClickListener){
this.recyclerViewOnItemClickListener = onRecyclerviewItemClickListener
}
// for filter the list
fun filterList(dymaniclist : List<DynamicModel>){
this.dynamiclist = dymaniclist
notifyDataSetChanged()
}
}
and this is the interface which I have implemented in my Main.kt class
interface RecyclerViewOnItemClickListener {
fun onItemClick(position : Int, view: View)
}
You won't get the desired position (the position from the unfiltered list) after applying your filters, because you lose that information when creating a new filtered list and putting it inside the DynamicListAdapter.
Let's say inside the adapter we have a list of the following items:
val dynamicList = listOf(
"#0 A", // 0th position
"#1 B", // 1st position
"#2 AB" // 2nd position
)
Now let's use your filter method:
filter("A")
This ends with replacing the old dynamicList inside the DynamicListAdapter with a completely new filteredList, which looks like this:
val filteredList = listOf(
"#0 A", // 0th position
"#2 AB", // 1st position
)
Now when clicking the #2 AB you will get position of value 1 (not desired 2) as it is the item's index in the new filteredList.
There are multiple ways of how to achieve what you want, but if you only want data from the clicked item, just return the object instead of its position on the item click:
interface RecyclerViewOnItemClickListener {
fun onItemClick(dynamicModel: DynamicModel, view: View)
}
// inside DynamicListAdapter
inner class DynamicViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bindItem(dynamiclist : DynamicModel) {
with (itemView) {
txtStatus.text = dynamiclist.vehiclestatus
setOnClickListener {
recyclerViewOnItemClickListener?.onItemClick(dynamiclist, this)
}
}
}
}
However if you need to return the position and the above is not an option, I would suggest leaving the original list in the adapter and letting it handle filtering by itself, for example:
// _dynamicList is always the original list
class DynamicListAdapter (private val _dynamicList: List<DynamicModel>) : RecyclerView.Adapter<DynamicListAdapter.DynamicViewHolder>() {
var recyclerViewOnItemClickListener : RecyclerViewOnItemClickListener? = null
var filterText: String = ""
set(value) {
field = value
notifyDataSetChanged()
}
// return original list (_dynamicList) if no filter should be applied or return the filtered list based on the filterText
private val dynamicList: List<DynamicModel>
get() = if (filterText.isBlank()) _dynamicList
else _dynamicList.filter { it.vehicleno.contains(filterText, ignoreCase = true) }
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DynamicViewHolder {
val inflatedView = LayoutInflater.from(parent.context).inflate(R.layout.singlerowdynamiclist,parent,false)
return DynamicViewHolder(inflatedView)
}
override fun getItemCount(): Int {
return dynamicList.size
}
override fun onBindViewHolder(holder: DynamicViewHolder, position: Int) {
holder.bindItem(dynamicList[position])
}
inner class DynamicViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
fun bindItem(dynamicModel: DynamicModel) {
with (itemView) {
txtStatus.text = dynamicModel.vehiclestatus
// get the item's original position (before filtering)
val position = _dynamicList.indexOf(dynamicModel)
setOnClickListener {
recyclerViewOnItemClickListener?.onItemClick(position, this)
}
}
}
}
}
// filter method
fun filter(text: String){
adapter?.filterText = text
}
I put my solution it might help somebody.
Given: recyclerView is working fine.
Problem: on item click is not working after implementing searchview.
solution: add mAdapter.setOnItemClickListener again inside onQueryTextChange as below:
#Override
public boolean onQueryTextChange(String newText) {
mAdapter = new MyAdapter(getApplicationContext(), OtherInofYouWantToPass);
recyclerView.setAdapter(mAdapter);
mAdapter.setOnItemClickListener(new MyAdapter.OnItemClickListener() {
#Override
public void onItemClick(View view, MyObj obj, int position) {
{ add your work here}
}
});
return false;
}

Resources