【问题标题】:Load data onto another activity in android将数据加载到android中的另一个活动
【发布时间】:2014-08-15 14:52:17
【问题描述】:

我刚开始学习使用 Android Studio 开发 android 应用程序,我制作了一个示例应用程序,当我单击secondActivity 上的“加载”按钮。但是我无法从 firstActivity 将它们加载到 secondActivity 上。有人可以帮我解决这个问题吗?

提前致谢。

编辑:

这是场景。

我有三个活动,分别是 ActivityOne、ActivityTwo 和 ActivityThree

在 ActivityOne 上,我有 EditText1、EditText2 和 Button1 当我单击 Button1 数据时,我输入到 EditText1 和 EditText2 应该被保存。 (共享偏好)

在 ActivityTwo 上,我有另一个名为 ButtonShow 的按钮。 当我单击 ButtonShow 时,它应该打开 ActivityThree,其中包含我之前从 ActivityOne(EditText1 和 EditText2)存储的值。

非常感谢您的帮助。

【问题讨论】:

标签: android load


【解决方案1】:

如果你想在活动之间传递值,你可以使用 SharedPreferences 例如: A类

String username2= "AAAA";
//to store the value use
SharedPreferences userDetails = A.this.getSharedPreferences("userdetails", MODE_PRIVATE);
                Editor edit = userDetails.edit();
                edit.clear();
                edit.putString("username", username2);
                //if you need to store more values you can add  here
                edit.commit();

B类

//to get the value just do this
SharedPreferences userDetails = getSharedPreferences("userdetails", MODE_PRIVATE);
            String  USERNAME = userDetails.getString("username", "");
            //if you need to get more value do it here
    //now you have your value username2 in USERNAME, now you can use it everywhere 

【讨论】:

    【解决方案2】:

    您应该使用捆绑功能。 您可以将变量放入此捆绑包中,然后将其附加到一个活动中,一旦该活动启动,您就可以将放入其中的变量取出,然后再次使用它们。

    这是一个示例(此代码在 FirstActivity 中调用,可能是在单击按钮时):

    Intent i = new Intent(getActivity(), SecondActivity.class);
    Bundle variablesBundle = new Bundle();
    Bundle.putString("EditText1Data", string1);
    Bundle.putInt("EditText2Data", int1);
    i.putExtras(variablesBundle);
    startActivity(i);
    

    然后在 SecondActivity 中调用这段代码(可能在 onCreate() 或任何你想要的地方)

    Bundle bundle = getIntent().getExtras();
    String myString = bundle.getString("EditText1Data");
    

    这样您就可以将数据从一项活动传递到另一项活动。

    希望这个例子有助于澄清一点:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多