Send data from one activity to another activity in android studio

  • Post comments:0 Comments

In this tutorial, we will discuss how to send data from one activity to another activity along with the image in android.

When press on button then edit text and ImageView data show in another activity, means there are two activity-one and activity-two. We will use EditText, Image and Button in Activity-One and will see all data in Activity-Two while pressing the button.

Here, we will create two activities named MainActivity.java and MainActivity2.java.

We will use some method in MainActivity.java file.

So let’s understand with example.

How to send data from one activity to another activity?

Step 1:

First we will create a UI design in the default activity activity_main.xml file.

In activity_main.xml, we will use an ImageView, EditText, and button in another Activity to view the data.

Through ImageView, we “pick an image from gallery” You can also “pick an image from camera and gallery” which we have discussed earlier. But here pick the image from the gallery.

Edit text for text data entry and “view” button for displaying data from another activity.

activity_main.xml code as shown below

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
    <ImageView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_gravity="center"
        android:id="@+id/avatar"
        android:src="@drawable/ic_launcher_background"/>
    <EditText
        android:hint="name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/name"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/view"
        android:text="view"/>
</LinearLayout>

Step 2:

Go to java file MainActivity.java

We will use image so we will pick image from gallery and show in imageview. You already know about “pick image from camera and gallery and show in image view”. So in this java class we use this logic differently.

So here create some methods and initialize it.

Here create three methods pickImage(),displayData() and clearData().

pickImage() to select image from gallery.

DisplayData(), to send data to another activity when button is pressed.

We will use some logic in the button view. You already know about intent that most uses communicate between two components.

putExtra(“key”, value): To send edit text and imageview data via intent.

MainActivity.java code as shown below

MainActivity.java

package com.example.senddata;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
EditText name;
Button view;
ImageView avatar;
//public static final int REQUEST_CAMERA=100;
public static final int REQUEST_STORAGE=101;
//String cameraPermission[];
String storagePermission[];
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findid();
//        cameraPermission=new String[]{Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE};
        storagePermission=new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
        pickImage();
        displayData();
    }
    private void displayData() {
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(MainActivity.this,MainActivity2.class);
                intent.putExtra("name",name.getText().toString());
                intent.putExtra("avatar",imageViewToByte(avatar));
                startActivity(intent);
            }
        });
    }
    private byte[] imageViewToByte(ImageView avatar) {
        Bitmap bitmap=((BitmapDrawable)avatar.getDrawable()).getBitmap();
        ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG,80,byteArrayOutputStream);
        byte[]bytes=byteArrayOutputStream.toByteArray();
        return bytes;
    }
    private void pickImage() {
        avatar.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onClick(View v) {
                int avatar=0;
                if (avatar==0){
                    if (!checkStoragePermission()){
                        requestStoragtePermission();
                    }else{
                        pickFromGallery();
                    }
                }
            }
        });
    }
    private void pickFromGallery() {
        Intent intent=new Intent();
        intent.setType("image/jpg/png");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent,"Pick Image"),101);
    }
    @RequiresApi(api = Build.VERSION_CODES.M)
    private void requestStoragtePermission() {
        requestPermissions(storagePermission,REQUEST_STORAGE);
    }
    private boolean checkStoragePermission() {
        boolean result= ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE)==(PackageManager.PERMISSION_GRANTED);
        return result;
    }
    private void findid() {
        name=findViewById(R.id.name);
        avatar=findViewById(R.id.avatar);
        view=findViewById(R.id.view);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==101&&resultCode==RESULT_OK){
            Uri uri=data.getData();
            Bitmap bitmap=null;
            try {
                bitmap= MediaStore.Images.Media.getBitmap(getContentResolver(),uri);
            }catch (FileNotFoundException e){
                e.printStackTrace();
            }catch (IOException e){
                e.printStackTrace();
            }
            avatar.setImageBitmap(bitmap);
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode){
            case REQUEST_STORAGE:{
                if (grantResults.length>0){
                    boolean storage_accepted=grantResults[0]==PackageManager.PERMISSION_GRANTED;
                    if (storage_accepted){
                        pickFromGallery();
                    }else {
                        Toast.makeText(this, "please enable storage permission", Toast.LENGTH_SHORT).show();
                    }
                }
            }
            break;
        }
    }
}

Step 3:

Now we will create another activity to display the data.

Create a new Activity.

Java ⇾ Right click on package name⇾new ⇾activity ⇾Empty activity. Here the default name MainActivity2 is used for easy understanding.

We are creating data view UI in xml file so create ImageView and TextView to display image and text in activity_main2.xml.

activity_main2.xml code as shown below

activity_main2.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity2">
<ImageView
    android:layout_marginTop="10dp"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:layout_gravity="center"
    android:src="@drawable/ic_launcher_background"
    android:id="@+id/avatarview"/>
    <TextView
        android:id="@+id/nameview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/app_name"
        android:gravity="center"
        android:textSize="20dp"
        android:textStyle="bold"/>
</LinearLayout>

Now open MainActivity.java

Java ⇾ package name ⇾ MainActivity2.java

In MainActivity2.java we will receive the data that is sent by putextra(“key”,value) . Here we will use getStringExtra(“key”) and getByteArrayExtra() method to get the data. And finally set edit text and imageview data in textview and imageview.

MainActivity2.java code as shown below

MainActivity2.java

package com.example.senddata;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity2 extends AppCompatActivity {
ImageView avatar;
TextView nameview;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        findId();
        viewData();
    }
    private void viewData() {
        Intent intent=getIntent();
        String name=intent.getStringExtra("name");
        byte[]bytes=intent.getByteArrayExtra("avatar");
        Bitmap bitmap= BitmapFactory.decodeByteArray(bytes,0,bytes.length);
        avatar.setImageBitmap(bitmap);
        nameview.setText(name.toString());
    }
    private void findId() {
        avatar=findViewById(R.id.avatarview);
        nameview=findViewById(R.id.nameview);
    }
}

Now run your project and see the output.

Send data from one activity to another activity
send data from one activity to another activity

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments