Java 如何在android中将数据从一个活动传输到另一个活动

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20169993/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 23:41:33  来源:igfitidea点击:

How to transfer data from one activity to another in android

javaandroid

提问by user3026034

It might sound simple but I can't make it working. I have two activities. Which first one is a form, and second one is showing data from a JSON file based on values entered in the first activity.

这听起来可能很简单,但我无法让它工作。我有两个活动。第一个是表单,第二个是根据第一个活动中输入的值显示来自 JSON 文件的数据。

So I am trying to make a simple version of it. I have a EditText, and a button, so when they press the button, whatever was in the EditText will be in the TextView of the next activity.

所以我正在尝试制作一个简单的版本。我有一个 EditText 和一个按钮,所以当他们按下按钮时,EditText 中的任何内容都将出现在下一个活动的 TextView 中。

Here is my code so far: Main Activity

到目前为止,这是我的代码: 主要活动

static TextView textView;

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

    textView = (TextView) findViewById(R.id.editText1);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}
public void transferIT(View view){
    Intent intent = new Intent(this, Page.class);
    startActivity(intent);
}

public static String getText(){
    String data = (String) textView.getText();
    return data;
}

Main XML

主 XML

<EditText
    android:id="@+id/editText1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignTop="@+id/textView1"
    android:layout_centerHorizontal="true"
    android:ems="10"
    android:hint="Enter Text to transfer" />

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:text="Transfer it"
    android:onClick="transferIT" />

Second Activity

第二个活动

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_page);
    // Show the Up button in the action bar.
    setupActionBar();


    TextView enteredValue = (TextView)findViewById(R.id.text);

    enteredValue.setText(MainActivity.getText());

}

Second XML

第二个 XML

<TextView
    android:id="@+id/text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="58dp" />

In this way I made a method for the data of the EditText and in the other activity I call it to get access to it. Currently when I press the button it stops working. So what is your solution for having the data of the form in other activity ?

通过这种方式,我为 EditText 的数据创建了一个方法,并在另一个活动中调用它来访问它。目前,当我按下按钮时,它停止工作。那么您在其他活动中拥有表单数据的解决方案是什么?

采纳答案by fada21

In first activity you should put extra argument to intent like this:

在第一个活动中,您应该像这样为意图添加额外的参数:

// I assume Page.class is your second ativity
Intent intent = new Intent(this, Page.class); 
intent.putExtra("arg", getText()); // getText() SHOULD NOT be static!!!
startActivity(intent);

Then in second activity you retrive argument like this:

然后在第二个活动中,您可以像这样检索参数:

String passedArg = getIntent().getExtras().getString("arg");
enteredValue.setText(passedArg);

It's also good to store "arg" String in MainActivity as constant and always refer to it in other places.

将 MainActivity 中的“arg”字符串存储为常量并始终在其他地方引用它也很好。

public static final String ARG_FROM_MAIN = "arg";

回答by VJ Vélan Solutions

You send the data in the intent when you call the second activity. This is pretty fundamental stuff. I suggest you read up on Intents and Parcelable concepts in Android and Serialization in Java that are all related to your question.

当您调用第二个活动时,您在意图中发送数据。这是非常基本的东西。我建议您阅读 Android 中的 Intents 和 Parcelable 概念以及 Java 中的序列化,这些都与您的问题有关。

回答by Raghunandan

You need to change

你需要改变

 static TextView textView;
 textView = (TextView) findViewById(R.id.editText1);

to

 EditText ed1; 
 ed1 = (EditText) findViewById(R.id.editText1);

Coz you have

因为你有

<EditText
android:id="@+id/editText1" // it is edittext not textview

Then

然后

public void transferIT(View view){
String value = ed1.getText().toString()
Intent intent = new Intent(this, Page.class);
intent.putExtra("key",value);
startActivity(intent);
}

Then in onCreate of second activity

然后在第二个活动的 onCreate 中

String value = getIntent().getExtras().getString("key");

回答by vineet

we are sending data from one activity to another where first activity is mainActivity and another is otherActivity for mainActivity

我们正在将数据从一个活动发送到另一个活动,其中第一个活动是 mainActivity,另一个是 mainActivity 的 otherActivity

       `Intent in = new Intent(this, OtherActivity.class);
        in.putExtra("name", etname.getText().toString());
        in.putExtra("job", etjob.getText().toString());
        in.putExtra("sal", etsal.getText().toString());    
        startActivity(in);`

for otherActivity

对于其他活动

   `Intent in = getIntent();
    tv.setText(in.getStringExtra("name")+"\n"+in.getStringExtra("job")+" "+in.getStringExtra("sal"));

`

`

回答by Faisal shahzad

We are sending data from MainActivity to another Activity

我们正在将数据从 MainActivity 发送到另一个 Activity

MainActivity code that is sending data to another activity

将数据发送到另一个活动的 MainActivity 代码

public class MainActivity extends AppCompatActivity
{
    EditText t1, t2, t3;
    Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        t1 = (EditText) findViewById(R.id.edit1);
        t2 = (EditText) findViewById(R.id.edit2);
        t3 = (EditText) findViewById(R.id.edit3);
        button = (Button) findViewById(R.id.move);

        button.setOnClickListener(new View.OnClickListener()
        {
            @Override

            public void onClick(View v)
            {
                String name = t1.getText().toString();
                String email = t2.getText().toString();
                String edu = t3.getText().toString();
                if (name.equals("") || email.equals("") || edu.equals(""))
                {
                    Toast.makeText(getApplicationContext(), "Fill the form", Toast.LENGTH_LONG).show();
                }
                else
                {
                    Intent intent = new Intent(MainActivity.this, Main2Activity.class);
                    intent.putExtra("fname", name);
                    /*putExtra method take two parameter,first is key  and second is value. By using key, we retrieve data
                     */

                    intent.putExtra("femail", email);
                    intent.putExtra("fedu", edu);
                    startActivity(intent);
                    finish();
                }
            }
        });
    }
}

Receiving activity code whose name is Main2Activity.java

接收名称为 Main2Activity.java 的活动代码

public class Main2Activity extends AppCompatActivity
{
    TextView textView1, textView2, textView3;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        textView1 = (TextView) findViewById(R.id.textView1);
        textView2 = (TextView) findViewById(R.id.textView2);
        textView3 = (TextView) findViewById(R.id.textView3);

        //We create  object of Bundle class that help to get data from MainActivity and used its  getString method

        Bundle bn = getIntent().getExtras();
        String name = bn.getString("fname");
        String email = bn.getString("femail");
        String edu = bn.getString("fedu");
        textView1.setText(String.valueOf(name));
        textView2.setText(String.valueOf(email));
        textView3.setText(String.valueOf(edu));
    }
}

回答by Agilanbu

We can implement this using the beneath possible ways,

我们可以使用以下可能的方式来实现这一点,

  1. SharedPrefrence
  2. Instance (getter , setter method)
  3. Constant method
  1. 共享优先级
  2. 实例(getter、setter 方法)
  3. 常数法

1. SharedPrefrence

1. 共享优先级

    public static final String MyPREFERENCES = "MyPrefs"; 

    // set the sharedprefrence
    SharedPreferences sharedpreferences = getActivity().getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedpreferences.edit();
    editor.putString("MasterAgilData", RestoreMasterData);
    editor.commit();

    // restore the sharedprefrence
    String RestoreMasterData1 = sharedpreferences.getString("MasterAgilData", "");

2. Instance

2. 实例

public class instance {

public static AgilDataList StoreAgilDataList;

public static AgilDataList getStoremasterDataList() {
    return StoreAgilDataList;
}

public static void setStoremasterDataList(AgilDataList storemasterDataList) 
{
    StoreAgilDataList = storemasterDataList;
}
}

3. Constant method(static variable)

3.常量方法(静态变量)

public class First_Activity extends Activity {
 public static String USER_FORMATED_NUMBER = null;

 USER_FORMATED_NUMBER="Data you want to pass"; 
}

public class Second_Activity extends Activity {
 String data=First_Activity.USER_FORMATED_NUMBER; 
}