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
}
}
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
**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 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)
}
I am working on an android app using Kotlin language and i need to save the fragment state when i click on another tab and then back to the same tab.
To make sure it is working as expected, i have inserted a counter that counts with each button click as shown in the below code but it seems there is an issue in my code as it resets to 0 each time i change the tab (i.e. not saving the state).
I went through many stackoverflow questions and many videos with no success.
Am i doing something wrong in my code below?
Appreciate your kind support please and thank you in advance.
MainActivity.kt
class MainActivity : AppCompatActivity() {
private var containerFrame: FrameLayout? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
containerFrame = findViewById<FrameLayout>(R.id.containerFrame)
val navigation = findViewById<BottomNavigationView>(R.id.bottomBar)
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectListener)
val fragment = HomeTabFragment() //.newInstance()
addFragment(fragment)
}
private val mOnNavigationItemSelectListener = object : BottomNavigationView.OnNavigationItemSelectedListener {
override fun onNavigationItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.TabHome -> {
val fragment = HomeTabFragment() //.newInstance()
addFragment(fragment)
return true
}
R.id.TabTwo -> {
val fragment = TabTwoFragment()
addFragment(fragment)
return true
}
R.id.TabThree -> {
val fragment = TabThreeFragment()
addFragment(fragment)
return true
}
R.id.TabFour -> {
val fragment = TabFourFragment()
addFragment(fragment)
return true
}
}
return false
}
}
private fun addFragment(fragment: Fragment) {
supportFragmentManager.beginTransaction()
.setCustomAnimations(R.anim.design_bottom_sheet_slide_in, R.anim.design_bottom_sheet_slide_out)
.replace(R.id.containerFrame, fragment, fragment.javaClass.simpleName)
.addToBackStack(fragment.javaClass.simpleName).commit()
}
}
HomeTabFragment.kt
class HomeTabFragment : Fragment() {
var counterOne: Int? = 0
companion object {
fun newInstance(): HomeTabFragment {
val homeTabFragment = HomeTabFragment()
val args = Bundle()
homeTabFragment.arguments = args
return homeTabFragment
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (savedInstanceState != null) {
counterOne = savedInstanceState!!.getInt("counter", 0)
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater!!.inflate(R.layout.fragment_tab_home, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
val testButtonOne = view!!.findViewById<Button>(R.id.testButtonOne)
val resultOne = view!!.findViewById<TextView>(R.id.resultOne)
resultOne.text = "$counterOne"
testButtonOne.setOnClickListener {
counterOne = counterOne!! + 1
resultOne.text = "$counterOne"
}
}
override fun onViewStateRestored(savedInstanceState: Bundle?) {
super.onViewStateRestored(savedInstanceState)
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putInt("counter", counterOne!!)
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<FrameLayout
android:id="#+id/containerFrame"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<android.support.design.widget.BottomNavigationView
android:id="#+id/bottomBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:background="?android:attr/windowBackground"
app:menu="#menu/tabs" />
</LinearLayout>
When i type something in listView and after that rotate it listView returns null instead of text i typed in. Can you please explain why is this happening.
override fun onRestoreInstanceState(savedInstanceState: Bundle?) {
super.onRestoreInstanceState(savedInstanceState)
Log.i("ToDoList","OnRestoreInstanceState was called")
val listSave = savedInstanceState?.getStringArrayList("list")
this.list.clear()
this.list.add(listSave.toString())
adapter = ArrayAdapter <String> (this, android.R.layout.simple_list_item_1,list)
toDoList.adapter = adapter
}
override fun onSaveInstanceState(outState: Bundle?, outPersistentState: PersistableBundle?) {
super.onSaveInstanceState(outState, outPersistentState)
Log.i("ToDoList","OnSaveInstanceState was called")
outState?.putStringArrayList("list", list)
}
Root cause: You override wrong onSaveInstanceState() method.
Solution: You must override onSaveInstanceState(Bundle) instead of onSaveInstanceState(Bundle, PersistableBundle).
Change your code from
override fun onSaveInstanceState(outState: Bundle?, outPersistentState: PersistableBundle?) {
super.onSaveInstanceState(outState, outPersistentState)
Log.i("ToDoList","OnSaveInstanceState was called")
outState?.putStringArrayList("list", list)
}
to
override fun onSaveInstanceState(outState: Bundle?) {
super.onSaveInstanceState(outState)
Log.i("ToDoList","OnSaveInstanceState was called")
outState?.putStringArrayList("list", list)
}