java - 如何访问在另一个 Activity 的主要 Activity 中声明的变量

标签 java android android-activity global-variables

我不知道这是否可行,或者它们是否是更好的编程实践,但我想知道如何在另一个 Activity 中使用在主要 Activity 中声明的变量。源代码 fragment 示例如下所示...

public class MainActivity extends ActionBarActivity {
private int a, b;
private EditText first, second;

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

    first = (EditText) findViewById(R.id.first_entry);
    second = (EditText) findViewById(R.id.second_entry);   }

public void doMath(View view) throws Exception {
    try {
        if (!first.getText().toString().equals("")) {
            a = Integer.parseInt(first.getText().toString());
        }
        else {
            a = 0;
        }
        if (!second.getText().toString().equals("")) {
            b = Integer.parseInt(gpa_credits1.getText().toString());
        }
        else {
            b = 0;
        }

        int sum = a + b;    }catch (Exception e) {}

现在,我想创建一个新 Activity 来使用变量“sum”来做一些数学运算,例如...

public class first_year_second_semester extends Activity {


 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.newActivity);
    int blah = 5;
    private TextView soln;
    soln = (TextView) findViewById(R.id.the_soln);
    soln = (blah / sum) //i.e sum from the previous activity...please i need this
}

最佳答案

您可以使用 Intent 或使用共享首选项将值从一个 Activity 传递到另一个 Activity 。

Intent intent=new Intent(MainActivity.this,year_second_semester.class);
intent.putExtras("sum",sum);
startActivity(intent);

然后在下一个 Activity 中你可以获得这个值。

或者使用共享首选项: 内部类: SharedPreferences 共享;

在 onCreate 内部: shared=getSharedPreferences("app",Context.MODE_PRIVATE);

计算总和后,即在做 sum=a+b 之后;

Editor edit=shared.edit();
edit.putString("sum",sum);
edit.commit();

在接下来的 Activity 中: 类内: SharedPreferences 共享;

内部创建: shared=getSharedPreferences("app",Context.MODE_PRIVATE);

无论你想要什么: String yourvalue=shared.getString("sum","默认值");

这里您的值(value)将是主要 Activity 的总和。

关于java - 如何访问在另一个 Activity 的主要 Activity 中声明的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29594648/

相关文章:

java - 为什么我无法在此代码中使用 setLocation 定位 JButton?

java - 正则表达式:区分边界匹配 ^ 和 Negation

java - Android 应用程序在 startActivity() 处崩溃

android - 我如何在 android 中按字母顺序对 Realm 结果列表进行排序?

android - 任务 ':app:processDebugResources' 的 Flutter 执行失败。 AAPT : error: resource string/app_name not found

java - 如何使用 toString 检索我的类中的信息以及如何获取我的方法来计算此类中的 "GPA"?

android - 即使在 android 中使用 Fused Location API 时将上下文传递给 GoogleApiClient,GoogleApiClient 也会给出空指针

android - 无法完成 Activity

android - Google map 和列表合二为一

android - onStop() 触发时我必须保留 Activity 数据吗?