Reputation: 123
I have a few edittexts and textviews in Fragment A. I use edittexts to get value from user and then I calculate based on my formula and show the result in the textview.
For example Edittext A has 1 and Edittext B has 2 and my formula is add so the textview will show the result as 3.
Also, there is a button, info on the Fragment A. On clicking this button a new fragment B is displayed using the below code:
FragmentTransaction fragmentTransaction =
fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.contentFrag, fragment);
fragmentTransaction.addToBackStack(backStackStateName);
fragmentTransaction.commit();
Now, when I press the back button, I let the system call super.onBackPressed() so that the current Fragment B is removed and I get back Fragment A.
MY PROBLEM:
Now the edittexts retain all their values, however the value I calculated and displayed on TextViews disappears.
I checked onViewStateRestored(Bundle savedInstanceState) method however the parameter savedInstanceState is null.
My Question:
How do I save/retrieve the values for my textviews?
OR
where can I call that code again that calculates the data for textviews ??
Upvotes: 1
Views: 100
Reputation: 2496
To resolve this problem you need use some data layer like Shared Preference or SQL storage. In some primitive way it looks like:
public override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater?.inflate(R.layout.fragment_blank, container, false)
//update you UI from local STORAGE on create
textView.text = sharedPreference.getInt("result_data", 0).toString()//make request local for date
//calling your calculation
button.setOnClickListener {
calculateData(dataInput, object : Callback {
override fun onCalculated() {
//update you UI from local STORAGE layer in MAIN THREAD
Handler(Looper.getMainLooper()).post {
textView.text = sharedPreference.getInt(
"result_data",0
).toString()
}
}
})
}
}
//you calculate and request to data layer
private fun calculateData(inPutData:Int, callback:Callback){
//use background for calculate It will be available.
Thread{
//calculate
val result = inPutData+ ARG_PARAM
//save result in LOCAL STORAGE
sharedPreference.edit().putInt( " result", result).apply()
//update UI
callback.onCalculated()
}.start()
}
interface Callback{
fun onCalculated()
}
Think also about MVP and Presenter. It is also be available. In open source you can find amazing MVP library called moxy. It can restore your view state.
Upvotes: 1
Reputation: 69
Using SharedPreferences will solve your issue just save them in sharedPreferences and clear SharedPreference after Use.
Upvotes: 0