Android 如何将文本设置为从其他活动中获得的结果

Android 如何将文本设置为从其他活动中获得的结果,android,Android,大家好,上面是我的activity1类,我查询它以获取地址并设置文本。我如何将activity2类中的其他文本视图设置为我从activity1获得的地址结果?提前感谢。在活动1中: String address = info.getAddress(); if(address != null && !address.isEmpty()) { TextView txtSearch = (TextVie

大家好,上面是我的activity1类,我查询它以获取地址并设置文本。我如何将activity2类中的其他文本视图设置为我从activity1获得的地址结果?提前感谢。

在活动1中:

String address = info.getAddress();

            if(address != null && !address.isEmpty()) 
            {
                TextView txtSearch = (TextView) getView().findViewById(R.id.text_search);
                txtSearch.setText(address);}
在activity2 onCreate中:

    // Create an intent to launch the second activity
    Intent intent = new Intent(getBaseContext(), activity2.class);

    // Pass the text from the edit text to the second activity
    intent.putExtra("address", address);

    // Start the second activity
    startActivity(intent);

您可以根据自己的要求选择不同的方式。 一种方法是按照另一个答案中的建议使用意图。 在第一个活动中,您可以使用Intent开始第二个活动,并将地址与Intent一起发送

    // Get the intent that was used to launch this activity
    Intent intent = getIntent();

    // Get the text that was passed from the main activity
    String address= intent.getStringExtra("address");
第二项活动

  Intent i=new Intent(context,ACTIVITY.class);
    i.putExtra("add", ADDRESS);
    context.startActivity(i);
若您不需要使用Intent,您可以在第一个活动中保存数据,并在第二个活动中检索数据。 保存数据

Intent intent = getIntent();
 String address= intent.getStringExtra("add");
获取数据

SharedPreferences shared=getSharedPreferences("app_name", Activity.MODE_PRIVATE);
shared.edit().putString("add", "ADDRESS").commit();

或者,您可以将其保存在缓存中,并在第二个活动中获取它

如果您只在这两个活动之间共享字符串地址,那么最简单的方法是使用puttera将其作为额外数据发送,并在另一个答案中描述

但是,如果你要在多个活动中使用地址,并且需要对所有的地址都是相同的,如果一个活动改变了地址,它就被改变了,那么你应该考虑使用SysPoopys/

SharedPreferences shared=getSharedPreferences("app_name", Activity.MODE_PRIVATE);
        String add=shared.getString("add", null);
以及检索任何活动中的数据:

String address = info.getAddress();
String prefName = "address";
SharedPreferences prefs;
prefs = getSharedPreferences(prefName, MODE_PRIVATE);
prefs.edit().putString(prefName, address).commit();
如果没有名称为address的共享pref,则将为address分配“null”,因此您可以测试该值以确保pref已经存在

SharedPreferences shared = getSharedPreferences(prefName, MODE_PRIVATE);
String address = shared.getString(prefName, null);