To Examples

SendMessage Example

Goal

Directions

  1. Create an Android Project named SendMessage. Leave MainActivity as the startup activity.
  2. Add a second activity named ReceiveMessageActivity:
    Right click on the Java package it372.smiths.sendmessage >>
        Select New >> Activity >> Empty Activity
        Leave the Generate Layout File box checked.
  3. Change the constraint layout to a linear layout in the activity_main layout.
  4. Change the constraint layout to a linear layout in the activity_receive_message layout.
  5. Add TextView, EditText and Button widgets to the layout.
  6. To the TextView widget add the text "Enter message to send:".
  7. Replace the text in the button by "Send Message".
  8. Set up an onClick event handler for the button.
  9. Add code to the event handler that gets the message from the EditText widget and stores it in a String named message.
  10. To the activity_receive_message layout, add two TextView widgets to the send message layout.
  11. To the first text view, add the text "Received Message:". The second textview will display the message sent from the first activity.
  12. Add code to the event handler in MainActivity that (a) creates an Intent object, (b) adds the String message to it as extra text, (c) starts a new activity using the intent. (Recall that the purpose of an intent is to start up a new activity.) Here is the Java source code to add to the onClick event handler:
    Intent intent = new Intent(this, ReceiveMessageActivity.class);
    // For the extra information in the intent, 
    // the key is "message; the value is message. 
    intent.putExtra("message", message);
    startActivity(intent);
    
  13. At the bottom of the onCreate method in the ReceiveMessage class, add this code to receive the sent message and display it in the text view:
    Intent intent = getIntent( );
    String messageText = intent.getStringExtra("message");
    TextView txtMessage = findViewById(R.id.message);
    txtMessage.setText(messageText);
    

Resulting Source Code Files