RaineShadow RaineShadow - 3 months ago 13
Android Question

android - Use text from EditText in activity1 on button in activity2

I want the button in activity2 to show the text that was entered in EditText in activity1. This is my first app using more than one activity so I may just be trying to pass things wrong. I've tried setting the button text to the direct EditText value by saving it but that didn't work right. Any direction would be much appreciated!

activity1

start_day is called when the button in activity1 is pressed. It sends the app into activity2.

public class AddTasksActivity extends AppCompatActivity {

public final static String taskOne = "Task One Content";

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

public void start_day(View view){
Intent intent = new Intent(this, DayTasksActivity.class);
intent.putExtra("taskOne", taskOne);
startActivity(intent);
}
}


activity2

Currently the button shows the text from activity1 "Task One Content." So I'm doing something right in passing things around but I can't seem to get anything but that working and I haven't quite found anything like this yet.

public class DayTasksActivity extends AppCompatActivity {

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

Bundle bundle = getIntent().getExtras();
String taskOne = bundle.getString("taskOne");

Button buttonTaskOne = (Button) findViewById(R.id.button_task_one);
buttonTaskOne.setText(taskOne);
}
}

Answer
  1. First give the id to your views in layout files
  2. Then instantiate your views in respective Activity class
  3. Then get he text from edit text and save it in bundle and pass it
  4. get the value from the bundle in second activity
  5. set the value in button

Activity1

public class AddTasksActivity extends AppCompatActivity {

private EditText myEditText;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add_tasks);
    myEditText = findViewById(R.id.put_your_id_here_form_layout_file);
}

public void start_day(View view){
    Intent intent = new Intent(this, DayTasksActivity.class);
    intent.putExtra("taskOne", myEditText.getText().toString());
    startActivity(intent);
 }
}

Activity2

public class AddTasksActivity extends AppCompatActivity {

private Button buttonTaskOne;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_day_tasks);
    buttonTaskOne = (Button) findViewById(R.id.button_task_one);
    Bundle bundle = getIntent().getExtras();
    String taskOne = bundle.getString("taskOne");
    if (taskOne != null){
        buttonTaskOne.setText(taskOne);
    }
 }
}
Comments