首页 文章

将数据加载到android中的另一个活动

提问于
浏览
0

我刚开始学习使用Android Studio开发Android应用程序,我制作了一个示例应用程序,它将在一个活动(firstActivity)上存储两个ExitText的值,并在我点击'load'时将这两个值加载到另一个活动(secondActivity)上secondActivity上的按钮 . 但是我无法从firstActivity加载到secondActivity上 . 有人可以帮我弄这个吗 .

提前致谢 .

编辑:

这是场景 .

我有三个活动说ActivityOne,ActivityTwo和ActivityThree

在ActivityOne上我有EditText1,EditText2和Button1当我单击Button1数据时,我输入EditText1和EditText2应该保存 . (Sharedpreferences)

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

非常感谢您的帮助 .

2 回答

  • 0

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

    这是一个示例(此代码在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");
    

    这样,您就可以将数据从1个活动传递到另一个活动 .

    希望这个例子有助于清除它:)

  • 0

    如果要在活动之间传递值,可以使用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
    

相关问题