How To Create New Java Class In Android Studio

In android development, the java class is commonly used to implement business logic processes such as database access, send emails, send short messages etc. We always use one java class to encapsulate some related functions.

So we can think java class as the Model role in the MVC pattern. This example will show you how to create a new java class in android studio, and we will create a SMSBean java class that will implement short message send and receives functions.

1.How To Create New Java Class In Android Studio.

  1. Launch Android Studio, create a new project. You can read the article How To Create New Android Studio Project to learn more.
  2. After that right-click the default package in the android studio Project View’s Android subview, then click the New —> Java Class menu item.
  3. You can also click the New —> Package menu item to create a new package or sub-package under exist package. In this example, we create a sub-package model under the existing com.dev2qa.example package.
  4. Then there will popup a dialog that will let you input java class-related information. Input class name SMSBean in the Name input text box, select Class in the Kind drop-down list, do not input any superclass, do not implement any interface. Input package name value such as com.dev2qa.example.model. Click the OK button.
  5. After clicking the OK button, the java class SMSBean has been created successfully. We will add two methods in it, one is sendSMS(), the other is receiveSMS(), please see code comments for detail.

2. Java Class SMSBean Usage Example.

This example will use SMSBean as a short messages manager object, it has two methods sendSMS() and receiveSMS().

The user interface of this example is not complex, there will have two buttons on the screen one is used to send short messages, the other is used to receive short messages. When you click any of the two buttons, an AlertDialog will pop up showing some messages.

If you can not watch the above video, you can see it on the youtube URL https://youtu.be/VhM3qIQkuD8

So if you want to run this example, you should create a new activity and layout XML files to implement the user interface. You can read the below articles if you do not know how to create activity and use event listener.

  1. How To Add Activity In Android Studio
  2. Android Hello World Example Project File Structure
  3. Android Studio Button Listener Key Listener And Browse Url Example

This example includes below core files.

2.1 SMSBean.java

package com.dev2qa.example.model;

import android.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;

import com.dev2qa.example.SMSManagerActivity;

public class SMSBean {

    // This variable will be injected by SMSBean caller, it will be used to show AlertDialog.
    private SMSManagerActivity sourceActivity;

    public SMSManagerActivity getSourceActivity() {
        return sourceActivity;
    }

    public void setSourceActivity(SMSManagerActivity sourceActivity) {
        this.sourceActivity = sourceActivity;
    }

    // Send short message.
    public void sendSMS(String msg)
    {
        if(this.getSourceActivity()!=null) {
            // Create a AlertDialog object.
            AlertDialog dialog = new AlertDialog.Builder(sourceActivity).create();
            String showMsg = "Short message '" + msg + "' has been sent.";
            // Set AlertDialog show message.
            dialog.setMessage(showMsg);
            // Show AlertDialog.
            dialog.show();
            System.out.println(showMsg);
        }else
        {
            System.out.println("Source activity is null.");
        }
    }

    // Receive short message.
    public void receiveSMS()
    {
        if(this.getSourceActivity()!=null) {
            // Create a AlertDialog object
            AlertDialog dialog = new AlertDialog.Builder(sourceActivity).create();
            String showMsg = "Some short messages has been received.";
            // Set AlertDialog show message
            dialog.setMessage(showMsg);
            // Show AlertDialog.
            dialog.show();
            System.out.println(showMsg);
        }else
        {
            System.out.println("Source activity is null.");
        }
    }
}

2.2 activity_smsmanager.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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="com.dev2qa.example.SMSManagerActivity">

    <LinearLayout
        android:layout_width="368dp"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        tools:layout_editor_absoluteX="8dp"
        tools:layout_editor_absoluteY="8dp">

        <Button
            android:id="@+id/btnSendSms"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Send Short Message" />

        <Button
            android:id="@+id/btnReceiveSms"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Receive Short Message" />
    </LinearLayout>
</android.support.constraint.ConstraintLayout>

2.3 SMSManagerActivity.java

package com.dev2qa.example;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import com.dev2qa.example.model.SMSBean;

public class SMSManagerActivity extends AppCompatActivity {

    // Declare SMSBean as a final static variable.
    public static final SMSBean smsBean = new SMSBean();

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

        // set this object in smsBean, it will be used to show send / receive message dialog.
        smsBean.setSourceActivity(this);

        // Get send short message button.
        Button sendSmsBtn = (Button)this.findViewById(R.id.btnSendSms);
        // Register an OnClickListener object what listen to sendSmsBtn on click event.
        sendSmsBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // If sendSmsBtn is clicked, then call smsBean sendSMS method to send short message.
                smsBean.sendSMS("Hello Android World :)");
            }
        });

        // Get receive short message button.
        Button receiveSmsBtn = (Button)this.findViewById(R.id.btnReceiveSms);
        // Register an OnClickListener object what listen to receiveSmsBtn on click event.
        receiveSmsBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // If receiveSmsBtn is clicked, then call smsBean receiveSMS method to receive coming in short messages.
                smsBean.receiveSMS();
            }
        });
    }
}

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.