Open top menu



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


Explain how to used Retrofit in android?

In this tutorial implement  custom classes for Retrofit API Call .

Add dependencies

implementation 'com.squareup.okhttp3:logging-interceptor:3.9.0'
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
implementation 'com.google.code.gson:gson:2.3.1'



create Class RestCallback.java

 
public abstract class RestCallback<T> implements Callback<T> {
    public static final String UN_SUCCESSFULL =  ContainMsg.UN_SUCCESSFULL;
    public static final String NO_CONNECTION = ContainMsg.Connectio_Error;

    public abstract void restResponse(boolean isSuccess, String message, Object response);

    @Override    public void onFailure(Call<T> call, Throwable t) {
        if (t instanceof SocketException || t instanceof SocketTimeoutException) {
            restResponse(false, UN_SUCCESSFULL, null);
            Log.e("RestCallback", t.getMessage());
        }else {
            restResponse(false, NO_CONNECTION, null);
            Log.e("RestCallback", t.getMessage());
        }
    }


    @Override    public void onResponse(Call<T> call, Response<T> response) {

        if (response.isSuccessful()) {
            try {
                Log.e("Response", new Gson().toJson(response.body()));
            } catch (Exception e) {
                e.printStackTrace();
            }
            restResponse(true, null, response.body());
        }else if (response.code()==401) {
            String str = ContainMsg.InvalidUser;
            restResponse(false, str, null);
        }else {
            restResponse(false,ContainMsg.connectioncoultnotbe, null);
        }
    }


}








 

Create RestClient.Java
public class RestClient { public static String BASE_URL; private static Retrofit retrofit = null; private static RestService apiService = null; public static RestService getClient() { String credentials = App.getString("Username") + ":" + App.getString("Password"); if (retrofit == null) { // create Base64 encodet string final String basic = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP); retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .client(UnsafeOkHttpClient.getUnsafeOkHttpClient(basic)) .build(); apiService = retrofit.create(RestService.class); } return apiService; } public static void restart() { retrofit = null; apiService = null; BASE_URL = GetUrl_whichMode(); } public static String GetUrl_whichMode() { return "http://" +"Your URL" + "/apis/";
    }

}




 

 
 Create Interface
public interface RestService {
    @POST("GetLogin")
    Call doLogin(@Body LoginRequest request);

}




 

 Create OkHttpClient Authencation Class.



public class UnsafeOkHttpClient {



    public static OkHttpClient getUnsafeOkHttpClient(final String basic) {
        try {
            // Create a trust manager that does not validate certificate chains            final TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        @Override                        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
                        }

                        @Override                        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {
                        }

                        @Override                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                            return new java.security.cert.X509Certificate[]{};
                        }
                    }
            };

            // Install the all-trusting trust manager            final SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

            // Create an ssl socket factory with our all-trusting manager            final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
            builder.hostnameVerifier(new HostnameVerifier() {
                @Override                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });


            builder.addInterceptor(new Interceptor() {
                @Override                public Response intercept(Chain chain) throws IOException {
                    return chain.proceed(chain.request().newBuilder()
                            .addHeader("Content-Type", "application/json")
                            //.addHeader("Content-Type", "application/json")                            .addHeader("Authorization", basic).build());
                }
            });
            OkHttpClient okHttpClient = builder
                    .readTimeout(120, TimeUnit.SECONDS)
                    .writeTimeout(120, TimeUnit.SECONDS)
                    .connectTimeout(120, TimeUnit.SECONDS)
                    .build();
            return okHttpClient;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}




Used in Main Activity...


 //Login request ...

public void setLogin(LoginRequest loginRequest) {
    if (isConnectingToInternet(this)) {
        ProgressDialogUtils.showLoader(this);
        App.saveString("Username", loginRequest.getUserName());
        App.saveString("Password", loginRequest.getPassword());
        RestClient.restart();
        RestClient.getClient().doLogin(loginRequest).enqueue(callback);
    }

}






RestCallback callback = new RestCallback() {
    @Override    public void restResponse(boolean isSuccess, String message, Object response) {
        try {
            if (isSuccess) {
                if (response instanceof LoginResponse) {
                  
                }  
            } 
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ProgressDialogUtils.hideLoader();
        }
    }
};


Read more

In this tutorial explain how to bind RecyclerView via kotlin.


RecyclerAdapter.kt


class RecyclerAdapter(val items: ArrayList, val context :Context,  val btnlistener: BtnClickListener) :RecyclerView.Adapter() {

    companion object {
        var mClickListener: BtnClickListener? = null    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {

        return ViewHolder(LayoutInflater.from(context).inflate(R.layout.animal_list_item, parent, false))
    }

    override fun getItemCount(): Int {

        return items.size    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        mClickListener = btnlistener        holder?.tvAnimalType.text = items.get(position)
        holder?.tvAnimalType.setOnClickListener(object : View.OnClickListener {
            override fun onClick(v: View?) {
                if (mClickListener != null)
                    mClickListener?.onBtnClick(position,holder?.tvAnimalType.text.toString())
            }
        })
    }


    class ViewHolder (view: View) : RecyclerView.ViewHolder(view) {
        val tvAnimalType = view.tv_animal_type
    }

    open interface BtnClickListener {
        fun onBtnClick(position: Int,string: String)
    }
}


layout_row.xml

xml version="1.0" encoding="utf-8";
xmlns:android="http://schemas.android.com/apk/res/android"              
android:layout_width="match_parent"              
android:layout_height="wrap_content">
    
TextView android:id="@+id/tv_animal_type"            
android:layout_width="match_parent"            
android:layout_height="wrap_content"            
android:textSize="20sp"            
android:padding="20dp" 
</LinearLayout >



 
MainActivity .kt

class MainActivity : AppCompatActivity(), RecyclerAdapter.BtnClickListener {

    override fun onBtnClick(position: Int, string: String) {
        Toast.makeText(this, "hello" + position + string, Toast.LENGTH_LONG).show()
    }

    val animals: ArrayList = ArrayList()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        setSupportActionBar(toolbar)
        addAnimal();
        rv_animal_list.layoutManager = LinearLayoutManager(this)
        rv_animal_list.adapter = RecyclerAdapter(animals, this, this)
    }

    fun addAnimal() {
        animals.add("dog")
        animals.add("cat")
        animals.add("owl")
        animals.add("cheetah")
        animals.add("raccoon")
        animals.add("bird")
        animals.add("snake")
        animals.add("lizard")
        animals.add("hamster")
        animals.add("bear")
        animals.add("lion")
        animals.add("tiger")
        animals.add("horse")
        animals.add("frog")
        animals.add("fish")
        animals.add("shark")

    }

}

activity_main.xml

xml version="1.0" encoding="utf-8"
?><android.support.design.widget.CoordinatorLayout        
xmlns:android="http://schemas.android.com/apk/res/android"        
xmlns:app="http://schemas.android.com/apk/res-auto"       
 xmlns:tools="http://schemas.android.com/tools"        
android:layout_width="match_parent"        
android:layout_height="match_parent"        t
ools:context=".activites.OneActivity">

   
 <android.support.design.widget.AppBarLayout            
android:layout_height="wrap_content"            
android:layout_width="match_parent"            
android:theme="@style/AppTheme.AppBarOverlay">

        
<android.support.v7.widget.Toolbar               
 android:id="@+id/toolbar"                
android:layout_width="match_parent"                
android:layout_height="?attr/actionBarSize"                
android:background="?attr/colorPrimary"                
app:popupTheme="@style/AppTheme.PopupOverlay"/>
 </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_one"/>

    <android.support.design.widget.FloatingActionButton            
android:id="@+id/fab"            
android:layout_width="wrap_content"            
android:layout_height="wrap_content"           
 android:layout_gravity="bottom|end"            
android:layout_margin="@dimen/fab_margin"            
app:srcCompat="@android:drawable/ic_dialog_email"/>

</android.support.design.widget.CoordinatorLayout>


Read more

In this tutorial explain how to convert  .png image to .bmp format.

Example:

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;

import android.graphics.Bitmap;

public class AndroidBmpUtil {
    private static  final int BMP_WIDTH_OF_TIMES = 4;
    private  static final int BYTE_PER_PIXEL = 3;

    public static boolean save(Bitmap orgBitmap, String filePath){

        if(orgBitmap == null){
            return false;
        }

        if(filePath == null){
            return false;
        }

        boolean isSaveSuccess = true;


        int width = orgBitmap.getWidth();
        int height = orgBitmap.getHeight();


        int dummySize = 0;
        byte[] dummyBytesPerRow = null;
        boolean hasDummy = false;
        if(isBmpWidth4Times(width)){
            hasDummy = true;
            dummySize = BMP_WIDTH_OF_TIMES - (width % BMP_WIDTH_OF_TIMES);
            dummyBytesPerRow = new byte[dummySize * BYTE_PER_PIXEL];
            for(int i = 0; i < dummyBytesPerRow.length; i++){
                dummyBytesPerRow[i] = (byte)0xFF;
            }
        }

        int[] pixels = new int[width * height];
        int imageSize = pixels.length * BYTE_PER_PIXEL + (height * dummySize * BYTE_PER_PIXEL);
        int imageDataOffset = 0x36;
        int fileSize = imageSize + imageDataOffset;


        orgBitmap.getPixels(pixels, 0, width, 0, 0, width, height);


        ByteBuffer buffer = ByteBuffer.allocate(fileSize);

        try {

            buffer.put((byte)0x42);
            buffer.put((byte)0x4D);

            //size            buffer.put(writeInt(fileSize));

            //reserved            buffer.put(writeShort((short)0));
            buffer.put(writeShort((short)0));

            //image data start offset            buffer.put(writeInt(imageDataOffset));

            //size            buffer.put(writeInt(0x28));

            //width, height            buffer.put(writeInt(width));
            buffer.put(writeInt(height));

            //planes            buffer.put(writeShort((short)1));

            //bit count            buffer.put(writeShort((short)24));

            //bit compression            buffer.put(writeInt(0));

            //image data size            buffer.put(writeInt(imageSize));

            //horizontal resolution in pixels per meter            buffer.put(writeInt(0));

            //vertical resolution in pixels per meter (unreliable)            buffer.put(writeInt(0));


            buffer.put(writeInt(0));


            buffer.put(writeInt(0));


            int row = height;
            int col = width;
            int startPosition = 0;
            int endPosition = 0;

            while( row > 0 ){

                startPosition = (row - 1) * col;
                endPosition = row * col;

                for(int i = startPosition; i < endPosition; i++ ){
                    buffer.put(write24BitForPixcel(pixels[i]));

                    if(hasDummy){
                        if(isBitmapWidthLastPixcel(width, i)){
                            buffer.put(dummyBytesPerRow);
                        }
                    }
                }
                row--;
            }

            FileOutputStream fos = new FileOutputStream(filePath);
            fos.write(buffer.array());
            fos.close();
        } catch (IOException e1) {
            e1.printStackTrace();
            isSaveSuccess = false;
        }
        finally{

        }

        return isSaveSuccess;
    }


    private static  boolean isBitmapWidthLastPixcel(int width, int i) {
        return i > 0 && (i % (width - 1)) == 0;
    }


    private static  boolean isBmpWidth4Times(int width) {
        return width % BMP_WIDTH_OF_TIMES > 0;
    }


    private static  byte[] writeInt(int value) throws IOException {
        byte[] b = new byte[4];

        b[0] = (byte)(value & 0x000000FF);
        b[1] = (byte)((value & 0x0000FF00) >> 8);
        b[2] = (byte)((value & 0x00FF0000) >> 16);
        b[3] = (byte)((value & 0xFF000000) >> 24);

        return b;
    }


    private static  byte[] write24BitForPixcel(int value) throws IOException {
        byte[] b = new byte[3];

        b[0] = (byte)(value & 0x000000FF);
        b[1] = (byte)((value & 0x0000FF00) >> 8);
        b[2] = (byte)((value & 0x00FF0000) >> 16);

        return b;
    }


    private static  byte[] writeShort(short value) throws IOException {
        byte[] b = new byte[2];

        b[0] = (byte)(value & 0x00FF);
        b[1] = (byte)((value & 0xFF00) >> 8);

        return b;
    }

}



Create Main Class


GestureOverlayView mSignature;
mSignature=  (GestureOverlayView) findViewById(R.id.shape_1_1);
WitnessSignature.setDrawingCacheEnabled(true);
Bitmap bitmap= Bitmap.createBitmap(mSignature.getDrawingCache());
AndroidBmpUtil.save(getResized(offenderBitmap, 384), 
Environment.getExternalStoragePublicDirectory(
        Environment.DIRECTORY_PICTURES).getAbsolutePath() + "/offender.bmp");

File fil = new File(Environment.getExternalStoragePublicDirectory(
        Environment.DIRECTORY_PICTURES).getAbsolutePath(), "offender.bmp");

 










Read more


Indicator for ExpandableListView ?


Explain how to used group indicator for custom ExpandableListView in android. you should be add line of code in group view in custom Adapter class.


int imageResourceId = isExpanded ? android.R.drawable.arrow_up_float : android.R.drawable.arrow_down_float;
image.setImageResource(imageResourceId);
image.setVisibility(View.VISIBLE);



ExpandableListView Example

Read more