Open top menu



What is an ANR?

When your app performs intensive work in response to user interaction, this single thread model can yield poor performance unless you implement your application properly. Specifically, if everything is happening in the UI Thread, perform long operation such as network access or database queries will block the whole UI.

When the thread is blocked, no event can be dispatched, including drawing events. From the user’s perspective, the application appears to hang. Even worse, if The UI thread is blocked for more than a few seconds (5 sec) the user OS presented with the infamous “Application not responding” (ANR) dialog.

How to Prevent ANR?

The Android UI toolkit is not thread safe. So you must not manipulate your UI from a worker thread – you must do all manipulation to your user interface from the UI thread,

Thus, there are simply two rule to Android single thread model.
1.       Do not block the UI Thread
2.       Do not access the Android UI toolkit from outside the UI thread?

Worker thread:

If you have operation perform that are not instantaneous, you should make sure to do them in separate thread (“Background” or “Worker” threads).
However, note that you cannot update the UI from any thread other than the UI Thread or the “main” thread.

To fix problem, Android offers several ways to access the UI thread from other thread.
1.       Activity. runOnUiThread(Runnable)
2.       View.post(Runnable)
3.       View.postDelayed(runnable,long)


Using AsyncTask:


AsyncTask allows you to perform asynchronous work on your user interface. It performs the blocking operations in worker tread and  publish the result on the UI Thread, without requiring you to handle thread and /or handlers yourself.

To use it, you must subclass AsyncTask and Implement callback methods
a.       doInBackground() :-  Which runs in pool of background thread.
b.      onPostExecute() :- Which delivers the result from doInBackground() and run in the UI thread.
So you can safety update you UI, You can then run the task by calling execute () from the UI thread.


Thread-Safe methods

In some situations, the method you implement might be called from more than one thread,
This is primarily true for methods that can be called remotely- such as methods in a bound service.

Bound Service:

A bound service is an implementation of the Service class that allows other applications to bind to it and interact with it. To provide bonding for a service, you must implement this OnBind() call-back method. This method return an IBinder object that defines the Programming interface that client can use to interact with the service.








Read more



Java is a widely used programing language and form the Basis of android development.
There are many reasons you have to switch Java to Kotlin, because Java cannot always be considered the best choice for android.


1.       Android only support a subset of java 8 feature. In a way , Android developer are not able to reap full benefits of Java.
2.       Java comes with some well-documents language issue like endless try-catch block, null-unsafety, NullPointerExceptions and lack of extendibility.
3.       Java is still a procedural language although it is starting to add lambda expression and functional interfaces recently.
4.       Java can create issues with Android API design.


Switch from Java to Kotlin be helpful ?

1.       There are some factors that make Kotlin stand out from the crowd, as there are many options available.
2.       Kotlin provide more documentation and real example.
3.       Kotlin is simultaneously operable with java. We can have both Java and kotlin code co-exist within a single project.
4.       Java and Kotlin both codes can compile perfectly and users are not even able to make out which part of the code is Kotlin.
5.       Kotlin and Java classes can be written simultaneously.
6.       Alternatively, Smal chunks of codes can be Written in kotlin and can be inserted as and when required, without affecting the entire code.
7.       Kotlin is a simple enhancement of java, so a Java Developer or an existing Java application user will be easily able to comprehend what kotlin code is doing. It looks familiar, the code is easy to read and understand.
8.       Kotlin aims to gel up with the best of both functional as well a procedural approaches, as there is no easy answer to which approach is best.
9.       Android Studio has an excellent support for kotlin.
10.   Once you all of this is set , Converting an entire Java code into Kotlin can be accomplished in single click.

Read more



 Purpose of Singleton:

The main purpose of the singleton class is to object creation, limiting the number of objects to only one. Since there is only one singleton instance fields of a singleton will occur only once per class, just like static.

Prons:

1. Singleton prevents other objects from instantiating their own copies of the singleton object, ensuring that all objects access the single instance.
2. Since the class controls the instantiation process, the class has the flexibility to change the instantiation process.
3. The advantage of singleton over global variable is that you are absolutely sure of the number of instances when you use Singleton.

Cons:

1. Their state is automatically shared across the entire app.
2. Bugs can often start occurring when that state changes unexpectedly.
3. The relationships between singleton and the code that depends on them is usually not very well     defined.
4. Managing their life-cycle can be tricky.



How to implement Singleton class.

Step 1. Create a class.

public class MyApplication  {

}

Step 2. Create an instance of the class which declare as a static.

public class MyApplication   {
    
    private static MyApplication appInstance;
}

 Step 3.  Make the initializer. final Singleton class

public class MyApplication   {
    
    private static MyApplication appInstance;
   
    public static synchronized MyApplication getAppInstance(){
        return appInstance;
    }
}

 


 Step 4.  final Singleton class in android.


public class MyApplication extends Application {
    
    private static MyApplication appInstance;
    

    @Override    public void onCreate() {
        super.onCreate();
        appInstance=this;

    }

    public static synchronized MyApplication getAppInstance(){
        return appInstance;
    }
 
}



How to used Singleton class in Activity in android.

 In this example we have save the login details in sharedpreferences  storage.

 

import android.app.Application;
import android.content.SharedPreferences;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;

public class MyApplication extends Application {
    private final static String PREFS_NAME = "SaveValue";
    private static MyApplication appInstance;
   

    @Override    public void onCreate() {
        super.onCreate();
        appInstance=this;

    }

    public static synchronized MyApplication getAppInstance(){
        return appInstance;
    }
    public void saveString(String key, String data) {
        SharedPreferences settings = MyApplication.appInstance.getSharedPreferences(PREFS_NAME, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString(key, data);
        editor.commit();
    }

    public String getString(String key) {
        SharedPreferences settings = MyApplication.appInstance.getSharedPreferences(PREFS_NAME, 0);
        return settings.getString(key,"");
    }

}

Activity

public class MainActivity extends AppCompatActivity {
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        MyApplication..getAppInstance()

        // Save login Details.
        MyApplication.getAppInstance().
                   saveString("Username", loginRequest.getUserName());
        MyApplication.getAppInstance().
                   saveString("Password", loginRequest.getPassword());


        // Get login Details
        MyApplication.getAppInstance().getString("Username");
        MyApplication..getAppInstance().getString("Password");
}
}


Read more



Basic Authorization :


You have to Add

{
@Overridepublic Map getHeaders() throws AuthFailureError {
    Map params = new HashMap();
    params.put("Content-Type", "application/json; charset=UTF-8");
    params.put("Authorization", basicAut);
    return params;
}



Please check how to call.

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.mespl.volleywebintegration.MyApplication;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class VolleyResponse {
    private static String BaseUrl = "http://" + "Your IP" + "/LoginApplication/";
    public VolleyInterface anInterface;
    private static  String basicAut="";

    public VolleyResponse(int methodType, String MethodName, JSONObject postParams) {

        JsonObjectRequest request = new JsonObjectRequest(methodType, 
                   BaseUrl + MethodName, postParams, new Response.Listener() {
                    @Override                   
                     public void onResponse(Object response) {
                        anInterface.onResponse(response);
                    }
                },

                new Response.ErrorListener() {
                    @Override                   
                 public void onErrorResponse(VolleyError error) {
                        anInterface.onResponse(error);
                    }
                }) {
@Overridepublic Map getHeaders() throws AuthFailureError {
    Map params = new HashMap();
    params.put("Content-Type", "application/json; charset=UTF-8");
    params.put("Authorization", basicAut);
    return params;
}
         
        };

public static void reStart(){
    String credentials = "Username" + ":" + "Password";
    basicAut="Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
}
}


Read more



Volley Overview


Volley is an HTTP library that makes networking for android apps and most Important.
You have to find multiple customise example on google. But I have explain keep and simple customise example, step by step.

Volley benefits

1.       Automatic scheduling of network request.
2.       Ease of customization for example.
3.       Support for request prioritization.
4.       Memory response caching with standard HTTP(cache coherence).
5.       Debugging and tracing tools.
Volley is not suitable for large download or streaming operation, since volley holds all response in memory during parsing. For large download operation used DownloadManager.

Dependency:

Example How to call Volley :

Step 1. Add Dependency.


dependencies {
    ....
    implementation 'com.android.volley:volley:1.1.1'   
}


Step 2. Add permissions.

xml version="1.0" encoding="utf-8"?><
manifest xmlns:android="http://schemas.android.com/apk/res/android">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application        ...
    </application>

</manifest>




 
Step 3. Make Custom interface.

import com.android.volley.VolleyError;

public interface VolleyInterface {
    
    public void onResponse(Object response);
    public void onErrorResponse(VolleyError error);
    
}



Step 4. Make Volley call back .


import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.mespl.volleywebintegration.MyApplication;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class VolleyResponse {
    private static String BaseUrl = "http://" + "Your IP" + "/LoginApplication/";
    public VolleyInterface anInterface;
    private static  String basicAut="";

    public VolleyResponse(int methodType, String MethodName, JSONObject postParams) {

        JsonObjectRequest request = new JsonObjectRequest(methodType, 
                   BaseUrl + MethodName, postParams, new Response.Listener() {
                    @Override                   
                     public void onResponse(Object response) {
                        anInterface.onResponse(response);
                    }
                },

                new Response.ErrorListener() {
                    @Override                   
                 public void onErrorResponse(VolleyError error) {
                        anInterface.onResponse(error);
                    }
                }) 
         
        };

        //This is for Headers If You Needed       
      MyApplication.getAppInstance().addRequestQueue(request, "Request");
    }


    public void setAnInterface(VolleyInterface anInterface) {
        this.anInterface = anInterface;
    }
}







Step 5. Call service REST API.
a.      You have add Dependency.
implementation 'com.google.code.gson:gson:2.3.1'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
b.   You have to create a Request and Response model class and implement Serializable  .
  
Request 
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

import java.io.Serializable;

public class LoginRequest implements Serializable {
    @SerializedName("UserName")
    @Expose    private String UserName;
    @SerializedName("Password")
    @Expose    private String Password;
    @SerializedName("DeviceId")
    @Expose    private String DeviceId;

    public String getUserName() {
        return UserName;
    }

    public void setUserName(String userName) {
        UserName = userName;
    }

    public String getPassword() {
        return Password;
    }

    public void setPassword(String password) {
        Password = password;
    }

    public String getDeviceId() {
        return DeviceId;
    }

    public void setDeviceId(String deviceId) {
        DeviceId = deviceId;
    }
}


First you have make request function, suppose you want make a login request. make a two override functions.
private void setLogin() {
    JSONObject obj = null;
    LoginRequest loginRequest = new LoginRequest();
    loginRequest.setDeviceId(Build.SERIAL);
    loginRequest.setUserName("max");
    loginRequest.setPassword("123");
 
     // convert Gson to String
    //String string = new Gson().toJson(loginRequest);    try {
        obj = new JSONObject(new Gson().toJson(loginRequest));
    } catch (JSONException e) {
        e.printStackTrace();
    }
    new VolleyResponse(Request.Method.POST, "GetLogin", obj).setAnInterface(this);
}

Implement

@Overridepublic void onResponse(Object response) {
    String string = response.toString();
}

@Overridepublic void onErrorResponse(VolleyError error) {

}

Step 5. Make Main Activity.


import com.android.volley.Request;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.mespl.volleywebintegration.pojo.LoginRequest;
import com.mespl.volleywebintegration.volley.VolleyInterface;
import com.mespl.volleywebintegration.volley.VolleyResponse;

import org.json.JSONException;
import org.json.JSONObject;

public class MainActivity extends AppCompatActivity implements VolleyInterface {

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

    private void setLogin() {
        JSONObject obj = null;
        LoginRequest loginRequest = new LoginRequest();
        loginRequest.setDeviceId(Build.SERIAL);
        loginRequest.setUserName("max");
        loginRequest.setPassword("123");
        MyApplication.saveString("Username", loginRequest.getUserName());
        MyApplication.saveString("Password", loginRequest.getPassword());
        VolleyResponse.reStart();
        //String string = new Gson().toJson(loginRequest);        try {
            obj = new JSONObject(new Gson().toJson(loginRequest));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        new VolleyResponse(Request.Method.POST, "GetLogin", obj).setAnInterface(this);
    }

    @Override    public void onResponse(Object response) {
        String string = response.toString();
    }

    @Override    public void onErrorResponse(VolleyError error) {

    }
}




you have to Used Basic Authorization.



Read more