Android MySQL Retrofit Full Course – INSERT SELECT UPDATE DELETE SEARCH PAGINATION → Creating Re-usable Utility Methods – Camposha

Android MySQL Retrofit Full Course – INSERT SELECT UPDATE DELETE SEARCH PAGINATION

Creating Re-usable Utility Methods

Introduction

This is part of our Android Full Scientists MySQL CRUD App development free course series. In this lesson we look at the utility methods. These are static methods that will be used by various other classes to perform various functionalities.

Let’s start by creating our class and adding some constants and class members:

    //private  static  final String base_url = "http://192.168.43.91/PHP/scientists/";
    private  static  final String base_url = "http://10.0.2.2/PHP/scientists/";
    //private  static  final String base_url = "http://10.0.3.2/PHP/scientists/";
    private static Retrofit retrofit;
    public static final String DATE_FORMAT = "yyyy-MM-dd";

In the base url you need to specify the URL leading to your php script. Just the base part.

Let’s look at those functions:

1. Obtaining a Retrofit instance

    public static Retrofit getClient(){
        if(retrofit == null){
            retrofit = new Retrofit.Builder()
                    .baseUrl(base_url)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }

        return  retrofit;
    }

The above method gives us a ready to use retrofit instance. Retrofit is our HTTP client hence we’ll need to obtain its instance so that we can make our HTTP requests. Take note we have provided tthe GsonConverterFactory. This is because we’ll be using Gson as our JSON parsing library.

2. Showing a Toast Message

    /**
     * THis method will allow us show Toast messages throughout all activities
     */
    public static void show(Context c,String message){
        Toast.makeText(c, message, Toast.LENGTH_SHORT).show();
    }

Showing a Toast message is a common cross activity operation. Hence it’s much better to define once a simple helper method that will do it. This method can then be called from any activity.

3. EditText Data Validation
    /**
     * This method will allow us validate edittexts
     */
    public static boolean validate(EditText... editTexts){
        EditText nameTxt = editTexts[0];
        EditText descriptionTxt = editTexts[1];
        EditText galaxyTxt = editTexts[2];

        if(nameTxt.getText() == null || nameTxt.getText().toString().isEmpty()){
            nameTxt.setError("Name is Required Please!");
            return false;
        }
        if(descriptionTxt.getText() == null || descriptionTxt.getText().toString().isEmpty()){
            descriptionTxt.setError("Description is Required Please!");
            return false;
        }
        if(galaxyTxt.getText() == null || galaxyTxt.getText().toString().isEmpty()){
            galaxyTxt.setError("Galaxy is Required Please!");
            return false;
        }
        return true;

    }

We will be validating edittext data before attempting to insert or update. Thus we have defined a method that receives edittext param and checks for null and length.

4. Clearing EditTexts

    /**
     * This utility method will allow us clear arbitrary number of edittexts
     */
    public static void clearEditTexts(EditText... editTexts){
        for (EditText editText:editTexts) {
            editText.setText("");
        }
    }

The above method receives an arbitrary number of edittexts, loops through them and clears them all.

5. Showing an Info Dialog

Add the following code:

    /**
     * This method will allow us show an Info dialog anywhere in our app.
     */
    public static void showInfoDialog(final AppCompatActivity activity,String title,
    String message) {
        new LovelyStandardDialog(activity, LovelyStandardDialog.ButtonLayout.HORIZONTAL)
                .setTopColorRes(R.color.indigo)
                .setButtonsColorRes(R.color.darkDeepOrange)
                .setIcon(R.drawable.m_info)
                .setTitle(title)
                .setMessage(message)
                .setPositiveButton("Relax", v -> {})
                .setNeutralButton("Go Home", v -> openActivity(activity, DashboardActivity.class))
                .setNegativeButton("Go Back", v -> activity.finish())
                .show();
    }

The above static method will be invoked whenever we want to show an info dialog. You need to pass the hosting activity, the title of the dialog as well as the message we wish to show. We are using the LoveLyDialogs library to show beautiful standard dialog.

6. Show Single Choice Dialog

Now add the following code:

    /**
     * This method will allow us show a single select dialog where we can select and return a
     * star to an edittext.
     */
    public static void selectStar(Context c,final EditText starTxt){
        String[] stars ={"Rigel","Aldebaran","Arcturus","Betelgeuse","Antares","Deneb",
        "Wezen","VY Canis Majoris","Sirius","Alpha Pegasi","Vega","Saiph","Polaris",
        "Canopus","KY Cygni","VV Cephei","Uy Scuti","Bellatrix","Naos","Pollux",
        "Achernar","Other"};
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(c,
         android.R.layout.simple_list_item_1,
                stars);
        new LovelyChoiceDialog(c)
                .setTopColorRes(R.color.darkGreen)
                .setTitle("Stars Picker")
                .setTitleGravity(Gravity.CENTER_HORIZONTAL)
                .setIcon(R.drawable.m_star)
                .setMessage("Select the Star where the Scientist was born.")
                .setMessageGravity(Gravity.CENTER_HORIZONTAL)
                .setItems(adapter, (position, item) -> starTxt.setText(item))
                .show();
    }

The above method is responsible for showing a dialog list that returns it’s clicked item. Through it we have beautiful material single choice dialog. In our case we are using it to show the star system where our Scientists resides. You can see the method is receiving a Context object as well as an edittext. The selected star will be set to our edittext.

7. Converting String to Date safely

Add the following code:

    /**
     * This method will allow us convert a string into a java.util.Date object and
     *  return it.
     */
    public static Date giveMeDate(String stringDate){
        try {
            SimpleDateFormat sdf=new SimpleDateFormat(DATE_FORMAT);
            return sdf.parse(stringDate);
        }catch (ParseException e){
            e.printStackTrace();
            return null;
        }
    }

The above method is receiving a string and attempting to turn it into a date. We first instantiate SimpleDateFormat class, passing in our date format. Then we invoke it’s parse() method to attempt the conversion and then return the resultant java.util.Date object. If the conversion fails we simply catch the exception and return null.

8. Showing and Hiding ProgressBar

Add the following code:

    /**
     * This method will allow us show a progressbar
     */
    public static void showProgressBar(ProgressBar pb){
        pb.setVisibility(View.VISIBLE);
    }
    /**
     * This method will allow us hide a progressbar
     */
    public static void hideProgressBar(ProgressBar pb){
        pb.setVisibility(View.GONE);
    }

The two simple static methods allow us to show or hide our progressbar. We simply invoke the setVisibility() method, passing in the appropriate constant.

9. Passing and Receiving Serialized Object across activities

Add the following code:

    /**
     * This method will allow us send a serialized scientist objec  to a specified
     *  activity
     */
    public static void sendScientistToActivity(Context c, Scientist scientist,
     Class clazz){
        Intent i=new Intent(c,clazz);
        i.putExtra("SCIENTIST_KEY",scientist);
        c.startActivity(i);
    }

    /**
     * This method will allow us receive a serialized scientist, deserialize it and return it,.
     */
    public  static Scientist receiveScientist(Intent intent,Context c){
        try {
            Scientist scientist= (Scientist) intent.getSerializableExtra("SCIENTIST_KEY");
            return scientist;
        }catch (Exception e){
            e.printStackTrace();
            show(c,"RECEIVING-SCIENTIST ERROR: "+e.getMessage());
        }
        return null;
    }

The first method will send our serialized scientist object to a given activity. How do we serialize it? Well all you need to do is make sure that that class is implementing the serializeable interface, like this:

public class Scientist implements Serializable { ...}

Then we instantiate an Intent object and pass the serialized scientist alongside an identifying key.

Then in the second method, we invoke the getSerializableExtra() method of the intent class, passing in the key. That is enough to allow us send and receive our object.

Full Code

Here’s the full code for the Utils class:

package info.camposha.retrofitmysqlcrud.Helpers;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.yarolegovich.lovelydialog.LovelyChoiceDialog;
import com.yarolegovich.lovelydialog.LovelyStandardDialog;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import info.camposha.retrofitmysqlcrud.R;
import info.camposha.retrofitmysqlcrud.Retrofit.Scientist;
import info.camposha.retrofitmysqlcrud.Views.DashboardActivity;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* A Utility class. Contains reusable utility methods we will use throughout our project.This
* class will save us from typing lots of repetitive code.
*/
public class Utils {
/**
* Let's define some Constants
*/
//supply your ip address. Type ipconfig while connected to internet to get your
//ip address in cmd. Watch video for more details.
private  static  final String base_url = "http://192.168.43.91/PHP/scientists/";
//private  static  final String base_url = "http://10.0.2.2/PHP/scientists/";
//private  static  final String base_url = "http://10.0.3.2/PHP/scientists/";
private static Retrofit retrofit;
public static final String DATE_FORMAT = "yyyy-MM-dd";
/**
* This method will return us our Retrofit instance which we can use to initiate HTTP calls.
*/
public static Retrofit getClient(){
if(retrofit == null){
retrofit = new Retrofit.Builder()
.baseUrl(base_url)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return  retrofit;
}
/**
* THis method will allow us show Toast messages throughout all activities
*/
public static void show(Context c,String message){
Toast.makeText(c, message, Toast.LENGTH_SHORT).show();
}
/**
* This method will allow us validate edittexts
*/
public static boolean validate(EditText... editTexts){
EditText nameTxt = editTexts[0];
EditText descriptionTxt = editTexts[1];
EditText galaxyTxt = editTexts[2];
if(nameTxt.getText() == null || nameTxt.getText().toString().isEmpty()){
nameTxt.setError("Name is Required Please!");
return false;
}
if(descriptionTxt.getText() == null || descriptionTxt.getText().toString().isEmpty()){
descriptionTxt.setError("Description is Required Please!");
return false;
}
if(galaxyTxt.getText() == null || galaxyTxt.getText().toString().isEmpty()){
galaxyTxt.setError("Galaxy is Required Please!");
return false;
}
return true;
}
/**
* This utility method will allow us clear arbitrary number of edittexts
*/
public static void clearEditTexts(EditText... editTexts){
for (EditText editText:editTexts) {
editText.setText("");
}
}
/**
* This utility method will allow us open any activity.
*/
public static void openActivity(Context c,Class clazz){
Intent intent = new Intent(c, clazz);
c.startActivity(intent);
}
/**
* This method will allow us show an Info dialog anywhere in our app.
*/
public static void showInfoDialog(final AppCompatActivity activity,String title,
String message) {
new LovelyStandardDialog(activity, LovelyStandardDialog.ButtonLayout.HORIZONTAL)
.setTopColorRes(R.color.indigo)
.setButtonsColorRes(R.color.darkDeepOrange)
.setIcon(R.drawable.m_info)
.setTitle(title)
.setMessage(message)
.setPositiveButton("Relax", v -> {})
.setNeutralButton("Go Home", v -> openActivity(activity, DashboardActivity.class))
.setNegativeButton("Go Back", v -> activity.finish())
.show();
}
/**
* This method will allow us show a single select dialog where we can select and return a
* star to an edittext.
*/
public static void selectStar(Context c,final EditText starTxt){
String[] stars ={"Rigel","Aldebaran","Arcturus","Betelgeuse","Antares","Deneb",
"Wezen","VY Canis Majoris","Sirius","Alpha Pegasi","Vega","Saiph","Polaris",
"Canopus","KY Cygni","VV Cephei","Uy Scuti","Bellatrix","Naos","Pollux",
"Achernar","Other"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(c,
android.R.layout.simple_list_item_1,
stars);
new LovelyChoiceDialog(c)
.setTopColorRes(R.color.darkGreen)
.setTitle("Stars Picker")
.setTitleGravity(Gravity.CENTER_HORIZONTAL)
.setIcon(R.drawable.m_star)
.setMessage("Select the Star where the Scientist was born.")
.setMessageGravity(Gravity.CENTER_HORIZONTAL)
.setItems(adapter, (position, item) -> starTxt.setText(item))
.show();
}
/**
* This method will allow us convert a string into a java.util.Date object and
*  return it.
*/
public static Date giveMeDate(String stringDate){
try {
SimpleDateFormat sdf=new SimpleDateFormat(DATE_FORMAT);
return sdf.parse(stringDate);
}catch (ParseException e){
e.printStackTrace();
return null;
}
}
/**
* This method will allow us show a progressbar
*/
public static void showProgressBar(ProgressBar pb){
pb.setVisibility(View.VISIBLE);
}
/**
* This method will allow us hide a progressbar
*/
public static void hideProgressBar(ProgressBar pb){
pb.setVisibility(View.GONE);
}
/**
* This method will allow us send a serialized scientist objec  to a specified
*  activity
*/
public static void sendScientistToActivity(Context c, Scientist scientist,
Class clazz){
Intent i=new Intent(c,clazz);
i.putExtra("SCIENTIST_KEY",scientist);
c.startActivity(i);
}
/**
* This method will allow us receive a serialized scientist, deserialize it and return it,.
*/
public  static Scientist receiveScientist(Intent intent,Context c){
try {
Scientist scientist= (Scientist) intent.getSerializableExtra("SCIENTIST_KEY");
return scientist;
}catch (Exception e){
e.printStackTrace();
show(c,"RECEIVING-SCIENTIST ERROR: "+e.getMessage());
}
return null;
}
}
//end

Conclusion

We have looked at Utility methods. Those methods will be re-used by other classes. This class is part of the android live courses season 1. In this course we are developing a full app using android and mysql. Now move over to the next class.

Leave a Reply

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

internal_server_error <![CDATA[WordPress &rsaquo; Error]]> 500