当我在Android中将捆绑从一个活动传递到另一个活动时,为什么它不传递数据?

时间:2018-07-29 10:19:21

标签: android android-intent android-activity android-bundle multiscreen

我正在尝试将私有字符串从MainActivity传递到另一个活动。这是代码:

MainActivity

public class MainActivity extends AppCompatActivity {
private String data1;
private String data2;

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

    //Direct to data Input page and then to the next page
    TextView text = findViewById(R.id.data_text);
    text.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            setContentView(R.layout.datalayout);
            EditText data = findViewById(R.id.Data1);
            MainActivity.this.data1 = data.getText().toString();
            data = findViewById(R.id.Data2);
            MainActivity.this.data2 = data.getText().toString();
            v = (ImageView) findViewById(R.id.continueNext);
            MainActivity.this.redirectToAnotherPage(v, MainActivity.this, AnotherActivity.class);

        }
    });

private void redirectToAnotherPage(View view, final Context baseActivity, final Class newActivity) {
    view.setOnClickListener(new View.OnClickListener() {
    @Override
        public void onClick(View v) {
            Intent myIntent = new Intent(baseActivity, newActivity);
            //Pass data between MainActivity and the launching activity using bundle
            Bundle bundle = new Bundle();
            bundle.putString("Data1",data1);
            bundle.putString("Data2",data2);
            myIntent.putExtras(bundle);
            //End MainActivity before starting new activity
            MainActivity.this.finish();
            startActivity(myIntent);
        }
    });
}

另一个活动

public class AnotherActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.page);

    //Get data from MainActivity using Bundle
    Bundle viewData = getIntent().getExtras();
    String dataToInclude = viewData.getString("Data1");
    Toast toast = Toast.makeText(getApplicationContext(),dataToInclude,Toast.LENGTH_LONG);  
    toast.show();
}

当我传递String类型的data1和data2时,看不到Toast消息。我在这里做什么错了?

3 个答案:

答案 0 :(得分:1)

您的代码难以理解:
1)你在做什么? setContentView(R.layout.datalayout);

2)data中的data.getText().toString();

如果您看到吐司中没有任何文字,则表示dataToIncludenull或为空。
因此,请重点检查data1data2变量。
编辑:点击text后,监听器将立即执行:
新版式将显示为空的EditText,其空字符串将存储在data1data2中,然后使用捆绑包中的空字符串打开新活动。

答案 1 :(得分:0)

您没有调用toast.show()。这样做-

Toast toast = Toast.makeText(getApplicationContext(),dataToInclude,Toast.LENGTH_LONG);
toast.show();

Toast.makeText(getApplicationContext(), dataToInclude, Toast.LENGTH_LONG).show();

答案 2 :(得分:0)

您可以仅在意图上使用putExtra方法,如下所示:

myIntent.putExtra("key", value);

在其他活动中,只需按照以下意图获取数据

String value = getIntent().getStringExtra("key");