ANDROID TUTORIAL-Working with Inner Classes and Singletons

in #utopian-io6 years ago (edited)

The Java language has many interesting features to work with and as such was one of the reasons it became the official android development language, well, until kotlin came along.

Many of Java's vast array of features are used in android, some others are rarely utilized even though they help solve a lot of problems when building an android application.

I will be explaining two of such rarely used concepts which if put into practice would really save android developers a great deal of stress.


Image Source

What Will I Learn?

  • You will learn how to effectively use inner classes in your android application
  • You will learn how to use singletons in your android application

Requirements

  • Android Studio 2.3 and above
  • Basic Knowledge of native Android development using Java

Difficulty

  • Intermediate

Tutorial Contents

INNER CLASSES

The importance of inner classes in android cannot be over emphasized. it is a very important feature to utilize when developing your android application and it can help preserve your development pattern (MVC, MVP etc.), if any of them is used.

An effective way of using inner classes in android is when working with the Asynctask class. This class helps perform high end operations (e.g network querying) on a background thread to avoid overloading the android main thread.

To begin, create new project in android studio and in your main activity class, create an inner class that extends Asynctask. This class being an abstract class must implement a method called doInBackground().

private class InnerClass extends AsyncTask<String, String, String>{

@Override
        protected void onPreExecute() {
            super.onPreExecute();
        }
        @Override
        protected String doInBackground(String[] params) {
            return "";
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
        }
}

To run the asynctask, call its execute method within your activity/fragment.

new InnerClass().execute();

The doInBackground() method is where the heavy tasks are performed and the results of the operations performed in this method are delivered in onPostExecute() and almost always require the results to be updated or shown on views within the activity. However if these views are not defined within the asynctask class, there is a problem passing them to the onPostExecute() method, this is where the concept of inner classes comes in.

Since you have defined your asynctask class as an inner class of the main activity, you can simply declare your views as global variables, instantiate them in the onCreate() of your activity and use them in your onPostExecute() method.

   public class MainActivity extends AppCompatActivity {
   private TextView mText;
   @Override
    protected void onCreate(Bundle savedInstanceState) {
    mText = (TextView) findViewById(R.id.text);
    new InnerClass().execute();
    }


    private class InnerClass extends AsyncTask<String, String, String>{

@Override
        protected void onPreExecute() {
            super.onPreExecute();
        }
        @Override
        protected String doInBackground(String[] params) {
            return "";
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            mText.setText(s);
        }
    }
}

This saves a lot of stress in terms of updating your views using the results from an operation. The concept of inner classes can also be used with broadcast receivers and other important components of android.

SINGLETONS

Singletons are classes in Java that implement a software engineering concept known as the singleton pattern that restricts the number of instantiations of an object from a class to just one.

In android, a singleton class has a single global object variable of the class that is instantiated in a public and static method method and preferably synchronized to help synchronize its usage. This method returns the single object of the class as required by other classes (activities and fragments).

Begin by creating a new project or preferably continue with the project already created for Inner class.
Create a new class named MySingleton and type in the following code

public class MySingleton {
    private static MySingleton ourInstance;
    public synchronized static MySingleton getInstance() {
        if (ourInstance == null){
            ourInstance = new MySingleton ();
        }
        return ourInstance;
    }

    private MySingleton () {
    }

The constructor of the singleton is made private to prevent additional instantiation in other classes. The getInstance() method returns the single object of the class and creates a new one if no previous object exists.

Getters and setters can then be used in the singleton to get and set objects of any kind and retaining just a single instance of the object.

The singleton provides a storage medium for your data which doesnt depend on the lifecycle of your activity/fragment, making it effective for many activities/fragments using just a single instance of the class. To explain this, an example of how to temporarily store an arraylist of videos is shown below.

Create a second activity preferably called SecondActivity, then in your singleton create a global variable of an arraylist of videos called videosArrayList and type in the following code

private ArrayList<Videos> videosArrayList;

public void setArrayList(ArrayList<Videos> videosArrayList){
        this.videosArrayList= videosArrayList;
    }
    public ArrayList<Videos> getArrayList(){
        return videosArrayList;
    }

In your main activity after getting the cursor or some other source to your videos use the following line of code to save to the singleton by passing in the arraylist to the setter method.

MySingleton.getInstance().setArrayList(videosArrayList);

In your second activity, get the stored arraylist by calling the getter method using the following line of code

ArrayList<Videos> receivedVideos = MySingleton.getInstance().getArrayList();

This clearly shows your list of videos as preserved across activities and same can be done for fragments and other android classes.

This practice for example helps solve a Transaction too Large error if the same amount of data was passed directly between the activities. The singleton thus acts as a temporary storage medium that can be accessed anywhere.

The singleton helps reduce the usage of larger data storage frameworks like Sqlite and realm and makes your development faster with less lines of code.

Thanks for reading, hopefully this boosts your android development best practices.



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

Your contribution cannot be approved because it does not follow the Utopian Rules.

  • Only whitelisted unofficial mirror repositories accepted. You can find whitelist below.
  • If I am wrong about this is an unofficial mirror, please prove with hard evidence.

Whitelist

You can contact us on Discord.
[utopian-moderator]

Hey @roj, I just gave you a tip for your hard work on moderation. Upvote this comment to support the utopian moderators and increase your future rewards!

Hey @davidemi I am @utopian-io. I have just upvoted you!

Achievements

  • You have less than 500 followers. Just gave you a gift to help you succeed!
  • This is your first accepted contribution here in Utopian. Welcome!

Community-Driven Witness!

I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!

mooncryption-utopian-witness-gif

Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x

Congratulations @davidemi! You have completed some achievement on Steemit and have been rewarded with new badge(s) :

You made your First Vote
You got a First Reply

Click on any badge to view your own Board of Honor on SteemitBoard.
For more information about SteemitBoard, click here

If you no longer want to receive notifications, reply to this comment with the word STOP

By upvoting this notification, you can help all Steemit users. Learn how here!

Thank you for the contribution. It has been approved.

You can contact us on Discord.
[utopian-moderator]

Thank you very much

Coin Marketplace

STEEM 0.28
TRX 0.13
JST 0.032
BTC 61060.27
ETH 2927.58
USDT 1.00
SBD 3.55