Open In App

How to Use Static Method in Android?

Improve
Improve
Like Article
Like
Save
Share
Report

Android is an open-source operating system, based on the Linux kernel and used in mobile devices like smartphones, tablets, etc. Further, it was developed for smartwatches and Android TV. In this article, we are going to see how we can implement static methods in Android. We will be creating static methods to display Toast, AlertDialog, and redirect to any other activity.

What we are going to build in this article?

Here is a sample video of what we are going to build in this article. Note that we are going to implement this project in the Java language.

Step by Step Implementation

Step 1: Create a New Project

  • Open a new project.
  • We will be working on Empty Activity with language as Java. Leave all other options unchanged.
  • Name the application at your convenience.
  • There will be two default files named activity_main.xml and MainActivity.java.

If you don’t know how to create a new project in Android Studio then you can refer to How to Create/Start a New Project in Android Studio?  

Step 2. Working on XML files

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.

XML




<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp"
    android:gravity="center"
    tools:context=".MainActivity">
  
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/bt_alert"
        android:text="Show alert dialog"/>
  
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/bt_redirect"
        android:text="Redirect to activity"/>
  
</LinearLayout>


Navigate to app > right-click > new > activity > empty activity and name it as “MainActivity2”. Use the following code in activity_main2.xml file

XML




<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:padding="16dp"
    android:gravity="center"
    android:layout_height="match_parent"
    tools:context=".MainActivity2">
  
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/btToast"
        android:text="Display Toast"/>
    
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/bt_alert"
        android:text="Display Alert Dialog"/>
    
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/bt_redirect"
        android:text="Redirect to activity with text"/>
  
</LinearLayout>


Step 3. Working on Java files

Navigate to the MainActivity.java file and use the following code in it. Comments are added to the code to have a better understanding.

Java




package com.example.staticmethod;
  
import androidx.appcompat.app.AppCompatActivity;
  
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
  
public class MainActivity extends AppCompatActivity {
  
    // Initialize variables
    Button btAlert,btRedirect;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // Assign variable
        btAlert=findViewById(R.id.bt_alert);
        btRedirect=findViewById(R.id.bt_redirect);
  
        btAlert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // call static method to display alert dialog
                StaticMethod.displayAlertDialog(MainActivity.this,getString(R.string.app_name),"Welcome to GFG");
            }
        });
  
        btRedirect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // call static method to redirect activity
                StaticMethod.redirect2Activity(MainActivity.this,MainActivity2.class);
            }
        });
  
        // Check condition
        if(getIntent().hasExtra("key0"))
        {
            // When intent has extra data
            // Initialize bundle
            Bundle bundle=getIntent().getExtras();
  
            // Check Condition
            if(bundle!=null)
            {
                // When bundle is not equal to null
                // get all string
                String s1=bundle.getString("key0");
                String s2=bundle.getString("key1");
  
                // Call static method to display toast
                StaticMethod.displayToast(MainActivity.this,s1+" And "+s2);
            }
        }
  
    }
}


Navigate to app > new > class and name it as “StaticMethod”. Use the following code in the StaticMethod.java file

Java




package com.example.staticmethod;
  
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.widget.Toast;
  
import java.util.ArrayList;
  
public class StaticMethod {
    // Create static method to redirect
    public static void redirect2Activity(Activity activity1,Class activity2)
    {
        // Initialize intent
        Intent intent=new Intent(activity1,activity2);
  
        // set flag
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  
        // Start activity
        activity1.startActivity(intent);
  
    }
    
    // Create static method to  redirect
    public static void redirectWithText(Activity activity1,Class activity2, ArrayList<String> arrayList)
    {
        // Initialize intent
        Intent intent= new Intent(activity1,activity2);
        // Use for loop
        for(int i=0;i<arrayList.size();i++)
        {
            // Add extra value
            intent.putExtra("key"+i,arrayList.get(i));
        }
        
        // Set flag
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
          
        // Start activity
        activity1.startActivity(intent);
    }
  
    // Create static method to display toast
    public static void displayToast(Activity activity,String message)
    {
        // Initialize toast
        Toast.makeText(activity,message,Toast.LENGTH_SHORT).show();
    }
  
    // create a static method to display an alert dialog
    public static void displayAlertDialog(Activity activity,String title,String message)
    {
        // Initialize alert dialog
        AlertDialog.Builder builder=new AlertDialog.Builder(activity);
          
        // Set title
        builder.setTitle(title);
              
        // Set message
        builder.setMessage(message);
          
        // Set positive button
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                // Dismiss dialog
                dialogInterface.dismiss();
            }
        });
  
        // show dialog
        builder.show();
    }
  
    // Create static method to display alert dialog with button
    public static AlertDialog.Builder displayAlertWithButton(Activity activity,String title,String message)
    {
        // Initialize alert dialog
        AlertDialog.Builder builder=new AlertDialog.Builder(activity);
         
        // set title
        builder.setTitle(title);
          
        // set message
        builder.setMessage(message);
          
        // Return alert dialog builder
        return builder;
    };
}


Navigate to the MainActivity2.java file and use the following code in it. Comments are added to the code to have a better understanding.

Java




package com.example.staticmethod;
  
import androidx.appcompat.app.AppCompatActivity;
  
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
  
import java.util.ArrayList;
  
public class MainActivity2 extends AppCompatActivity {
  
    // Initialize variables
    Button btToast,btAlertDialog,btRedirect;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
  
        // Assign variable
        btToast=findViewById(R.id.btToast);
        btAlertDialog=findViewById(R.id.bt_alert);
        btRedirect=findViewById(R.id.bt_redirect);
  
        btToast.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Call static method to display toast
                StaticMethod.displayToast(MainActivity2.this,"Welcome to GFG");
            }
        });
  
        btAlertDialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Initialize alert dialog
                AlertDialog.Builder builder=StaticMethod.displayAlertWithButton(
                        MainActivity2.this
                        ,getString(R.string.app_name)
                        ,"You want to close the activity?"
                );
                // Set positive button
                builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        // finish activity
                        finish();
                    }
                });
                // Set negative button
                builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        // Dismiss dialog
                        dialogInterface.dismiss();
                    }
                });
                // Show dialog
                builder.show();
            }
        });
  
        btRedirect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Initialize array list
                ArrayList<String> arrayList=new ArrayList<>();
  
                // Add value in array list
                arrayList.add("Text1");
                arrayList.add("Text2");
  
                // call static method to redirect with text
                StaticMethod.redirectWithText(MainActivity2.this,MainActivity.class,arrayList);
            }
        });
    }
}


Here is the final output of our application.

Output:



Last Updated : 15 Mar, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads