How to switch between Activities and send data in Android

In Android user interface is displayed through an activity. In Android application development you might face situations where you need to switch between one Activity to another. In this case we will be discussing about switching between one Activity to another and sending data between activities.



Before start we must be follow step 

1. Create application 
2. Create second activity 
3. Create second screen java file
4. Run Application



Before getting complete this article we must be know some code that handling activities. lets with newly activity called SecondScreen.java 

Open the newly activity created follow on this code. We used startActivity() method or startActivityForResult()  follow with this code 


             Intent intent = new Intent( getApplicationContext() , SecondScreen.class);                                                         startActivity(intent);

Send parameter to newly activity 

we used method putExtra(); for send parameter to newly activity


intent.putExtra("key", "value");
// for example 
// username is "key"//user password is "value"
intent.putExtra("username","userpass");



Receive parameter on new activity  we use method called getStringExtra();  


         Intent intent = getIntent();                   intent.getStringExtra("key");
           //Example of this case 
           String  username = intent.getStringExtra("username");





Opening new Activity and expecting result
In some situations you might expect some data back from newly created activity. In that situations startActivityForResult() method is useful. And once new activity is closed you should you use onActivityResult() method to read the returned result.


Intent i = new Intent(getApplicationContext(), SecondScreen.class);startActivityForResult(i, 100); // 100 is some code to identify the returning result
// Function to read the result from newly created activity@Override    protected void onActivityResult(int requestCode,                                     int resultCode, Intent data) {        super.onActivityResult(requestCode, resultCode, data);        if(resultCode == 100){
             // Storing result in a variable called myvar             // get("website") 'website' is the key value result data             String mywebsite = data.getExtras().get("result");        }
    }


for sending to back old activity method startActivityForResult() is used.

// Sending param key as 'website' and value as 'androidshare.info'
i.putExtra("website", "Androidshare.info");
// Setting resultCode to 100 to identify on old activity
setResult(100,in);
Intent i = new Intent();


you should enter new activity in AndroidManifest.xml and new activity between
tag <application>

<activity android:name="ClassName"></activity>



lets start with simple project, So now we have all of code. In this case we
we need to create two activities one call firstscreen_activity.xml and two call secondscreen_activity.xml
and create FirstScreen.java and SecondScreen.java.




Now lets start a simple project


1. Go to File--> New--> Android Project rename your activity to FirstScreen


2. Create new xml file in folder layout call frstscreen_activity.xml or rename main.xml

Right Click on folder layout --> New -->Android XML

3. follow with this code

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/first_screen_activity" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.simple.www.betweenactiviy.FirstScreen">
<TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Name: "/>
<EditText android:id="@+id/name" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginBottom="10dip"/>
<TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Password: " />
<EditText android:id="@+id/pass" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginBottom="10dip"/>
<Button android:id="@+id/btnNextScreen" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Send to Next Screen" android:layout_marginTop="15dip"/>
</LinearLayout>


Out put see like this



4. Open FirstScreen.java and type following with this code..


package com.simple.www.betweenactiviy;

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

public class FirstScreen extends AppCompatActivity {
     EditText inputName,inputpass;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.first_screen_activity);
        inputName = (EditText) findViewById(R.id.name);
        inputpass = (EditText) findViewById(R.id.email);
        Button btnNextScreen = (Button) findViewById(R.id.btnNextScreen);

        //Listening to button event        btnNextScreen.setOnClickListener(new View.OnClickListener() {

            public void onClick(View arg0) {
                //Starting a new Intent                Intent nextScreen = new Intent(getApplicationContext(), SecondScreen.class);

                //Sending data to another Activity                nextScreen.putExtra("name", inputName.getText().toString());
                nextScreen.putExtra("pass", inputpass.getText().toString());

                Log.e("n", inputName.getText()+"."+ inputpass.getText());

                startActivity(nextScreen);

            }
        });
    }
}


6. Create class called SecondScreen.java Right Click on folder package New--> Class and
rename to SecondScreen.java




7. Now create interface for SecondScreen.java bellow on this code, We need to create xml file call secondscreen,xml. Just Right Click on folder layout--> New --> Android XML and rename it to secondscreen.xml. follow with this code,


<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical">

    <TextView android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="You Entered."        android:textSize="25dip"        android:gravity="center"        android:layout_margin="15dip"/>

    <TextView android:id="@+id/txtName"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:layout_margin="15dip"        android:textSize="18dip"/>

    <TextView android:id="@+id/txtpass"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:layout_margin="15dip"        android:textSize="18dip"/>

    <Button android:id="@+id/btnClose"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:layout_marginTop="15dip"        android:text="Close"/>
</LinearLayout>


8. Open SecondScreen.java follow with this code 


package com.simple.www.betweenactiviy;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

/** * Created by Android on 3/22/2017. */
public class SecondScreen extends Activity {
    
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.secondscreen);

        TextView txtName = (TextView) findViewById(R.id.txtName);
        TextView txtEmail = (TextView) findViewById(R.id.txtpass);
        Button btnClose = (Button) findViewById(R.id.btnClose);
        Intent i = getIntent();
        // Receiving the Data        String name = i.getStringExtra("name");
        String email = i.getStringExtra("pass");
        Log.e("Second Screen", name + "." + email);
        // Displaying Received data        txtName.setText(name);
        txtEmail.setText(email);
        // Binding Click event to Button        btnClose.setOnClickListener(new View.OnClickListener() {

            public void onClick(View arg0) {
                //Closing SecondScreen Activity                finish();
            }
        });

    }
}


9. Now all of code is ready we need one point go to AndroidManifest and add with this code.






      <activity android:name=".SecondScreen"></activity>


10. Now start to run our project and test it all together, The program will out 
put see like on this.

FirstScreen

Second Screen







Post a Comment

0 Comments