How to Make Android Apps 5

Passing Data between ActivitiesIn this tutorial I’ll show you how to create multiple Android Activities and then how you’d go about passing data between Android Activities. I also cover Intents.

I’ll specifically cover creating multiple Activity layouts, setting up the manifest file, sending data to an Activity when you open it, retrieving data when an Activity closes and what Intents are. All of the code can be found below and it is heavily commented to help you learn.

If you like videos like this, it helps others find it if you share on Google Plus with a click here

Code from the Video

second_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:gravity="left"
    android:padding="20dp">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/enter_name_text_view"/>

    <EditText
        android:layout_width="185dp"
        android:layout_height="wrap_content"
        android:id="@+id/users_name_edit_text"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:paddingTop="10dp">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Enter"
            android:onClick="onSendUsersName"/>

        <TextView
            android:id="@+id/calling_activity_info_text_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/calling_activity_message"/>

    </LinearLayout>

</LinearLayout>

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center|top"
    android:padding="20dp"
    tools:context="com.newthinktank.switchingscreens2.app.MainActivity">

    <TextView
        android:text="@string/get_the_name_text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textStyle="bold"
        android:textSize="20sp"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Go Get It"
        android:layout_marginTop="20dp"
        android:onClick="onGetNameClick"/>

    <TextView
        android:text="@string/users_name_sent_back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textStyle="bold"
        android:textSize="20sp"
        android:layout_marginTop="20dp"
        android:id="@+id/users_name_message"/>

</LinearLayout>

MainActivity.java

package com.newthinktank.switchingscreens2.app;

import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;


public class MainActivity extends ActionBarActivity {

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


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void onGetNameClick(View view) {

        // We have to state that are intention is to open another Activity. We do so
        // by passing a Context and the Activity that we want to open

        Intent getNameScreenIntent = new Intent(this, SecondScreen.class);

        // We ask for the Activity to start and don't expect a result to be sent back
        // startActivity(getNameScreenIntent);

        // We use startActivityForResult when we expect a result to be sent back

        final int result = 1;

        // To send data use putExtra with a String name followed by its value

        getNameScreenIntent.putExtra("callingActivity", "MainActivity");

        startActivityForResult(getNameScreenIntent, result);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // Create the TextView so I can put the users name on it
        TextView usersNameMessage = (TextView) findViewById(R.id.users_name_message);

        // Get the users name from the previous Activity
        String nameSentBack = data.getStringExtra("UsersName");

        // Add the users name to the end of the textView
        usersNameMessage.append(" " + nameSentBack);

    }
}

SecondScreen.java

package com.newthinktank.switchingscreens2.app;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class SecondScreen extends Activity{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Set the layout for the layout we created
        setContentView(R.layout.second_layout);

        // Get the Intent that called for this Activity to open

        Intent activityThatCalled = getIntent();

        // Get the data that was sent

        String previousActivity = activityThatCalled.getExtras().getString("callingActivity");

        TextView callingActivityMessage = (TextView)
                findViewById(R.id.calling_activity_info_text_view);

        callingActivityMessage.append(" " + previousActivity);
    }

    public void onSendUsersName(View view) {

        // Get the users name from the EditText
        EditText usersNameET = (EditText) findViewById(R.id.users_name_edit_text);

        // Get the name typed into the EditText
        String usersName = String.valueOf(usersNameET.getText());

        // Define our intention to go back to ActivityMain
        Intent goingBack = new Intent();

        // Define the String name and the value to assign to it
        goingBack.putExtra("UsersName", usersName);

        // Sends data back to the parent and can use RESULT_CANCELED, RESULT_OK, or any
        // custom values starting at RESULT_FIRST_USER. RESULT_CANCELED is sent if
        // this Activity crashes
        setResult(RESULT_OK, goingBack);

        // Close this Activity
        finish();

    }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.newthinktank.switchingscreens2.app" >

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.newthinktank.switchingscreens2.app.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <!-- name defines the class that handles setting up the Activity
        label will be the title for the activity
        theme defines the theme to use -->

        <activity android:name=".SecondScreen"
            android:label="Get Name"
            android:theme="@style/AppTheme"/>

    </application>

</manifest>

18 Responses to “How to Make Android Apps 5”

  1. PhYtOn says:

    Hi Derek,
    I am waiting for the next tutorial.

  2. Matheus says:

    Hey Derek.

    First of all: thanks for this tutorial. It’s really great and is helping me a lot.

    After watching this video and the next one, I thought it would be great for practice switching activitis by making an app that works like this: the main screen have a button, when you click this button you go to other activity and you can write a name, and then you gou to another one so you can press the age and then, finally, you go to the last one so you can type your height.
    When you click the last button, it creates an object and sends it to the first activity that displays it in the screen.

    It worked great, but I’m not sure I’m doing it the most efficient way.

    In the last activity, I typed setResult(..) and sent the data to the last screen, and did it with all of them until the data arrived in the main activity. I uploaded it on pastebin so you can see it if you don’t get it (I’m bad at explaining things in english): http://pastebin.com/R8XDEzrV

    So… Am I doing it the right way?

    • Derek Banas says:

      You’re very welcome Matheus. Yes that works as well. I’m not optimizing everything so that I can really focus in on the main concepts. As the tutorial continues I’ll make much more optimized apps.

  3. Scott says:

    Love the tutorials! Just started following along in Eclipse, when I tried to install Android Studio I had so many problems over 2 days solid I just went back to Eclipse! (acronym – AS+ Android Studio Supposedly) for example:
    1. current AS+ version is beta, nothing like your tut.
    2. SDK mgr, all sorts of problems ???
    3. AVD mgr didn’t recognize my device but adb.exe did.
    4. a lot of install content errors recommending to deactivate anti-virus protection even after completely uninstalled.
    5. on & on & on for 2 days
    ** I don’t think it uninstalls cleanly, leaves a lot of directories and sdk versions.
    Any suggestions ?
    Windows 8.1 (ugh!) 64-bit, i5 duo-core 16 gb RAM

    • Derek Banas says:

      Thank you 🙂 I’m doing my best to make the tutorial work with Eclipse so if you prefer it stick with it. I did cover some common ways to solve AS problems in part 6 of this tutorial series. I hope that helps

  4. David says:

    Derek, let me get this straight. Every screen requires it’s own XML file, but they can all use strings.xml for global XML settings?

  5. Arshad says:

    Hi Derek,

    How are you? I hope your doing well…

    First of all: thanks alot for this tutorial. But it would be great if you can upload another video on how to launch another activity from button or just a multiple activities without data transfering.

    Thanks,
    And keep it up your doing a very job.

  6. LvLiangHan says:

    Why the app crashes that when press the back button to exit ? Thank you!

    • Derek Banas says:

      What errors show up in the LogCat panel?

      • LvLiangHan says:

        The code is same as yours , very very Thank You ! You are so nice ! ; )

        11-10 01:51:10.339 30651-30651/com.lvianghan.switchingscreens2 E/AndroidRuntime﹕ FATAL EXCEPTION: main
        Process: com.lvianghan.switchingscreens2, PID: 30651
        java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=0, data=null} to activity {com.lvianghan.switchingscreens2/com.lvianghan.switchingscreens2.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method ‘java.lang.String android.content.Intent.getStringExtra(java.lang.String)’ on a null object reference
        at android.app.ActivityThread.deliverResults(ActivityThread.java:3432)
        at android.app.ActivityThread.handleSendResult(ActivityThread.java:3475)
        at android.app.ActivityThread.access$1300(ActivityThread.java:139)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1258)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5086)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
        Caused by: java.lang.NullPointerException: Attempt to invoke virtual method ‘java.lang.String android.content.Intent.getStringExtra(java.lang.String)’ on a null object reference
        at com.lvianghan.switchingscreens2.MainActivity.onActivityResult(MainActivity.java:76)
        at android.app.Activity.dispatchActivityResult(Activity.java:5446)
        at android.app.ActivityThread.deliverResults(ActivityThread.java:3428)
                    at android.app.ActivityThread.handleSendResult(ActivityThread.java:3475)
                    at android.app.ActivityThread.access$1300(ActivityThread.java:139)
                    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1258)
                    at android.os.Handler.dispatchMessage(Handler.java:102)
                    at android.os.Looper.loop(Looper.java:136)
                    at android.app.ActivityThread.main(ActivityThread.java:5086)
                    at java.lang.reflect.Method.invoke(Native Method)
                    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
                    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)

  7. Patrick Lawrence says:

    Hey Derek, I was following your tutorial word for word and I seem to keep getting an error you’re not. I’ve even looked through your code and everything seems to be exactly the same. It’s at the very end in the MainActivity.java the very bottom where we are doing the text views.

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    TextView usersNameMessage = (TextView)
    findViewById(R.id.users_name_message);

    String nameSentBack = data.getStringExtra(“UsersName”);

    usersNameMessage.append(” ” + nameSentBack);

    The “users_name_message” bit is in red and telling me that it cannot resolve the symbol. Sorry if that doesn’t make sense

  8. alvin says:

    on my second screen the title bar doesnt show up

Leave a Reply

Your email address will not be published.

Google+