Useless app can send and receive

Ok as promised I will show you how to send data using an Intent.
Let’s get started by creating the xml layouts for your new activity.
At this location “res\layout\” create the xml file “second_choice.xml” and copy this.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <EditText
        android:id="@+id/my_edit_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_above="@+id/go_back_button"
        android:layout_marginBottom="30dp"
        android:hint="Say Somthing"/>
    <Button
        android:id="@+id/go_back_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Click to go back"/>

</RelativeLayout>
Notice that we created an EditText in the second layout. We will need it later.
Now that we have the xml file created, lets create the activity.
In your package under the Java folder create the activity “SecondChoice.java” and copy the following code.
package com.thewannabeprogrammer.wbpuselessapp;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;

public class SecondChoice extends AppCompatActivity {
 private String myNameRecieved;
 private String yourMessage = "You have nothing to say?";
   @Override
   public void onCreate(Bundle savedInstanceState){
     super.onCreate(savedInstanceState);
     setContentView(R.layout.second_choice);
   }
}
Now lets go back to the main activity and add the code for the second choice of the drawer layout in the switch statement in the “onItemClick listener” of the Adapter View.
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position){
go to Case 2, replace the current code with the code below.
case 2:
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);
    // enter a title here
    alertDialogBuilder.setTitle("What is your name?");
    
    final EditText editText = new EditText(MainActivity.this);
    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.MATCH_PARENT);
    editText.setLayoutParams(lp);
    alertDialogBuilder.setView(editText);
    alertDialogBuilder.setCancelable(false)
            .setPositiveButton("GO",new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    // go to the second choice activity
                    drawerLayout.closeDrawer(drawerList);
                    myName = editText.getText().toString();
                    Log.d("TAG", "myName "+myName);
                    Intent i2 = new Intent(MainActivity.this, SecondChoice.class);
                    i2.putExtra("val1", myName);
                    startActivityForResult(i2, 1);
                }
            })
            .setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog,int id) {
                    dialog.cancel();
                }
            });

    // create alert dialog
    AlertDialog alertDialog = alertDialogBuilder.create();

    // show the dialog
    alertDialog.show();
    break;
In here we are creating an alert dialog that will pop out when you click on the secondChoice drawer item.
In the dialog box you will see an edit box where you can enter your name and click GO.
This will send you to the activity SecondChoice where you will see what you entered previously in the edit box.
Now the key issue here is how we are sending data between activities.
in the code you copied, take a look at the Intent i2.
Just above the Intent i2 part, notice that we loaded the value of the editText into the variable myName, which we are adding to the intent like so “i2.putExtra(“val1”, myName)
Note the string “val1” is just a reference that we add so that when the second activity gets loaded, it could call that same string to reference and retrieve the value in the myName variable.
Now back to that i2 Intent. Take a look at the code startActivityForResult(i2, 1); This does not only send the value of myName variable to the second activity but it also waits for something to be sent back from the second activity. That’s the “ForResult” part.
Ok enough of the MainActivity lets move back to the second activity and setup the code that receives the value and returns a value to the MainActivity.
So in the SecondChoice activity copy this code in the onCreate methode below “setContentView(R.layout.second_choice);”
myNameRecieved = getIntent().getStringExtra("val1").toString();

final EditText editText = (EditText) findViewById(R.id.my_edit_text);
editText.setHint("Say Something "+ myNameRecieved);

findViewById(R.id.go_back_button).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        yourMessage = editText.getText().toString();
        Intent returnIntent = new Intent();
        returnIntent.putExtra("result",yourMessage);
        setResult(Activity.RESULT_OK,returnIntent);
        finish();
    }
});
In this code we are retrieving the value sent by the intent from the MainActivity and putting it in the myNameRecieved variable.
The edit text is used to retrieve the new value entered which will be sent back to the MainActivity and displayed in the Textview.
That value is sent back through the
returnIntent.putExtra(“result”,yourMessage);
setResult(Activity.RESULT_OK,returnIntent);
Now let’s go back to the Main Activity and see how that returned value is retrieved.
I know! lots of back and fourth… you are probably getting dizzy. It’s the last one I promise.
Just open the MainActivity and copy this method anywhere in between other methods.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // Verify which request we're responding to
    if (requestCode == 1) {
        // Making sure the request was successful

        if (resultCode == RESULT_OK) {
            messageText.setText(data.getStringExtra("result"));
        }
    }
}
The onActivityResult is called by the returnIntent of the secondChoice activity.
In here we check if the requestcode is = 1 to make sure that the result request was successful and we take the result and display it in the text view.
And finally lets go back to res\values\strings.xml and change the second choice from “this also” to “this does something”.

Comments

Popular Posts