如何将变量从class1的静态函数传递到另一个class2?

时间:2016-04-19 07:09:31

标签: java android

我打算将函数的总权重传递给另一个类。我打算使用getIntent()。但是,静态函数不允许它。如果是这样的话,我应该如何通过呢?下面是class1的静态函数。我在"这个"一部分。

public class Shopping{
public static double getShipping(double total_weight) {
    String weight = Double.toString(total_weight);
    Intent intent = new Intent(this ,shopping1.class);
    intent.putExtra(total_weights, weight);
    this.startActivity(intent);
    double shipping_fee = 0;
   return shipping_fee;
  }
  }

这是2级功能。

public class shopping1 extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.shoppingcart);
    Intent intent = getIntent();
    String weight = intent.getStringExtra(Shopping.total_weights);
    System.out.println(weight);
    new connect5(this,   
  this.findViewById(android.R.id.content)).execute(weight);
}
}

2 个答案:

答案 0 :(得分:0)

this引用对象的当前实例,不能在静态方法中使用它。

由于静态方法不需要执行intance,因此应将对象作为参数传递。

public static double getShipping(Object this, double total_weight)

您需要将Object更改为您正在使用的课程(活动,片段,上下文...)

完成后,您可以像这样调用静态方法

double weight = Shopping.getShipping(this, totalWeight);

实施例

public static double getShipping(Context c, double total_weight) {
    String weight = Double.toString(total_weight);
    Intent intent = new Intent(c ,shopping1.class);
    intent.putExtra(total_weights, weight);
    c.startActivity(intent);
    double shipping_fee = 0;
    return shipping_fee;
}

答案 1 :(得分:0)

Context传递给静态方法。从那里,您可以通过多种方式共享数据。

1)如果您的活动尚未开始,那么您可以使用startActivity()和Intent extras。

2)如果您的活动已经开始,您可以使用LocalBroadcastManager

LocalbroadcastManager.getInstance(context).setBroadcast(intent);