Android Workshop Day 3 Slides

On the 3rd day of the workshop, we have covered Google-Firebase overall. We have seen that

  • Problems with developing server side for the apps.
  • What is Firebase & Why it exists
  • Firebase Push Notifications
  • Firebase Analytics
  • Real-time Database
  • Remote Config
  • App Indexing

Following are the slides for Day 3:

Android Apps Development workshop at TechHubConnect Day 2 Slides

TechHubConnect is a free co-working space by the Punjab, Pakistan Government who invited me to conduct Android Apps Development one week long workshop as the co-working space member along with another company.

In this workshop, I will be covering topics related to

  • Facebook-Android-SDK
  • Login with Facebook
  • Introduction to Firebase
  • Firebase-Android-SDK
  • Firebase Authentication
  • Saving and retrieving data from Facebook
  • Firebase offline capabilities
  • Google In-App Purchase SDK

on Day 2, and Day 4 and first or second half of the Day 5.

The Day 2 slides are uploaded on SlideShare and rest of the slides will also be shared. So make sure that you subscribe to us via SlideShare and our Email Newsletter to know about all the upcoming events we will be participating.

The example app on which I referenced in the slides can be checked here


How-to-implement-offline-support-for-Android-using-Firebase

How to implement offline support for Android using Firebase

While building the Task management app Hash-Todo using Firebase and adding offline support for it, I am sharing what i learned to impliment it perfectly. I assume that you have already configured Firebase in your project and know the basics of it. If you don’t then you can go ahead and follow the firebase essentials for android course on Udacity. 

To enable offline support in Android, you just need to add the following line after you initialise the Firebase-Android SDK.

Firebase.getDefaultConfig().setPersistenceEnabled(true);

Now all the data changes will be saved locally in the phone when the user is in offline mode and all will be synced automatically when user will be connected to the internet and even if the app will be in the background.

However when calling setValue(),removeValue() or updateChildren(), methods of Firebase-Android SDK, we can set completion listener (Firebase.CompletionListener) which overrides the onComplete(FirebaseError firebaseError, Firebase firebase)  method. Here the first parameter indicates any error that might occur during the operation otherwise it is null.

My suggestion here is to not wait for the onComplete callback, especially when the app is supposed to work in offline mode. 

The complete method is called when the app communicates with Firebase successfully. If the user is not connected to the internet then the Firebase SDK does all the hard-work to store it locally and waits for the phone to be connected to the internet. So the app itself should not wait for the onComplete callback. In Hash-Todo app when the user adds a task, I do not show the ProgressDialog indicating task is being added, instead, I finish the Add Task Activity. 

The FirebaseError parameter helps to find potential problems in the app, so inside this method FirebaseError should be checked, if it is not null then it should be reported somewhere (I use Fabric’s Crashlytics for this). The code is simple but will look like this:

Firebase firebaseRef = new Firebase(Constants.FIREBASE_URL);
firebaseRef.updateChildren(updateUserTaskData, new Firebase.CompletionListener() {
    @Override
    public void onComplete(FirebaseError firebaseError, Firebase firebase) {
        if (firebaseError != null) {
            Crashlytics.logException(
                new RuntimeException("Error while adding task in AddEditTaskFragment: " +
                    firebaseError.getMessage()));
        }
    }
});

Now the app will work fine without the internet connection and all the data will be synced automatically when connected to the internet.

Found it useful and want to learn more? Make sure you try Hash-Todo app, share this article with your community and feel free to discuss it further in the comments below 🙂

Protected: Simple tips for building better Android Apps

This content is password protected. To view it please enter your password below:

Android: Best way to pass data between activities

In Android often we need to pass data from one activity or fragment to another activity or fragment (master-detail view). In this article, I am going to talk about best way and practices to do that.

Organize the Keys

While passing the data with Bundle we need to specify the key for the value that we use in the second activity to retrieve. Usually, beginners hard code that key in the as the first parameter of the setData method which can lead to many problems later in the code. What if you do not correctly type the same key name in second activity or fragment? Recommended way for this is to use a final static variable and use the same in both activities. This will ensure that same key is used. Also, it is handy to create a dedicated class that will just contain the information related keys only that will be used to pass data. See the following

    public class ActivityHelper {
        public static final String KEY_USER_NAME = "key_user_name";
        public static final String KEY_USER_EMAIL = "key_user_email";
        public static final String KEY_USER = "key_user";
    }

Use Parcelable provided by Android to pass custom Object

If you want to pass Custom Objects between activities then your object should implement Parcelable (android.os.Parcelable) interface and should override its methods “correctly” which makes it possible to use intent.putParcelable(Key, Object) the method.

I will use the following simple model for this example:

public class UserModel {
        private String name;
        private String email;
        private String age;
    }

After you will implement the Parcelable  interface, the Android Studio will give you the error to override the required methods of the interface. Right clicking on the error or pressing Command + 1 from the keyboard after placing the cursor on the error will give you an option to “Implement methods” (See below image) that will automatically add required methods.

Android Studio Implement interface methods error

Android Studio Implement interface methods error

After implementing the methods UserModel will look like below and it will still give an error: “This class implements Parcelable but does not provide Creator”.

    public class UserModel implements Parcelable {
        private String name;
        private String email;
        private String age;

        @Override
        public int describeContents() {
            return 0;
        }

        @Override
        public void writeToParcel(Parcel dest, int flags) {
        }
    }

Again place the cursor in the class name and press Command + 1 from the keyboard to automatically generate the code. So now the class will look like this:

public class UserModel implements Parcelable {
        private String name;
        private String email;
        private String age;

        protected UserModel(Parcel in) {
            name = in.readString();
            email = in.readString();
            age = in.readString();
        }

        public static final Creator<UserModel> CREATOR = new Creator<UserModel>() {
            @Override
            public UserModel createFromParcel(Parcel in) {
                return new UserModel(in);
            }

            @Override
            public UserModel[] newArray(int size) {
                return new UserModel[size];
            }
        };

        @Override
        public int describeContents() {
            return 0;
        }

        @Override
        public void writeToParcel(Parcel dest, int flags) {
            dest.writeString(name);
            dest.writeString(email);
            dest.writeString(age);
        }
    }

Now we can pass the object as:

Intent i = new Intent(CONTEXT, CLASS_NAME.class);
        i.putExtra(ActivityHelper.KEY_USER, userObject);

And in the second activity, we can retrieve the passed object as:

UserModel user = (UserModel) getIntent().getParcelableExtra(ActivityHelper.KEY_USER);

Cool? I don’t think so.

Big Problem and its Solution

You might be thinking that everything is great, but actually, it is not. First the code does not look good now, in UserModel we only want to see code that is related to our fields. Also, let’s say if we decide to add more fields in ours UserModel ? for example,firstName lastName , location , etc. Now we will have to regenerate all the code again so that the newly added fields can also be passed between activities. This is not good because we can forget to regenerate all the code again which will cause problems that will be hard to fix. So there must be some nice way to solve this problem.

The solution is to use Parceler @Parcel and everything is handled automatically. However, it is recommended not to use private fields when using the default field serialization strategy as it will incur a performance penalty due to reflection. So to use this library we need to add the following dependency in the app level build.gradle file

compile 'org.parceler:parceler-api:1.0.4'
apt "org.parceler:parceler:1.0.4"

And add the following as dependency in the project level build.gradle and apply plugin: apply plugin: 'com.neenbedankt.android-apt'

classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'

So now our model looks like this:

    @Parcel
    public class UserModel {
        String name;
        String email;
        String age;
    }

Isn’t it is Cool now? We don’t have to think about the code generation now, also, the Model looks very clean now.

However you will need to use Parcels.wrap(userObject) and Parcels.unWrap() methods provided by the library as follows.

Bundle bundle = new Bundle();<br>bundle.putParcelable(ActivityHelper.KEY_USER, Parcels.wrap(userObject));

and in the second activity, you will need to call

UserModel userModel = Parcels.unwrap(getIntent().getParcelableExtra(ActivityHelper.KEY_USER));

You can learn more at about the library at Parceler.org

Ending note

This is my first ever blog post on the internet and I want your feedback about this. If you want me to write then let me know via Comments and by sharing the article with others. I can write about Android, GoogleAppEngine, Firebase, Best practices for apps development, management and App marketing etc.

Happy Coding.