Open top menu






private void getDeviceId(){
try {
String deviceId = "";
if (android.os.Build.VERSION.SDK_INT > Build.VERSION_CODES.O_MR1) {
deviceId = Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);
} else {
deviceId = Build.SERIAL;
}
if (deviceId.equals("")) {
deviceId = UUID.randomUUID().toString();
}
ApplicationSetting.saveString("DeviceId", deviceId);
} catch (
Exception e) {
e.printStackTrace();
}
}
Read more



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