I'm making an app, and in my app I have a currency, bunz, that gets constantly updated, depending on what a player has purchased. I made a fragment that I put in every single activity to keep track of the bunz, and have a singleton class, Bunz, that keeps track of how many bunz a player has. My fragment's code looks like the following:
package com.example.bunzclicker;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.example.bunzclicker.bunz.Bunz;
import java.math.BigDecimal;
import java.util.Timer;
import java.util.TimerTask;
public class fragment1 extends Fragment {
private TextView bunz_count;
private TextView money_count;
private Bunz bunz;
private Handler handler;
int delay = 1000;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
bunz = Bunz.getInstance();
handler = new Handler();
final View view = inflater.inflate(R.layout.fragment1, container, false);
handler.postDelayed(new Runnable(){
public void run(){
update(view);
handler.postDelayed(this, delay);
}
}, delay);
return view;
}
public void update(View view){
bunz_count = (TextView) view.findViewById(R.id.final_bunz_count);
money_count = (TextView) view.findViewById(R.id.final_money_count);
//System.out.println(bunz.getBaker1());
TextView bunzCount = (TextView) (view.findViewById(R.id.final_bunz_count));
BigDecimal number = bunz.getBunz().add((BigDecimal.valueOf
(bunz.getBaker1()).multiply(BigDecimal.valueOf(.1)))
).add((BigDecimal.valueOf(bunz.getBaker2()).multiply(BigDecimal.valueOf(.2)))).
add((BigDecimal.valueOf
(bunz.getBaker3()).multiply(BigDecimal.valueOf(.4)))).
add((BigDecimal.valueOf
(bunz.getBaker4()).multiply(BigDecimal.valueOf(.8)))).
add((BigDecimal.valueOf(bunz.getBaker5()).multiply(BigDecimal.valueOf(1)))).
add((BigDecimal.valueOf(bunz.getBaker6()).multiply(BigDecimal.valueOf(2)))).
add((BigDecimal.valueOf(bunz.getBaker7()).multiply(BigDecimal.valueOf(4)))).
add((BigDecimal.valueOf(bunz.getBaker8()).multiply(BigDecimal.valueOf(5)))).
add((BigDecimal.valueOf(bunz.getBaker9()).multiply(BigDecimal.valueOf(10))));
System.out.println(number);
bunz.setBunz(number);
System.out.println(bunz.getBunz());
bunzCount.setText("Bunz: " + bunz.getBunz());
money_count.setText("Money: " + bunz.getMoney());
}
}
The problem is that there is some lag in updating the UI, which causes issues. How can I fix this?