-1

i am creating a activity having two fragment . one for summation-substraction other for displaying total value the main activity contains variable (total) if in fragment the value is sum then variable (total) is increased by entered value otherwise it is decreased by entered value

and this variable (total) is displayed in second fragment

Shabnam Siddiqui
  • 579
  • 4
  • 13

3 Answers3

1

you can use interface for get and set data into fragment with activity . or you can create the static variable and call it from class name like this in mainActivity

public static int total=0

in fragment where you want to call and change its value just call like this MainActivity.total=your value

Amit pandey
  • 1,149
  • 1
  • 4
  • 15
1

Put this function in your activity:

public void setTotal(int newTotal) {
this.total = newTotal;
}

Then call this in your fragment:

((YourActivityClassName)getActivity()).setTotal(newTotal);

Although I would suggest you storing variables that you need app wide in shared preferences or Room if you have many variables. Or using bundles to send data between activitys/fragments.

Hope this helps!

aztek
  • 73
  • 5
1

Solution 1:

//activity
    val variable=0

//fragment
    activity?.variable = newValue

Solution 2: Use Singleton Class

object AppData{
    val variable=0
}

//activity : use the variable
AppData.variable

//fragment
AppData.variable = newValue

Solution 3: (Recommended) Use MVVM

class ActivityVM : ViewModel {
        val variable = MutableLiveData<Int>()
    }

//activity
activityVM= ViewModelProviders.of(activity).get(ActivityVM::class.java)

activityVM.variable.observe(this,Observer{ 
//it <- value
})

//fragemnt
activityVM= ViewModelProviders.of(activity).get(ActivityVM::class.java)
activityVM.variable.postValue(newValue)
KKSINGLA
  • 1,284
  • 2
  • 10
  • 22