无法传递字符串值

问题描述 投票:-2回答:2

我想创建一个简单的计算器,无论我在文本View中写什么,我都得到第二个0的活动值。

    Intent intent = new Intent(this, DisplayResultActivit.class );
    EditText edittext = findViewById(R.id.liczba);
    EditText edittext2 = findViewById(R.id.liczba2);
    int wpis2 = Integer.valueOf(edittext.getText().toString());
    int wpis = Integer.valueOf(edittext2.getText().toString());
    Bundle extras = new Bundle();
    extras.putInt("wpis", wpis);
    extras.putInt("wpis2", wpis2);
    startActivity(intent);

2活动:

    Intent intent = getIntent();
    Bundle extras = intent.getExtras();
    int wpis = 0;
    if (extras != null) {
        wpis = extras.getInt("wpis1");
    }
    int wpis2 = 0;
    if (extras != null) {
        wpis2 = extras.getInt("wpis2");
    }


    TextView tv = findViewById(R.id.result);
        tv.setText(String.valueOf(wpis) + String.valueOf(wpis2));
java android
2个回答
2
投票

正如评论中提到的那样。您还需要将Bundle变量与Intent变量链接。请参阅以下链接:https://zocada.com/using-intents-extras-pass-data-activities-android-beginners-guide/

//create a Bundle object
Bundle extras = new Bundle();
//Adding key value pairs to this bundle
//there are quite a lot data types you can store in a bundle
extras.putString("USER_NAME","jhon Doe");
extras.putInt("USER_ID", 21);
extras.putIntArray("USER_SELCTIONS", [1, 2, 3, 4, 5]);
...
//create and initialize an intent
Intent intent = new Intent(this, NextActivity.class);
//attach the bundle to the Intent object
intent.putExtras(extras);
//finally start the activity
startActivity(intent);

所以你的代码必须是:

Intent intent = new Intent(this, DisplayResultActivit.class );
EditText edittext = findViewById(R.id.liczba);
EditText edittext2 = findViewById(R.id.liczba2);
int wpis2 = Integer.valueOf(edittext.getText().toString());
int wpis = Integer.valueOf(edittext2.getText().toString());
Bundle extras = new Bundle();
extras.putInt("wpis", wpis);
extras.putInt("wpis2", wpis2);

intent.putExtras(extras);

startActivity(intent);

0
投票

只需将您的代码更改为:

Intent intent = new Intent(this, DisplayResultActivit.class );
EditText edittext = findViewById(R.id.liczba);
EditText edittext2 = findViewById(R.id.liczba2);
int wpis2 = Integer.valueOf(edittext.getText().toString());
int wpis = Integer.valueOf(edittext2.getText().toString());
Bundle extras = new Bundle();
extras.putInt("wpis", wpis);
extras.putInt("wpis2", wpis2);
intent.putExtras(extras);
startActivity(intent);

你忘记了putExtras()方法!

© www.soinside.com 2019 - 2024. All rights reserved.