18 Aug 2021

Read large file from the external storage in Android

 Hi All,


There are many features or snippet of code, which we are using in our daily development.
Here I am sharing some common basic function for make our life easy and fast in the development. Below is the code written in the Kotlin.

File path can be : 
val file = File(context.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS), "test.txt")

  •  Read file from external storage:

fun readFileData(file: File): String
    {
        val sb = StringBuilder()

        if (file.exists()) {
            try {
                val bufferedReader = file.bufferedReader();
                bufferedReader.useLines { lines ->
                    lines.forEach {
                        sb.append(it)
                    }
                }
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
        return sb.toString()
    }

  • Read file from assets:

fun loadJSONFromAsset(mContext: Context, fileName: String): String {
        val inputStream = mContext.assets.open(fileName)
        val size = inputStream.available()
        val buffer = ByteArray(size)
        inputStream.read(buffer)
        inputStream.close()
        return String(buffer, Charsets.UTF_8)
    }

I will be happy if you will provide your feedback or follow this blog. Any suggestion and help will be appreciated.
Thank you :)

22 May 2017

Runtime Permissions in Android Marshmallow

Today I will show you Android Marshmallow Permissions Example. One of the major changes in Android Marshmallow is the new permission system. In earlier versions we were declaring the permission in the AndroidManifest.xml file. But with Android Marshmallow we need to ask the permission at run time.  In this post I will show you a simple Android Marshmallow Permissions Example. So lets begin.

Permission Groups

Different types of permissions are separated into groups based on which data or resource it requests access for. Once permission from a group has been granted, then other permissions within that group do not need to be granted again.

For example, a permission group for SMS can send or receive the SMS. Those are two different permissions but the user only needs to allow one.

Android 6.0 Marshmallow has nine main groups of permissions:

Calendar: Read and/or write to the calendar.

Camera: Give the application the ability to access the camera.

Location: Access fine or coarse location.

Microphone: The ability to record audio.

Phone: Includes phone state; the ability to make calls, read, and write to the call log; and voicemail.

Sensor: The ability to use various sensors in the device, like a gyroscope.

SMS: Similar to how the phone is handled including sending and receiving texts. MMS and cell broadcasts.

Storage: Read and write to device’s external storage.

Here, i have added relation Permissions to provide multiple permission at once in the app.

Main Activity :

In this example, its acquiring permission for Location and Camera. Below is the code snippet check whether permission is allow or not by user. if it's not then its requesting for permission.

if ( !checkPermission() )
                {

                    requestPermission();

                }
                else
                {

                    Snackbar.make(view, "Permission already granted.", Snackbar.LENGTH_LONG).show();

                }
Below are the full code snippet :

static int PERMISSION_REQUEST_CODE=100;
private boolean checkPermission()
    {
        if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.M )
        {
            int result = ContextCompat.checkSelfPermission(getApplicationContext(), ACCESS_FINE_LOCATION);
            int result1 = ContextCompat.checkSelfPermission(getApplicationContext(), CAMERA);

            return result == PackageManager.PERMISSION_GRANTED && result1 == PackageManager.PERMISSION_GRANTED;
        }
        else
        {
            return  true;
        }
    }

    private void requestPermission()
    {

        ActivityCompat.requestPermissions(this, new String[]{ACCESS_FINE_LOCATION, CAMERA}, PERMISSION_REQUEST_CODE);

    }

    @Override
    public void onRequestPermissionsResult( int requestCode, String permissions[], int[] grantResults )
    {
        switch ( requestCode )
        {
            case PERMISSION_REQUEST_CODE:
                if ( grantResults.length > 0 )
                {

                    boolean locationAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                    boolean cameraAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;

                    if ( locationAccepted && cameraAccepted )
                    {
                        Snackbar.make(view, "Permission Granted, Now you can access location data and camera.", Snackbar.LENGTH_LONG).show();
                        Log.v("Main Activity ==>", "All permission Granted");
                    }
                    else
                    {

                        Snackbar.make(view, "Permission Denied, You cannot access location data and camera.", Snackbar.LENGTH_LONG).show();

                        if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.M )
                        {
                            if ( shouldShowRequestPermissionRationale(ACCESS_FINE_LOCATION) )
                            {
                                showMessageOKCancel("You need to allow access to both the permissions",
                                                    new DialogInterface.OnClickListener()
                                                    {
                                                        @Override
                                                        public void onClick( DialogInterface dialog, int which )
                                                        {
                                                            if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.M )
                                                            {
                                                                requestPermissions(new String[]{ACCESS_FINE_LOCATION, CAMERA},
                                                                                   PERMISSION_REQUEST_CODE);
                                                            }
                                                        }
                                                    });
                                return;
                            }
                        }

                    }
                }


                break;
        }
    }


    private void showMessageOKCancel( String message, DialogInterface.OnClickListener okListener )
    {
        new AlertDialog.Builder(MainActivity.this)
                .setMessage(message)
                .setPositiveButton("OK", okListener)
                .setNegativeButton("Cancel", null)
                .create()
                .show();
    }
I will be happy if you will provide your feedback or follow this blog. Any suggestion and help will be appreciated.
Thank you :)

7 Apr 2016

Retrofit 2.0 Android | Web service using Retrofit.

Retrofit is developed by Square, Inc. It is one of the most popular HTTP Client Library for Android as a result of its simplicity and its great performance compare to the others.

A part from development,Old method to using web service which is quite lengthy and time consuming.

Here retrofit set everything for you automatically. Now Lets implement Retrofit in our code.

Step 1 : Create studio project.
Now we will Add Retrofit library to our project : Visit Retrofit Official Site
For Android Studio you just need to paste below line of code under dependency of  build.gradle file.

compile 'com.squareup.retrofit2:retrofit:2.0.1'

Now, Add Another library called Okhttp to our project
compile 'com.squareup.okhttp:okhttp:2.4.0' 

Now, Add two more Library Gson and GsonConverter to build.gradle
compile 'com.google.code.gson:gson:1.7.2' 
compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'

Now, Add one more lib to display log of request and response from retrofit.
compile 'com.squareup.okhttp:logging-interceptor:2.6.0'

SERVICE : 
Let's take Login service to implement using retrofit. below is the service for user login which have two parameter Username and password.
http://xyz/service/userlogin?Username=xyz&password=abc

Step 2: Create POJO/Class
Now we will make all POJO of JSON data coming from server. in my case here is the JSON response of the server.
{"status":"true","message":"Login successfully","data":{"id":1,"first_name":"Hasmukh","last_name":"Bhadani"}}

POJO class in Retrofit by Most Easiest Way :

  • Visit pojo.sodhanalibrary - This is Official website to Convert JSON Data into POJO class. Just You have to Copy Paste all the Codes. Rename pojo as per your requirement.


Here I am creating Three POJO : (1)BaseResponse (2)LoginResponse. (3)UserInfo

BaseResponse :
It contain common filed which is used for whole server in the project.

  public class BaseResponse {

    private String message;

    private String status;

    public String getMessage ()
    {
        return message;
    }

    public void setMessage (String message)
    {
        this.message = message;
    }

    public boolean getStatus ()
    {
        return status.equalsIgnoreCase("true");
    }

    public void setStatus (boolean status)
    {
        this.status = String.valueOf(status);
    }
}
LoginResponse :
   public class LoginResponse extends BaseResponse
{
    private Data data;
    public Data getData ()
    {
        return data;
    }
    public void setData (Data data)
    {
        this.data = data;
    }
   
}
UserInfo: 
   public class UserInfo
{
     private String id;

    private String first_name;

    private String last_name;

    public String getId ()
    {
        return id;
    }

    public void setId (String id)
    {
        this.id = id;
    }

    public String getFirst_name ()
    {
        return first_name;
    }

    public void setFirst_name (String first_name)
    {
        this.first_name = first_name;
    }

    public String getLast_name ()
    {
        return last_name;
    }

    public void setLast_name (String last_name)
    {
        this.last_name = last_name;
    }
   
}
Step 3: Create RestClient.java
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.logging.HttpLoggingInterceptor;
import com.truckforload.app.AppUrls;
import java.util.concurrent.TimeUnit;
import retrofit.GsonConverterFactory;
import retrofit.Retrofit;

public class RestClient
{
    private static ApiInterface restClient;
    static
    {
        setupRestClient();
    }
    private RestClient() {}

    public static ApiInterface get()
    {
        return restClient;
    }
    private static void setupRestClient()
    {
        OkHttpClient client = new OkHttpClient();
        client.setConnectTimeout(10, TimeUnit.SECONDS);

        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);

        HttpLoggingInterceptor interceptorBody = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        client.interceptors().add(interceptor);
        client.interceptors().add(interceptorBody);

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(AppUrls.BASE_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        restClient = retrofit.create(ApiInterface.class);
    }
}
Step 4: Create ApiInterface.java
Now create an Interface for all http methods and parameter.

import retrofit.Call;
import retrofit.http.Body;
import retrofit.http.GET;
import retrofit.http.POST;
import retrofit.http.Query;

public interface ApiInterface
{
    // Login
    @GET("service/userlogin")
    Call<LoginResponse> login( @Query("Username") String strUsername, @Query("password") String strpassword);

}
Step 5: Create AppWs.java
It contain all method of project which are used for service.And it will provide response using call back listener.

import retrofit.Call;
import retrofit.Callback;
import retrofit.Response;
import retrofit.Retrofit;

public class AppWs
{
    private static final String TAG = "AppWs";

    public static String login( final LoginRequest request, final Context context, final WsListener listener )
    {
        String unm= request.getUsername();
        String password = request.getPassword();

        Call<LoginResponse> call = RestClient.get().login(unm, password);
        try
        {
            call.enqueue(new Callback<LoginResponse>()
            {
                @Override
                public void onResponse( Response<LoginResponse> response, Retrofit retrofit )
                {
                    LoginResponse baseResponse = response.body();
                    if ( baseResponse != null && response.isSuccess() )
                    {
                        if ( listener != null )
                        {
                            listener.onResponseSuccess(baseResponse);
                        }
                    }
                    else
                    {
                        if ( listener != null )
                        {
                            ResponseBody errorBody = response.errorBody();

                            if ( errorBody != null )
                            {
                                listener.notifyResponseFailed(errorBody.toString(), null);
                            }
                        }

                    }
                }

                @Override
                public void onFailure( Throwable t )
                {
                    retrofitError(t, listener, context);
                }

            });

        }
        catch ( Exception e )
        {
            e.printStackTrace();
        }
        return "";
    }


    public static void retrofitError( Throwable t, WsListener listener, Context context )
    {
        if ( listener != null )
        {
            t.printStackTrace();
            listener.notifyResponseFailed(null, null);
        }
    }

    public interface WsListener
    {
        void onResponseSuccess( BaseResponse baseResponse );

        void notifyResponseFailed( String message, BaseRequest request );
    }
}
Step 6: Create MainActivity.java
Below is the Method which is call on SignIn Button in the activity

private void callServiceLogin()
    {
  ProgressDialog progressDialog = new ProgressDialog(this);
  progressDialog.setMessage("Loading...");
  progressDialog.setCancelable(false);

        LoginRequest loginRequest = new LoginRequest();

        String phone = etUserName.getText().toString();
        loginRequest.setUsername(phone);

        String password = etPassword.getText().toString();
        loginRequest.setPassword(password);

        AppWs.login(loginRequest, this, new AppWs.WsListener()
        {
            @Override
            public void onResponseSuccess( BaseResponse baseResponse )
            {
  if (progressDialog != null && progressDialog.isShowing())
             {
                 progressDialog.dismiss();
             }

                if ( baseResponse instanceof LoginResponse )
                {
                    LoginResponse loginResponse = (LoginResponse) baseResponse;

                    boolean status = loginResponse.getStatus();
                    UserInfo userInfo = loginResponse.getData();
                }
            }

            @Override
            public void notifyResponseFailed( String message, BaseRequest request )
            {
                dismissProgressDialog();                
            }
        });

    }
Here is the official site to get more API interface declaration for service. Visit here.

Find following are the reference links to go in deep for retrofi 2.0 :
https://guides.codepath.com/android/Consuming-APIs-with-Retrofit
http://www.iayon.com/consuming-rest-api-with-retrofit-2-0-in-android/

I will be happy if you will provide your feedback or follow this blog. Any suggestion and help will be appreciated.
Thank you :)

5 Apr 2016

GET/POST request Using HttpURLConnection.

Hi All,

Today I am sharing one of the important code snippet. As we all know  org.apache.http.client.HttpClient,

This interface was deprecated in API level 22. So now onward need to use URLConnection instead.
Means that you should switch to java.net.URL.openConnection().

Here is the http utility class to send GET/POST request to the server.

RestClient :
package com.httpurlconnection;

import android.util.Log;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

public class RestClient
{
    public enum RequestMethod
    {
        GET,
        POST
    }

    private HashMap<String, String> params;

    private HashMap<String, String> headers;

    private String serviceUrl;

    private int responseCode;

    private String message;

    private String response;

    private InputStream inputStream = null;

    private HttpURLConnection urlConnection = null;

    private String strJson=null;

    public RestClient( String url )
    {
        this.serviceUrl = url;
        params = new HashMap<String, String>();
        headers = new HashMap<String, String>();
    }

    public String getResponse()
    {
        return response;
    }

    public String getErrorMessage()
    {
        return message;
    }

    public int getResponseCode()
    {
        return responseCode;
    }


    public void AddParam( String name, String value )
    {
        params.put(name, value);
    }

    public void AddHeader( String name, String value )
    {
        headers.put(name, value);
    }

    public void AddData( String strJson )
    {
        this.strJson=strJson;
    }

    public void Execute( RequestMethod method ) throws Exception
    {
        switch ( method )
        {
            case GET:
            {
                //add parameters
                String combinedParams = "";
                if ( !params.isEmpty() )
                {
                    combinedParams += "?";
                    for ( Map.Entry<String, String> p : params.entrySet() )
                    {
                        String paramString = URLEncoder.encode(p.getKey(), "UTF-8") + "=" + URLEncoder.encode(p.getValue(), "UTF-8");
                        if ( combinedParams.length() > 1 )
                        {
                            combinedParams += "&" + paramString;
                        }
                        else
                        {
                            combinedParams += paramString;
                        }
                    }
                }
                try
                {
                    URL url = new URL(serviceUrl + combinedParams);

                    urlConnection = (HttpURLConnection) url.openConnection();
                    urlConnection.setRequestMethod("GET");
                    urlConnection.setReadTimeout(15000);
                    urlConnection.setConnectTimeout(15000);

                    /* Add header */
                    if ( !headers.isEmpty() )
                    {
                        for ( Map.Entry<String, String> header : headers.entrySet() )
                        {
                            urlConnection.setRequestProperty(header.getKey(), header.getValue());
                        }
                    }

                    int statusCode = urlConnection.getResponseCode();

                /* 200 represents HTTP OK */
                    if ( statusCode == HttpURLConnection.HTTP_OK )
                    {
                        inputStream = new BufferedInputStream(urlConnection.getInputStream());
                        response = convertStreamToString(inputStream);
                        Log.e("Response ::", response);
                    }
                }
                catch ( Exception e )
                {
                    Log.d("Exception::", e.getLocalizedMessage());
                }
                finally
                {
                    urlConnection.disconnect();
                }
                break;
            }
            case POST:
            {
                try
                {
                    URL url = new URL(serviceUrl);

                    urlConnection = (HttpURLConnection) url.openConnection();
                    urlConnection.setRequestMethod("POST");
                    urlConnection.setReadTimeout(15000);
                    urlConnection.setConnectTimeout(15000);
                    urlConnection.setDoInput(true);// true indicates the server returns response
                    urlConnection.setDoOutput(true);// true indicates POST request

                 /* Add header */
                    if ( !headers.isEmpty())
                    {
                        for ( Map.Entry<String, String> header : headers.entrySet() )
                        {
                            urlConnection.setRequestProperty(header.getKey(), header.getValue());
                        }
                    }
                    /* Parameter */
                    if(!params.isEmpty())
                    {
                        OutputStream os = urlConnection.getOutputStream();
                        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
                        writer.write(getPostDataString(params));

                        writer.flush();
                        writer.close();
                        os.close();
                    }
                    /* Request with JSON string */
                    if(strJson!=null)
                    {
                        OutputStreamWriter wr= new OutputStreamWriter(urlConnection.getOutputStream());
                        wr.write(strJson);

                    }
                    int statusCode = urlConnection.getResponseCode();

                /* 200 represents HTTP OK */
                    if ( statusCode == HttpURLConnection.HTTP_OK )
                    {
                        inputStream = new BufferedInputStream(urlConnection.getInputStream());
                        response = convertStreamToString(inputStream);
                        Log.e("Response ::", response);
                    }

                }
                catch ( Exception e )
                {
                    Log.d("Exception::", e.getLocalizedMessage());
                }

                finally
                {
                    urlConnection.disconnect();
                }
                break;
            }
        }
    }

    private static String convertStreamToString( InputStream is )
    {

        BufferedReader br = null;
        StringBuilder sb = new StringBuilder();

        String line;
        try {

            br = new BufferedReader(new InputStreamReader(is));
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return sb.toString();
    }

    private String getPostDataString( HashMap<String, String> params ) throws UnsupportedEncodingException
    {
        StringBuilder result = new StringBuilder();
        boolean first = true;
        for ( Map.Entry<String, String> entry : params.entrySet() )
        {
            if ( first )
            {
                first = false;
            }
            else
            {
                result.append("&");
            }

            result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
        }

        return result.toString();
    }
}
How to Use:
 package com.httpurlconnection;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

public class MainActivity extends AppCompatActivity
{
    private static final String TAG = "Http Connection";

    private String url = "Service Url";

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

        new AsyncHttpTask().execute(url);
    }

    public class AsyncHttpTask extends AsyncTask<String, Void, String>
    {
        String response=null;
        @Override
        protected String doInBackground( String... params )
        {
            try
            {
                RestClient client = new RestClient(url);
//                client.AddParam("service", "analytics");
                client.AddHeader("Content-Type", "application/json");
                try
                {
                    client.Execute(RestClient.RequestMethod.GET);
                    response = client.getResponse();
                }
                catch ( Exception e )
                {
                    e.printStackTrace();
                }
            }
            catch ( Exception e )
            {
                Log.d(TAG, e.getLocalizedMessage());
            }
            return response;
        }


        @Override
        protected void onPostExecute( String result )
        {
            /* Download complete. Lets update UI */
            if ( result!=null && result.length()>0)
            {
                Log.e("Response ====",result);
            }
            else
            {
                Log.e(TAG, "Failed to fetch data!");
            }
        }
    }

}
 
I will be happy if you will provide your feedback or follow this blog. Any suggestion and help will be appreciated.
Thank you :)

11 Feb 2016

AsteriskPassword in EditText for Android

Hi All,

There are many features or snippet of code, which we are using in our daily development.
Here I am sharing some common basic function for make our life easy and fast in the development.

AsteriskPassword:

In android, By default provide property android:inputType = "textPassword" for Password edit text. But It has minor issue like password character visible while we are typing.
To Restrict this, I have created class AsteriskPasswordUtils. here you can give any password patterns.

AsteriskPasswordUtils.java

import android.text.method.PasswordTransformationMethod;
 import android.view.View;

 public class AsteriskPasswordUtils extends PasswordTransformationMethod
 {
  @Override    
  public CharSequence getTransformation( CharSequence source, View view )
  {
   return new PasswordCharSequence(source);
  }

  private class PasswordCharSequence implements CharSequence
  {
   private CharSequence mSource;

   public PasswordCharSequence( CharSequence source )
   {
    mSource = source; // Store char sequence       
   }

   public char charAt( int index )
   {
    return '*'; // This is the important part        
   }

   public int length()
   {
    return mSource.length(); // Return default        
   }

   public CharSequence subSequence( int start, int end )
   {
    return mSource.subSequence(start, end); // Return default        
   }
  }
 };
MainActivity 
 EditText etPassword = (EditText) findViewById(R.id.etPassword);
 etPassword.setTransformationMethod(new AsteriskPasswordUtils());
Note : Don't forget to add android:inputType = "textPassword" in the edit text on xml.

I will be happy if you will provide your feedback or follow this blog. Any suggestion and help will be appreciated.
Thank you :)

20 Oct 2015

Data Binding in Android Marshmallow 6.0

Hello Friends,

There are lots of exiting library come up with new android feature.
One of the new API that caught my eye is the Data Binding Library. In short, it lets you bind data directly into your layouts by having a POJO - variable declaration pair.

Key features:

  • The Data Binding Library offers both flexibility and broad compatibility — it's a support library, so you can use it with all Android platform versions back to Android 2.1 (API level 7+).
  • So far so good, nothing really complicated or hard to comprehend. In a way, this removes a bit of boilerplate code (not having to findViewById() or setText()). My first impression was that this is the aim of this API.

Build Environment :


1) The Data Binding plugin requires Android Plugin for Gradle 1.3.0-beta4 or higher, so update your build dependencies (in the top-level build.gradle file) as needed.

2) Make sure you are using a compatible version of Android Studio. Android Studio 1.3 adds the code-completion and layout-preview support for data binding.

Setting Up Work Environment:

Step 1 :
To set up your application to use data binding, add data binding to the class path of your top-level       build.gradle file, right below "android".

dependencies {
    classpath 'com.android.tools.build:gradle:1.3.0'
    classpath "com.android.databinding:dataBinder:1.0-rc1"
}
Then make sure jcenter is in the repositories list for your projects in the top-level build.gradle file.

Step 2 :
In each module you want to use data binding, apply the plugin right after android plugin

apply plugin: 'com.android.application'
apply plugin: 'com.android.databinding'


Let's take the example  to understand better :


User.java :

public class User {
    public final String firstName;
    public final String lastName;
    public User(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }
}

In the layout in which we want to display the user's first and last name. With Data Binding we can directly reference the user's fields in the layout

activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android = "http://schemas.android.com/apk/res/android">
    <data>
        <variable name = "user" type = "com.testapp.User"/>        
    </data>

    <LinearLayout
        android:layout_width = "match_parent"
        android:layout_height = "match_parent"
        android:orientation = "vertical" >

        <TextView android:textColor="@android:color/black"
            android:layout_width = "wrap_content"
            android:layout_height = "wrap_content"
            android:text = "@{user.firstName}"/>

        <TextView
            android:textColor="@android:color/black"
            android:layout_width = "wrap_content"
            android:layout_height = "wrap_content"
            android:text = "@{user.lastName}"/>   
    </LinearLayout>
</layout>

MainActivity.java :

A binding class will be generated based on the name of the layout file (in this case ActivityMainBinding) which you can use in your activity to actually tell the layout which user object to use

 ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);

 user user=new user("Hello"," World !!!");
 binding.setUser(user);

*****Binding Events*****

Events may be bound to handler methods directly, similar to the way android:onClick can be assigned to a method in the Activity.

Step 1: Create MyHandlers.java class 
You can add method to perform action on button click same what we did before like onClickListner

public class MyHandlers
{
    public void onClickButton(View view)
    {
        Toast.makeText(view.getContext(),"Button press",Toast.LENGTH_SHORT).show();
        Log.i(MyHandlers.class.getSimpleName(), "Button press...");
    }
}

Step 2 : Modify activity_main.xml
- Add one more variable inside the <data> tag Eg.
<variable name = "clickHandler" type = "com.testapp.MyHandlers"/> 

 Add button inside the xml file , bind the button with its click even like as below

<Button
    android:layout_width = "wrap_content"
    android:layout_height = "wrap_content"
    android:text = "New Button"
    android:id = "@+id/button"
    android:onClick="@{clickHandler.onClickButton}"/>
We can perform many action using Bind data feature. Please refer following links
Data binding Operation 

I will be happy if you will provide your feedback or follow this blog. Any suggestion and help will be appreciated.
Thank you :)

6 Aug 2015

JSON Parsing Using Gson | gson example Android

JSON is a very common format used in API responses. JSON is very light weight, structured, easy to parse and much human readable. JSON is best alternative to XML when your android app needs to interchange data with your server.

This tutorial will cover how to fetch and parse JSON from a remote server on Android. We will use GSON, a JSON parsing library developed by Google, to quickly parse the JSON into Java objects with very minimal work required.

Gson overview:

Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson is an open-source project hosted at http://code.google.com/p/google-gson.

For more detail, visit Gson User guide

Let’s get started by downloading latest version of Gson .jar & add libs in your project.

Create two classes, SubjectBean and TopicBean. These will be our entity classes that model the data retrieved by the REST calls.You will notice that some fields have the @SerializedName("") annotation. This denotes that the property name does not match the field name in our JSON. If both names do match, there is no need for the annotation.



Steps 1: Create class SubjectBean
import com.google.gson.annotations.SerializedName;

import java.util.ArrayList;

public class SubjectBean
{
    @SerializedName("subject")
    private String subject;

    @SerializedName("price")
    private String price;

    @SerializedName("auther")
    private String auther;

    @SerializedName("topics")
    private ArrayList<TopicBean> beanTopics;

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {

        this.subject = subject;

    }

    public String getPrice() {

        return price;

    }

    public void setPrice(String price) {

        this.price = price;

    }

    public String getAuther() {

        return auther;

    }

    public void setAuther(String auther) {

        this.auther = auther;

    }

    public ArrayList<TopicBean> getBeanTopics() {

        return beanTopics;

    }

    public void setBeanTopics(ArrayList<TopicBean> beanTopics) {

        this.beanTopics = beanTopics;

    }

}

Steps 2: Create class TopicBean

 import com.google.gson.annotations.SerializedName;

public class TopicBean {


    @SerializedName("title")

    private String title;


    public TopicBean(String title) {

        this.title = title;
    }

    public String getTitle() {

        return title;

    }
    public void setTitle(String title) {

        this.title = title;

    }
}

Steps 3: Create class ServiceHandler
 import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

public class ServiceHandler {

    public final static int GET = 1;
    public final static int POST = 2;

    static InputStreamReader inputStreamReader = null;

    public ServiceHandler() {}

    /**
     * Making service call
     *
     * @url - url to make request
     * @method - http request method
     * @params - http request params
     */
    public static  InputStreamReader makeServiceCall(String url, int method,List<NameValuePair> params)
    {
        try
        {
            // http client
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpEntity httpEntity = null;
            HttpResponse httpResponse = null;

            if (method == POST)
            {
                HttpPost httpPost = new HttpPost(url);
                if (params != null)
                {
                    httpPost.setEntity(new UrlEncodedFormEntity(params));
                }

                try
                {
                    httpResponse = httpClient.execute(httpPost);
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
            else if (method == GET)
            {
                if (params != null)
                {
                    String paramString = URLEncodedUtils.format(params, "utf-8");
                    url += "?" + paramString;
                }
                HttpGet httpGet = new HttpGet(url);

                httpResponse = httpClient.execute(httpGet);

            }
            StatusLine statusLine = httpResponse.getStatusLine();
            if (statusLine.getStatusCode() == 200)
            {
                HttpEntity entity = httpResponse.getEntity();
                InputStream content = entity.getContent();
                inputStreamReader = new InputStreamReader(content);
            }
        }
        catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return inputStreamReader;
    }
}
Steps 4: Create class MainActivity
  import android.app.ProgressDialog;

import android.os.AsyncTask;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.util.Log;

import android.widget.TextView;

import com.google.gson.GsonBuilder;

import java.io.Reader;

import java.util.ArrayList;



public class MainActivity extends AppCompatActivity
{

    private ProgressDialog progressDialog;

    private SubjectBean beanSubject;

    private ArrayList<TopicBean> topicArrayList =new ArrayList<>();

    private TextView txtSubject,txtPrice,txtAuther,txtTopicsList;



    @Override

    protected void onCreate(Bundle savedInstanceState)
    {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);



        txtSubject= (TextView) findViewById(R.id.txtSubject);

        txtPrice= (TextView) findViewById(R.id.txtPrice);

        txtAuther= (TextView) findViewById(R.id.txtAuther);

        txtTopicsList= (TextView) findViewById(R.id.txtTopicsList);



        new AsyncTaskData().execute();

    }



   class AsyncTaskData extends AsyncTask<Void,Void,Void>

    {

        StringBuffer topicList;

        @Override

        protected void onPreExecute()

        {

            super.onPreExecute();

            progressDialog=new ProgressDialog(MainActivity.this);

            progressDialog.setCancelable(false);

            progressDialog.setMessage("Loading...");

            progressDialog.show();

        }

        @Override

        protected Void doInBackground(Void... voids)

        {

            Reader reader= ServiceHandler.makeServiceCall("http://beta.json-generator.com/api/json/get/OkS85Le",ServiceHandler.GET,null);


            if(reader!=null)
            {

                beanSubject = new GsonBuilder().create().fromJson(reader, SubjectBean.class);



                topicArrayList=beanSubject.getBeanTopics();

                topicList=new StringBuffer();

                for(TopicBean topic: topicArrayList)
                {

                    Log.e("topic title: ",topic.getTitle()+"");
                    topicList.append("->"+topic.getTitle()+"\n");

                }

            }

            return null;

        }

        @Override

        protected void onPostExecute(Void aVoid)

        {

            super.onPostExecute(aVoid);

            progressDialog.dismiss();

            txtSubject.setText("Subject: "+beanSubject.getSubject());

            txtPrice.setText("price: "+beanSubject.getPrice());

            txtAuther.setText("Auther: "+beanSubject.getAuther());

            txtTopicsList.setText("Topics: "+"\n"+topicList);

        }

    }

}
Steps 5: Add permission to AndroidManifest.xml

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

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



I will be happy if you will provide your feedback or follow this blog. Any suggestion and help will be appreciated.
Thank you :)

4 Aug 2015

Customizing info window contents in Google map v2 Android

In this article we will create an Android application that displays a customized info-window in GoogleMap Android API V2 using InfoWindowAdapter interface.

At first, Please follow this Article to implement Google map with your android application.

Once you have implemented Google map and its working fine with android application, let modify code to show custom info window of Google map.




1. Create info_window_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@android:color/white"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/tv_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center" />

    <TextView
        android:id="@+id/tv_lat"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/tv_lng"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />


</LinearLayout>

2. Modify LoadingGoogleMap Method


Below is the code snippet need to change with previous article.

void LoadingGoogleMap(ArrayList<LatLngBean> arrayList)
       {     
              if (googleMap != null)
              {
                     googleMap.clear();
                     googleMap.getUiSettings().setMyLocationButtonEnabled(true);
                     googleMap.setMyLocationEnabled(true);
                     googleMap.getUiSettings().setZoomControlsEnabled(true);

                     if(arrayList.size()>0)
                     {                                
                           try
                           {                         
                                  listLatLng=new ArrayList<LatLng>();
                                  for (int i = 0; i < arrayList.size(); i++)
                                  {
                                         LatLngBean bean=arrayList.get(i);
                                         if(bean.getLatitude().length()>0 && bean.getLongitude().length()>0)
                                         {
                                                double lat=Double.parseDouble(bean.getLatitude());
                                                double lon=Double.parseDouble(bean.getLongitude());          

                                                Marker marker = googleMap.addMarker(new MarkerOptions()
                                                .position(new LatLng(lat,lon))
                                                .title(bean.getTitle())
                                                .snippet(bean.getSnippet())
                                                .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));

                                                //Add Marker to Hashmap
                                                hashMapMarker.put(marker,bean);

                                                //Set Zoom Level of Map pin
                                                LatLng object=new LatLng(lat, lon);
                                                listLatLng.add(object);
                                         }                                
                                  }
                                  SetZoomlevel(listLatLng);
                           }
                           catch (NumberFormatException e)
                           {
                                  e.printStackTrace();
                           }                         
                           googleMap.setInfoWindowAdapter(new InfoWindowAdapter()
                           {                                
                                  // Use default InfoWindow frame
                                  @Override
                                  public View getInfoWindow(Marker arg0)
                                  {
                                         return null;
                                  }

                                  // Defines the contents of the InfoWindow
                                  @Override
                                  public View getInfoContents(Marker marker)
                                  {                   
                                         // Getting view from the layout file info_window_layout
                                         View v = getLayoutInflater().inflate(R.layout.info_window_layout, null);

                                         // Getting the position from the marker
                                         LatLngBean bean=hashMapMarker.get(marker);

                                         TextView tv_title = (TextView) v.findViewById(R.id.tv_title);
                                         TextView tvLat = (TextView) v.findViewById(R.id.tv_lat);
                                         TextView tvLng = (TextView) v.findViewById(R.id.tv_lng);

                                         tv_title.setText("Title:" + bean.getTitle());
                                         tvLat.setText("Latitude:" + bean.getLatitude());
                                         tvLng.setText("Longitude:"+ bean.getLongitude());

                                         // Returning the view containing InfoWindow contents
                                         return v;

                                  }
                           });

                           googleMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {

                                  @Override
                                  public void onInfoWindowClick(Marker marker)
                                  {
                                         LatLngBean bean=hashMapMarker.get(marker);
                                         Toast.makeText(getApplicationContext(), bean.getTitle(),Toast.LENGTH_SHORT).show();
                                  }
                           });
                     }
              }

              else
              {
                     Toast.makeText(getApplicationContext(),"Sorry! unable to create maps", Toast.LENGTH_SHORT).show();
              }

       }

I will be happy if you will provide your feedback or follow this blog. Any suggestion and help will be appreciated.
Thank you :)