Open top menu


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


Print HTML document and webpage in android application.
Printing an html doc with webview involves loading an html res or building an html doc as a string.

Creating custom print view step by step

1.       Creat a webviewclient that starts a print job after the html res is loaded.
2.       Load the html res into the webview object.

private WebView testWebView;

private void TestWebViewPrint() {
   
// Create a WebView object specifically for printing
   
WebView webView = new WebView(this);
    webView.setWebViewClient(
new WebViewClient() {

       
public boolean shouldOverrideUrlLoading(WebView view, String url) {
           
return false;
        }

       
@Override
        
public void onPageFinished(WebView view, String url) {
            Log.i(
"TAG", "page finished loading " + url);
            createTestWebPrintJob(view);
           
testWebView = null;
        }
    });

   
// Generate an HTML document on the fly:
   
String htmlDocument = "

Test Content

Androidbeginner tutorial point, "
+
           
"Hello, Hello...
";
    webView.loadDataWithBaseURL(
null, htmlDocument, "text/HTML", "UTF-8", null);

   
// Keep a reference to WebView object until you pass the PrintDocumentAdapter
    // to the PrintManager
   
testWebView = webView;
}


private void createTestWebPrintJob(WebView webView) {
   
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
    {

        PrintManager printManager = (PrintManager)
this.getSystemService(Context.PRINT_SERVICE);

        PrintDocumentAdapter printAdapter = webView.createPrintDocumentAdapter();

        String jobName = getString(R.string.
app_name) + " Print Test";

        printManager.print(jobName, printAdapter,
new PrintAttributes.Builder().build());
    }
}

you can load a webpage for printing by replacing the method loadUrl().
 webView.loadUrl("https://developer.android.com/distribute/index.html");



Read more