从textView中的另一个类添加整数

时间:2019-04-08 19:01:31

标签: java android textview

MainActivity类中,我有一个TextView,我想用另一个类中的整数填充它。整数是某些数据库计算的结果。如何设置TextView文本和另一个类的'sum'整数?谢谢!

MainActivity TextView

valFormula.setText( here I need to pass the sum Integer);

这是我计算总和值的类:

public class CalculateItems extends AppCompatActivity {
        MyDBHandler myDb;
        String timeStamp = String.valueOf(TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()));
        int sum;

    public void myResult() {
                List<Integer> items = new ArrayList<>();
                myDb = new MyDBHandler(this);
                Cursor cursor = myDb.getItemsToday();
                if (cursor !=null) {
                        while (cursor.moveToNext()) {
                                int timeWhenAdded = cursor.getInt(1);
                                int timePassed = Integer.parseInt(timeStamp) - timeWhenAdded;
                                int price = total - (int) ((percentageToDecrease / 100) * discount);
                                items.add(price);
                        }
                }
                //This is the variable that I want to have it displayed in the textView:
                sum = 0;
                for (int i : items)
                        sum += i;
        }

1 个答案:

答案 0 :(得分:3)

通常,您不应该更新其他活动的视图。如果您只需要计算一些内容,请创建静态方法

public class CalculateItems {
    public static int myResult() {
        int sum = 0;
        List<Integer> items = new ArrayList<>();
        MyDBHandler myDb = new MyDBHandler(this);
        Cursor cursor = myDb.getItemsToday();
        if (cursor !=null) {
            while (cursor.moveToNext()) {
                int timeWhenAdded = cursor.getInt(1);
                int timePassed = Integer.parseInt(timeStamp) - timeWhenAdded;
                int price = total - (int) ((percentageToDecrease / 100) * discount);
                items.add(price);
            }
        }
        for (int i : items)
            sum += i;
        return sum;
    }
}

并在需要时从主要活动中调用它

valFormula.setText(CalculateItems.myResult());