How To Pass Data Using Interface In Android

Introduction 

In this article, we are going to learn how to pass data using the interface in android. In android, when we are working on a large project, most of the time we need to pass data from one activity to another activity or one fragment to another fragment. The interface is one efficient technique to pass data from one class to another class.

Prerequisite

  • Basic knowledge of java
  • Basic knowledge of Interface. You can learn the Interface by clicking here
  • Basic knowledge of android

 Let's start with the implementation.

Step 1

Create a new project in android studio and select an empty activity.

 

Step 2

Import a HeadSet icon from Vector Asset in android and set its id named ic_headset.

Step 3

Go to activity_main.xml and add the following code:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
    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"
    tools:context=".MainActivity">

    <ImageView
        android:id="@+id/imageview"
        android:visibility="visible"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:src="@drawable/ic_headset"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Here we take an imageview that is used to show the headset icon when the headphone plugin to our android device.

Step 5

Create an interface named OnDataShowListener and add the below code:

package com.example.interfaceexample;

public interface OnDataShowListener {
    
    void show(String data);
    
}

Here we are creating an interface and defining a method named show. We take a string parameter in the show() method.

Step 4

Create a new class named MyReceiver.javaThis class is extended to the BroadcastReceiver class.

package com.example.interfaceexample;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class MyReceiver extends BroadcastReceiver {

   OnDataShowListener listener;

    public MyReceiver(OnDataShowListener listener) {
        this.listener = listener;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        String action=intent.getAction();
        if(Intent.ACTION_HEADSET_PLUG.equals(action)){
            //condition to check headset plugin or not

            if (intent.getIntExtra("state",-1) == 0) {
                // head set not plug-in
                listener.show("0");
            } else {
                // headset plug-in
                listener.show("1");
            }
        }

    }
}

Here, we create an OnDataShowListener object and initialize this inside the class constructor. Inside the onReceive() method, we get the intent action using the getAction() method, and then we apply the condition to check whether the event occurred or not. If the event occurred, then we pass "1" to the interface method. Otherwise, we pass "0" to the interface method. 

Step 5

Go to MainActivity.java and add the below code:

package com.example.interfaceexample;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity implements OnDataShowListener{
  ImageView imageView;
  MyReceiver receiver;
  IntentFilter filter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageView=findViewById(R.id.imageview);
        filter=new IntentFilter(Intent.ACTION_HEADSET_PLUG);
        receiver=new MyReceiver(this);
    }


    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(receiver,filter);
    }

    @Override
    protected void onStop() {
        super.onStop();
        unregisterReceiver(receiver);
    }

    @Override
    public void show(String data) {
        if(data.equals("1")){
            imageView.setVisibility(View.VISIBLE);
        }else{
            imageView.setVisibility(View.INVISIBLE);
        }
    }
}

Here, we create the IntentFilter object, MyReceiver class object, and ImageView object. Inside the onCreate() method, we initialize the imageview, intent-filter, and receiver objects. During the initialization of the receiver object, we pass this as a parameter. Here, we are passing listener to MyReceiver class. We call the registerReceiver() method inside onResume() method and call the unregisterReceiver method inside the onStop() method. 

Important Point

Here we need to implement OnDataShowListener, so we are using the implements keyword. Now we need to override the show method. Inside this method we get the data from the interface. If the value is 1 then we set the imageview visibility to VISIBLEotherwise, set it to INVISIBLE.

Step 6

Press the run button and launch the application.

Output

 

Conclusion

In this article, we have seen how to pass data using an interface in android. Thanks for reading and I hope you liked it. If you have any suggestions or queries about this article, please share your thoughts. You can read my other articles by clicking here.

Happy learning, friends!


Similar Articles