问题:我在以下代码处设置了断点:

 intent.putExtra(WorkoutRoutinesActivity.EXTRA_WORKOUT_NAME, workoutName);
 intent.putExtra(WorkoutRoutinesActivity.EXTRA_WORKOUT_DAYS, workoutDays);


,当我在调试模式下运行应用程序时,两者均显示为null。 workoutName包含传递给新活动的简单String,而workoutDays包含String数组。

完整的代码如下:

public class CreateWorkoutActivity extends Activity {


public final String TAG = this.getClass().getSimpleName();
protected String[] workoutDays = new String[7];
protected String workoutName;

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

     Button mNextButton = (Button) findViewById(R.id.next_button1);
     CheckBox satBox = (CheckBox) findViewById(R.id.sat_checkbox);
     CheckBox sunBox = (CheckBox) findViewById(R.id.sun_checkbox);
     CheckBox monBox = (CheckBox) findViewById(R.id.mon_checkbox);
     CheckBox tuesBox = (CheckBox) findViewById(R.id.tues_checkbox);
     CheckBox wedBox = (CheckBox) findViewById(R.id.wed_checkbox);
     CheckBox thursBox = (CheckBox) findViewById(R.id.thurs_checkbox);
     CheckBox friBox = (CheckBox) findViewById(R.id.fri_checkbox);

    final EditText mWorkoutName = (EditText) findViewById(R.id.workout_name1);
    workoutName = mWorkoutName.getText().toString();

    Log.i(TAG, workoutName);



   if (satBox.isChecked()) {
      workoutDays[0] = new String(satBox.getText().toString());
   }

    if (sunBox.isChecked()) {
        workoutDays[1] = new String(sunBox.getText().toString());
    }

    if (monBox.isChecked()) {
        workoutDays[2] =  new String(monBox.getText().toString());
    }

    if (tuesBox.isChecked()) {
        workoutDays[3] = new String(tuesBox.getText().toString());
    }

    if (wedBox.isChecked()) {
        workoutDays[4] =  wedBox.getText().toString();
    }

    if (thursBox.isChecked()) {
        workoutDays[5] =  satBox.getText().toString();
    }

    if (friBox.isChecked()) {
        workoutDays[6] = friBox.getText().toString();
        Log.i(TAG, workoutDays[6]);
    }




    mNextButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.i(TAG, workoutDays.toString());
            Intent intent = new Intent(CreateWorkoutActivity.this, WorkoutRoutinesActivity.class);
            intent.putExtra(WorkoutRoutinesActivity.EXTRA_WORKOUT_NAME, workoutName);
            intent.putExtra(WorkoutRoutinesActivity.EXTRA_WORKOUT_DAYS, workoutDays);
            Log.i(TAG, workoutDays.toString());
            startActivity(intent);

        }
    });

}

最佳答案

问题不在于意图,而在于您获取workoutName的方式(这是空值)。您创建活动,设置final EditText mWorkoutName = (EditText) findViewById(R.id.workout_name1);,然后立即通过workoutName = mWorkoutName.getText().toString();询问输入值,但是此时用户仍未输入任何内容。您应该将第二行放在下面的侦听器中(因此只有在用户按下mNextButton之后才激活它。最好在其后进行一些检查并向用户发送一条消息,告知他们需要填写该字段(如果确实如此)必要)。

10-08 07:22