How To Create New Java Class In Android Studio

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

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

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

  1. Launch Android Studio, create a new project. You can read article How To Create New Android Studio Project to learn more.
  2. After that right click the default package in Project View’s Android sub view, click New —> Java Class .

    You can also click New —> Package to create a new package or sub package under exist package. In above example, we create a sub package model under com.dev2qa.example.
  3. Then there will popup a dialog which will let you input java class related information. Input class name SMSBean, select Class in Kind drop down list, no super class, not implement any interface. Input package name value as com.dev2qa.example.model. Click OK button.
    android studio new java class detail information dialog
  4. After click 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.
    android studio newly created java class in project view

2. Java Class SMSBean Usage Example.

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

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

READ :   Android Gridlayout Example Programmatically

android send short message example

So if you want to run this example, you should create a new activity and layout xml files to implement user interface. You can read 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

There example include 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;

/**
 * Created by Jerry on 10/16/2017.
 */

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();
            }
        });
    }
}
(Visited 3,359 times, 8 visits today)

Leave a Reply

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.