I have some private Int variables initialized in kotlin.
class multiply : AppCompatActivity() {
.
.
private var score:Int=0;
private var score2=0;
.
.
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState);
if(savedInstanceState==null) {
score=score2;
}
.
.
}
.
.
override fun onRestoreInstanceState(savedInstanceState: Bundle) {
super.onRestoreInstanceState(savedInstanceState)
score=savedInstanceState.getInt("val_score");
}
My question is while I rotate my phone, a new is activity is created and in the present code score is getting assigned to 0. Is there any way for initializing only once? What is the way out?
I have some calculations inside onCreate using score. Since onRestoreInstanceState is executed after onCreate is there any way to keep the value of score unaffected on screen rotation other than defining it in onStart?
Your code should look like this:
class MultiplyActivity : AppCompatActivity() {
private var score = 0;
private var score2 = 0;
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if(savedInstanceState != null) {
score = savedInstanceState.getInt("score", 0)
score2 = savedInstanceState.getInt("score2", 0)
}
}
override fun onSaveInstanceState(bundle: Bundle) {
super.onSaveInstanceState(bundle)
bundle.putInt("score", score)
bundle.putInt("score2", score2)
}
Related
I have a Fragment_A on Activity_1 and whenever a Button is clicked in the Fragment_A I have to start Activity_2 witch have a Fragment_B
So i need to send a user_Id from the Fragment_A in Activity 1 to the Fragment_B in activity_2.
Is there any way to send the data directly from Frament_A in Activity_1 to Fragment_B in Activity_2?
I am a student , so i am a beginner and i did found this question here but i didn't understand what to do to solve this
I did find some solution about interface but i didn't know how to do it
i keep getting class_id null
Language : Kotlin
Class : ClassesAdapter
class ClassesAdapter(val c:Fragment,val l:android.content.Context? ,val classeslist: ArrayList<Classes>) : RecyclerView.Adapter <ClassesAdapter.ClassesViewHolder> (){
lateinit var auth: FirebaseAuth
lateinit var DataBase : DatabaseReference
lateinit var DataBase2 : DatabaseReference
lateinit var clipboardManager: ClipboardManager
private lateinit var mListener :onItemClickListener
interface onItemClickListener {
fun onItemClick(position :Int)
}
/*fun setOnItemClickListener(listener : onItemClickListener){
// mListener=listener
}*/
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ClassesViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.class_items2,parent,false)
//return ClassesViewHolder(itemView,mListener)
return ClassesViewHolder(itemView,)
}
override fun onBindViewHolder(holder: ClassesViewHolder, position: Int) {
val currentitem = classeslist[position]
holder.classname.text = currentitem.name
holder.classrole.text = currentitem.role
holder.itemView.setOnClickListener {
val intent = Intent(l, DetailedClassActivity::class.java)
intent.putExtra("classId", currentitem.class_id)
l!!.startActivity(intent)
}
Class : Acttivity2 who has the fragment iwant to send it the class_id`
package com.example.myclass1
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.viewpager2.widget.ViewPager2
import com.example.myclass1.databinding.ActivityDetailedClassBinding
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.google.firebase.auth.FirebaseAuth
class DetailedClassActivity : DrawerBaseActivity() {
private lateinit var binding: ActivityDetailedClassBinding
//lateinit var toggle: ActionBarDrawerToggle
override lateinit var auth: FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding= ActivityDetailedClassBinding.inflate(layoutInflater)
setContentView(binding.root)
// add it to change the toolbar title's to the activity name
val actionBar = supportActionBar
if (actionBar != null) {
val dynamicTitle: String = HomeActivity::class.java.simpleName
//Setting a dynamic title at runtime. Here, it displays the current activity name
actionBar.setTitle("Home")
}
// navigate between documents ,notification and chatroom : tabLayout
val tablayout2 : TabLayout =findViewById(R.id.tab_layout2)
val viewpager21 : ViewPager2 =findViewById(R.id.viewPager21)
val adapter =PagerAdapter2(supportFragmentManager,lifecycle)
viewpager21.adapter = adapter
TabLayoutMediator(tablayout2, viewpager21) { tab, position ->
when(position){
0->{tab.text="Documents"}
1->{tab.text="Note"}
2->{tab.text="ChatRoom"}
}
}.attach()
val intent=getIntent()
var classId= intent.getStringExtra("classId")
fun getMyData(): String? {
return classId
}
}
class : fragment B
enter code here
btnAddcourse.setOnClickListener {
var nameofthecourse = Coursename.text.toString().trim()
var course_id :String?=DataBase3.push().key
var classId = arguments?.getString("classId")
val dateofthecourse: String = formatTimeStamp()
if (TextUtils.isEmpty(nameofthecourse)) {
// No name added
Coursename.error = "No name added !! Please enter the name of the class"
}
else{
courseList.add(Course(course_id,nameofthecourse,dateofthecourse,classId))
coursesAdapter.notifyDataSetChanged()
Toast.makeText(activity,"Adding Course Success", Toast.LENGTH_SHORT).show()
//Toast.makeText(activity,"class_id is null ", Toast.LENGTH_SHORT).show()
if (classId != null) {
addCourseToDataBase(course_id!!,nameofthecourse,dateofthecourse,classId)
}else{
Toast.makeText(activity,"class_id is null ", Toast.LENGTH_SHORT).show()
}
}
}
fragmentA
button.setOnClickListener {
val intent = Intent(requireContext(), Activity2::class.java)
intent.putExtra("user_Id", user_Id)
startActivity(intent)
}
activity2
val intent = getIntent()
val message = intent.getStringExtra("user_Id")
val bundle = Bundle()
bundle.putString("user_Id", message) //the part i updated
val fragmet= fragment_B()
fragmet.setArguments(bundle)
fragmentB
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_B, container, false)
val bundle = this.arguments //the part i updated
val myString = bundle!!.getString("user_Id", "defaultValue") //the part i updated
}
1-Read About Singleton Design Pattern
for make user id global in all app
read it to understand
2-Shared Preference :save user id to can using for all app
Shared Preferences
3-you can try Navigation Args : better choose for performance
and can use it for movement through you app
Navigation
When i click on multiple images of recyclerview then multiple audios start playing without stopping the previous one. It is getting irritating. I hope someone can help me fix this. I have read about singleton class and using only one instance of media player but couldn't understood how to implement it correctly.
class RecylerViewAdapter (var context: Context, var arrayList: ArrayList<ItemModel>) :
RecyclerView.Adapter<RecylerViewAdapter.ItemHolder>() {
var mediaPlayer: MediaPlayer? = null
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemHolder {
val viewHolder = LayoutInflater.from(parent.context)
.inflate(R.layout.sound_item_list, parent, false)
return ItemHolder(viewHolder)
}
override fun onBindViewHolder(holder: ItemHolder, position: Int) {
val itemModel: ItemModel = arrayList[position]
holder.soundImage.setImageResource(itemModel.soundImage)
holder.soundTitle.text = itemModel.soundTitle
mediaPlayer = MediaPlayer.create(context, itemModel.soundTrack)
mediaPlayer!!.isLooping = true
holder.soundImage.setOnClickListener {
Toast.makeText(context, itemModel.soundTitle, Toast.LENGTH_LONG).show()
mediaPlayer!!.start()
}
}
override fun getItemCount(): Int {
return arrayList.size
}
class ItemHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var soundImage = itemView.soundImage
var soundTitle = itemView.soundTitle
}
}
Code seems to be good. Remember to call release() on your player and initialise it again with new media file before playing it. Maybe it could be useful for you to implement a MediaPlayer.OnCompletionListener in which you could call player.release()
Or maybe this is enough:
holder.soundImage.setOnClickListener {
mediaPlayer!!.release()
mediaPlayer = null
mediaPlayer = MediaPlayer.create(context, itemModel.soundTrack)
Toast.makeText(context, itemModel.soundTitle, Toast.LENGTH_LONG).show()
mediaPlayer!!.start()
}
I'll recommend to initialize just single object of MediaPlayer in your fragment or activity in which your RecyclerView is located and than pass that object into adapter as a parameter and use it and dont forget to release MediaPlayer in onDestroy() of activity or onDestroyView() of fragment by calling MediaPlayer?.release(). In adapter OnClickListener() you have to stop the media player calling MediaPlayer?.stop() and MediaPlayer?.reset() and than add the new source
class RecylerViewAdapter (var context: Context, var arrayList: ArrayList<ItemModel>, var mediaPlayer : MediaPlayer?) :
RecyclerView.Adapter<RecylerViewAdapter.ItemHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemHolder {
val viewHolder = LayoutInflater.from(parent.context)
.inflate(R.layout.sound_item_list, parent, false)
return ItemHolder(viewHolder)
}
override fun onBindViewHolder(holder: ItemHolder, position: Int) {
val itemModel: ItemModel = arrayList[position]
holder.soundImage.setImageResource(itemModel.soundImage)
holder.soundTitle.text = itemModel.soundTitle
holder.soundImage.setOnClickListener {
mediaPlayer?.stop()
mediaPlayer?.reset()
mediaPlayer?.setDataSource(itemModel.soundTrack)
mediaPlayer?.isLooping = true
mediaPlayer?.start()
}
}
override fun getItemCount(): Int {
return arrayList.size
}
class ItemHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var soundImage = itemView.soundImage
var soundTitle = itemView.soundTitle
}
}
**this is my Activity pager **
private const val TAG = "CarpagerActivity"
var carList: ArrayList<Car>? = null
var mSerializer : JsonSerializer? = null
class CarPagerActivity : AppCompatActivity(){
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_car_pager)
mSerializer = JsonSerializer("CarTrinkApp.json",
applicationContext)
try {
carList = mSerializer!!.load()
} catch (e: Exception) {
carList = ArrayList()
Log.e("Error loading cars: ", "", e)
}
// create list of fragments, one fragment for each car
var carFragmentList = java.util.ArrayList<Fragment>()
for (car in carList!!) {
carFragmentList.add(ShowCarFragment.newInstance(car))
}
val pageAdapter = CarPagerAdapter(supportFragmentManager, carFragmentList)
findViewById<ViewPager>(R.id.pager_cars).adapter = pageAdapter
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
val myPost = data?.getIntExtra("adapterPosition", 123)
println(myPost)
println("adadadada")
}
class CarPagerAdapter(fm: FragmentManager, private val carFragmentList: ArrayList<Fragment>) : FragmentPagerAdapter(fm, FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
override fun getCount() = carFragmentList.size
override fun getItem(position: Int) = carFragmentList[position]
}
}
[![I want add animation to this transition ][1]][1]
**and also this page in Fragment Layout **
[1]: https://i.stack.imgur.com/qFB3b.png
Fading animation, see reference here
viewPager.setPageTransformer(false) { page, position ->
// do transformation here
page.alpha = 0f
page.visibility = View.VISIBLE
// Start Animation for a short period of time
page.animate()
.alpha(1f).duration =
page.resources.getInteger(android.R.integer.config_longAnimTime)
.toLong()
}
or
viewPager.setPageTransformer(false) { page, position ->
// do transformation here
page.rotationY = position * -70
}
i have to create a multiplication method in application 1 call the logic from application 2 and print the output in application 2. basically i have to create 2 application
here is my code
MainActivity1 : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var firstValue = editText_first_no.text.toString()
var secondValue = editText_second_no.text.toString()
add_button.setOnClickListener{
//Here i have to call method from my second app
var result = multiPlyValue(firstValue.toLong(), secondValue.toLong())
Toast.makeText(this, result , Toast.LENGTH_SHORT).show()
}
}
}
MainActivity2 : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
fun multiPlyValue(firstValue: Long, secondValue: Long): Long{
return firstValue*secondValue
}
}
I tried to send data from adapter A to Activity A.
In adapter A I used Intent.putExtra() and it's success.
And in Activity A I used getStringExtra() to get the data.
When I clicked an item , the getStringExtra() returns null value. But, when I don't close my app and click the same item again, I got the value.
This is Adapter A :
class AdapterA (private val daftarMeja: ArrayList<DaftarMeja.Meja>, private val clickListener: (DaftarMeja.Meja) -> Unit) : RecyclerView.Adapter<RecyclerView.ViewHolder>(){
companion object {
const val ID_MEJA = "idMeja"
const val STATUS_MEJA = "statusMeja"
}
override fun getItemCount(): Int {
return daftarMeja.size
}
fun updateData(dataBaru: ArrayList<DaftarMeja.Meja>) {
daftarMeja.clear()
daftarMeja.addAll(dataBaru)
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
val cellForRow = layoutInflater.inflate(R.layout.item_meja,parent,false)
return PartViewHolder(cellForRow)
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
(holder as PartViewHolder).bind(daftarMeja[position], clickListener)
}
inner class PartViewHolder (itemView: View): RecyclerView.ViewHolder(itemView){
fun bind(meja: DaftarMeja.Meja, clicklistener: (DaftarMeja.Meja) -> Unit){
itemView.tv_table_name.text = meja.nama
if(meja.status){
itemView.container_table.setBackgroundResource(R.color.colorTableAvailable)
itemView.tv_table_name.setTextColor(Color.BLACK)
}
else {
itemView.container_table.setBackgroundResource(R.drawable.gradient)
itemView.tv_table_name.setTextColor(Color.WHITE)
}
itemView.setOnClickListener {
val intent = Intent(itemView.context, ActivityA::class.java)
intent.putExtra(ID_MEJA, meja.id)
intent.putExtra(STATUS_MEJA, meja.status)
itemView.context.startActivity(intent)
clicklistener(meja)
}
}
}
}
To get the data in Activity A :
val idMeja = intent.getStringExtra(MejaAdapter.ID_MEJA)
When the item clicked :
private fun mejaItemClicked() {
val intent = Intent(this, ActivityB::class.java)
startActivity(intent)
}
I don't know where is the problem. Please help me to solve this
1)In Activity onCreate() , this is the right mode to test Bundle
Bundle extras = getIntent().getExtras();
if (extras != null)
{
if (extras.containsKey("YOURNAMEPARAM"))
{....your assign}
}
2)Wend lanch a intent FIRST you put in extra of intent the value
val intent = Intent(this, ActivityB::class.java)
intent.putExtra("YOURNAMEPARAM",yourvalue);
startActivity(intent)
3)Make sure that the type of variable you are passing is consistent and use the "PUT" and the "GET"corresponding to the variable.
4)Make sure the activity is not already open, otherwise the onCreate () method will not be called and your getextra will not be re-evaluated.