如何将值从一个活动传递到另一个活动/适配器

时间:2018-12-16 20:45:22

标签: java android android-studio android-intent

我正在尝试将Cartadapter的值传递给CartActivity

我的代码如下:

CartActivity.java:

    cartTotalChanged((cartAdapter.getTotal()));

CartAdapter.java:

    public Double getTotal() {
        Double total = 0d;
        try{
            for (MenuItem item : dataList)
                total += item.getTotal();
        }
        catch(Exception e){
            return total;
        }
        finally{
            return total;
        }


    }

cartTotalChanged函数:

 public void cartTotalChanged(Double totalAmount) {
        if (coupon != null) {
            totalAmount = totalAmount - (coupon.getType().equals("fixed") ? coupon.getReward() : ((totalAmount * coupon.getReward()) / 100));
        }
        DecimalFormat decimalFormat = new DecimalFormat("###.##");
        subtotal.setText(decimalFormat.format(totalAmount) + currency);
        double sc = (totalAmount * serviceCharge / 100);
        feeService.setText(decimalFormat.format(sc) + currency);
        total.setText(decimalFormat.format(totalAmount > 0 ? (totalAmount + sc + deliveryFee) : 0) + currency);
        Helper.setCart(sharedPreferenceUtil, cartItems);
    }

我的问题是cartTotalChanged((cartAdapter.getTotal()));返回了Null,我的应用因多线程故障而崩溃。

请帮助

2 个答案:

答案 0 :(得分:2)

要将数据从适配器传递到活动,请使用以下方法:

1。使用接口创建新的接口类。

2。在活动中实现该接口类并覆盖传递数据的方法。

3。在适配器类中,将变量作为内部参数分配给接口方法

接口类:

v1

适配器类:

Class Ainterface
{ 
public void passData(String setData);
 }

活动分类:

  Ainterface ainterface;
  Adapterclass(Context context)
    {
     ainterface=context;
    }

    /*add below line in your onbind or onclick... whenever you want to pass data from adpter to activity use below line*/
    ainterface.passData("set your variable which is load to activity");

我希望它对您有用

答案 1 :(得分:0)

您可以创建如下所示的类:

public class Globals{
private static Globals instance;

// Global variable

private Double cartTotal;


// Restrict the constructor from being instantiated
private Globals(){}

public void setData(Double d){
    this.cartTotal=d;
}
public Double getData(){
    return this.cartTotal;
}

public static synchronized Globals getInstance(){
    if(instance==null){
        instance=new Globals();
    }
    return instance;
}

}

然后在您的适配器上将其设置如下:

Globals g = Globals.getInstance();
g.setData(cartTotal); 

并以以下方式接收您的活动:

Globals g = Globals.getInstance();
Double cartTotal = g.getData();

您可以根据需要设置许多这样的Global变量。

希望这会有所帮助!