首页 > 解决方案 > How to pass variable from different class to the main class

问题描述

I want to pass some variables to the main class and do some calculations depend on the user input in the previous interfaces. I've tried to use setters and the getters but the most confusing part is how to use those variable to do the calculation without displaying them in TextView.

public class Weight extends AppCompatActivity implements View.OnClickListener {

    public static AutoCompleteTextView userWeight;
    private Button secondPage;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_weight);

        userWeight =(AutoCompleteTextView) findViewById(R.id.weight);
        secondPage = (Button) findViewById(R.id.toHeightPage);

        secondPage.setOnClickListener(this);

    }

    }

    private void enterWeight(){
        String weight = userWeight.getText().toString().trim();

        if(TextUtils.isEmpty(weight)){
            Toast.makeText(Weight.this,"Please Enter your weight", Toast.LENGTH_SHORT).show();

        return;
    }

in this class I want to get the value of the weight and use it in the main class, and here is the main class code.

public class Main_Interface extends AppCompatActivity {
    public TextView results;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main__interface);

        Toolbar toolbar = findViewById(R.id.toolbar1);
        setSupportActionBar(toolbar);

        results = (TextView)findViewById(R.id.results);

    }
    public void calculateBMR(){

    }

I am going to use the calculation method to use all of the variables in the app to give me the results.

标签: javaandroid

解决方案


如果您需要在两个活动之间传递一些数据,您应该为此使用 Intent:

class ActivityA extends AppCompatActivity {
    ...

    void startActivityB(String code) {
        Intent i = new Intent(this, ActivityB.class);
        i.putExtra("code", code);
        startActivity(i);
    }
}


class ActivityB extends AppCompatActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ...
        String code = getIntent().getStringExtra("code");
    }
}

有关更多详细信息,请查看官方文档开始另一个活动


推荐阅读