Wednesday, 30 August 2017

Retrofit Android Tutorial with Recyclerview


Retrofit Android Tutorial with Recyclerview

Hello guys, In this Retrofit android tutorial I am going to explain about how to use Retrofit REST client to consume the Rest Web services.Basically, Retrofit developed by square and It's a type-safe REST client for Android.


Advantages of retrofit

Retrofit is dead-simple to use. It essentially lets you treat API calls as simple Java method calls, so you only define which URLs to hit and the types of the request/response parameters as Java classes.  The entire network call + JSON/XML parsing is completely handled by it (with help from Gson for JSON parsing), along with support for arbitrary formats with pluggable serialization/deserialization.

Speed:

Compare with Volley and AsyncTask, Retrofit providing the very fast response to the request.


Retrofit android tutorial Let's get into the code part,
First, We have to add the retrofit dependency into our build.grade file. We can find the latest retrofit version in the official retrofit website. http://square.github.io/retrofit/
compile 'com.squareup.retrofit2:retrofit:2.3.0'
And the gson converter from retrofit used to convert the JSON response from the server.
compile 'com.squareup.retrofit2:converter-gson:2.3.0'


Create the Retrofit instance

We need to create the Retrofit instance to send the network requests. we need to use the Retrofit Builder class and specify the base URL for the service.


ApiClient.java

package com.example.velm.retrofitexample;

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;


public class ApiClient {

    public static String BASE_URL ="http://10.0.2.2:3000/api/";
    private static Retrofit retrofit;
    public static Retrofit getClient(){
        if(retrofit == null){
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}

Setting Up the Retrofit Interface

Retrofit provides the list of annotations for each HTTP methods:
@GET, @POST, @PUT, @DELETE, @PATCH or @HEAD.
The endpoints are defined inside of an interface using retrofit annotations to encode details about the parameters and request method. T return value is always a parameterized Call<T>.
Because the POJO classes are wrapped into a typed Retrofit Call class.
Method Parameters :
@Body – Sends Java objects as the request body.
@Url – use dynamic URLs.
@Query – We can simply add a method parameter with @Query() and a query parameter name, describing the type. To URL encode a query using the form:
@Query(value = "auth_token",encoded = true) String auth_token



ApiInterface.java

package com.example.velm.retrofitexample;

import java.util.List;
import retrofit2.Call;
import retrofit2.http.GET;

public interface ApiInterface {

    @GET("movies/")
    Call<List<Movie>> getMovies();
}

Creating Model Class
Before creating the model, we need to know what type of response we will be receiving.

http://localhost:3000/api/movies/

[  
   {  
      "name":"Titanic",
      "year":"1997",
      "Director":"James Cameron"
   },
   {  
      "name":"Ghost in the Shell",
      "year":"2017",
      "Director":"Rupert Sanders"
   },
   {  
      "name":"Security",
      "year":"2017",
      "Director":"Alain Desrochers"
   },
   {  
      "name":"Gifted",
      "year":"2017",
      "Director":"Marc Webb"
   }
]

In my JSON response, I am having the list of movies with name, year and director properties. So, My Model class will be like Movie as class name and name, year, director are properties.|


Movie.java

package com.example.velm.retrofitexample;

import com.google.gson.annotations.SerializedName;

public class Movie {

    @SerializedName("name")
    private String name;
    @SerializedName("year")
    private String year;
    @SerializedName("actor")
    private String actor;

    public Movie(String name, String year, String actor) {
        this.name = name;
        this.year = year;
        this.actor = actor;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getYear() {
        return year;
    }

    public void setYear(String year) {
        this.year = year;
    }

    public String getActor() {
        return actor;
    }

    public void setActor(String actor) {
        this.actor = actor;
    }


    @Override
    public String toString() {
        return "Movie{" +
                "name='" + name + '\'' +
                ", year='" + year + '\'' +
                ", actor='" + actor + '\'' +
                '}';
    }
}
@SerializedName is used to map the POJO object into to JSON response properties.

Consume the REST web service

All the setup are done. Now we are ready to consume the REST web service. In Our MainActivity.Java, First, need to initialize the ApiClient.

ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);


After the initialization, we to call the getMovies() interface and implement the CallBacks. Part of the Implementation we need to override the onResponse() and onFailure().

If the request succeeds the callback will come into onResponse(). If any error in the request the callback will go into onFailure() method. In onResponse() method, we can get our response from response body.


ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);

        Call<List<Movie>> call = apiService.getMovies();

        call.enqueue(new Callback<List<Movie>>() {
            @Override
            public void onResponse(Call<List<Movie>> call, Response<List<Movie>> response) {
                movieList = response.body();
                Log.d("TAG","Response = "+movieList);               
            }

            @Override
            public void onFailure(Call<List<Movie>> call, Throwable t) {
                Log.d("TAG","Failed = "+t.toString());
            }
        });
Now our data is ready, then I am going to set the data into the recyclerview.

Setup Recyclerview

adding the recyclerview dependency into our build.grade file.
compile 'com.android.support:recyclerview-v7:26.0.+'

Please check my Recyclerview tutorial for more details about recyclerview.
Create the recyclerview

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    tools:context="com.example.velm.retrofitexample.MainActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</LinearLayout>

create the
recyclerview adapter
RecyclerAdapter.java

package com.example.velm.retrofitexample;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import org.w3c.dom.Text;

import java.util.List;

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyviewHolder> {

    Context context;
    List<Movie> movieList;

    public RecyclerAdapter(Context context, List<Movie> movieList) {
        this.context = context;
        this.movieList = movieList;
    }

    @Override
    public RecyclerAdapter.MyviewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.recycler_layout,parent,false);
        return new MyviewHolder(view);
    }

    @Override
    public void onBindViewHolder(RecyclerAdapter.MyviewHolder holder, int position) {
        holder.tvMovieName.setText(movieList.get(position).getName());
    }

    @Override
    public int getItemCount() {
        return movieList.size();
    }

    public class MyviewHolder extends RecyclerView.ViewHolder {
        TextView tvMovieName;

        public MyviewHolder(View itemView) {
            super(itemView);
            tvMovieName = (TextView)itemView.findViewById(R.id.textViewMovieName);
        }
    }
}
 
recycler_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/textViewMovieName"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:padding="5dp"
        android:gravity="center_vertical"
        android:textColor="@color/cardview_dark_background"
        android:layout_weight="1"
        android:text="TextView" />
</LinearLayout>
Recylerview is ready. Now I am going to set the data that we got from the response into the recyclerview.


ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);

        Call<List<Movie>> call = apiService.getMovies();

        call.enqueue(new Callback<List<Movie>>() {
            @Override
            public void onResponse(Call<List<Movie>> call, Response<List<Movie>> response) {


                movieList = response.body();
                Log.d("TAG","Response = "+movieList);
                recyclerAdapter = new RecyclerAdapter(getApplicationContext(),movieList);
                recyclerView.setAdapter(recyclerAdapter);

            }

            @Override
            public void onFailure(Call<List<Movie>> call, Throwable t) {
                Log.d("TAG","Response = "+t.toString());
            }
        });
The final MainActivity.java.
MainActivity.java

package com.example.velm.retrofitexample;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity {

    List<Movie> movieList;
    RecyclerView recyclerView;
    RecyclerAdapter recyclerAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        movieList = new ArrayList<>();
        recyclerView = (RecyclerView)findViewById(R.id.recyclerview);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        
        ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
        Call<List<Movie>> call = apiService.getMovies();

        call.enqueue(new Callback<List<Movie>>() {
            @Override
            public void onResponse(Call<List<Movie>> call, Response<List<Movie>> response) {
                movieList = response.body();
                Log.d("TAG","Response = "+movieList);
                recyclerAdapter = new RecyclerAdapter(getApplicationContext(),movieList);
                recyclerView.setAdapter(recyclerAdapter);
            }

            @Override
            public void onFailure(Call<List<Movie>> call, Throwable t) {
                Log.d("TAG","Response = "+t.toString());
            }
        });
    }
}
                                         

                                                   Retrofit android tutorial


Wednesday, 24 May 2017

Kotlin android Examples

Kotlin android

Kotlin an official language on Android

Kotlin android

Kotlin




Normally we will create the native android applications in java programming language.



When run we run the java application, the application compiled into bytecode contains set of instructions and runs in the virtual machine.



JetBrains is a software development company. Who developed the android studio based on IntelliJ.

Now JetBrains introduced the Kotlin language.

Kotlin is programming language runs on the JVM.


Why Kotlin For Android?

Kotlin is very easy to start because it works side by side with Java and C++ on Android.So you can keep your existing code, continue to use the various Android libraries, and incrementally add Kotlin code to your project

Kotlin reduces the amount of boilerplate code.

you can call into the Java language from Kotlin, and you can call into Kotlin from the Java language.

Kotlin is expressive, concise, extensible, powerful, and a joy to read and write.

Kotlin has safety features like nullability and immutability to increase the performance and health of the android application.

install the kotlin plugin:

Kotlin plugin is inbuilt in android studio 3.0 version,
For the earlier version, you can use following steps to install the kotlin plugin in your android studio.

1.open your android studio.
go to File under files, select Settings.
Kotlin android
File > Settings

2.In Settings, you can see the many items like Appearance, Editor, Plugins, version control and etc in these select Plugins.
Kotlin android
plugins

3.Under plugin, you can see the Install JetBrains plugin at the bottom of the window.
select Install JetBrains plugin.
In the Browse JetBrains plugin window, search for the kotlin.
Kotlin android
Kotlin

4.Install the kotin plugin.
Once the installation completed it will ask you to restart the android studio.

Kotlin android
Restart
The kotlin plugin installed in your android studio, Now you can develop the android application with kotlin language.

Please check this installation of kotlin plugin in android studio.


First Kotlin android applicattion

Below, I am going to show you how to develop kotlin android application in android studio.

1. open android studio and create new project.
Kotlin android
Create new project

After entering the Application and company domain click Next,
In my case I have named the application name as FirstKotlinApp.

Then, Select for what purpose you are going to develop this application like Mobile and Tablet and wear or TV.
Please select Mobile and Tablet , press Next,
Kotlin android
Mobile and Tablet
Create new Blank Activity to start the app as a Normal blank activity,
Click Next,
Kotlin android
Blank Activity
In this step It will ask you to configure the Activity Name and Layout Name, In my project I set the default name for both activity and layout.
Then click finish.
Kotlin android
Activity Name
Now you can see the default java android project be created .

You need to convert the Java project in to kotlin project.
You can also do convert kotlin to  java project.

To convert the java langage to kotlin , you need to "Enter Action" in android studio.

Press "ctrl + shift + a" to open the Enter action tool.

Kotlin android
Enter action
In the enter action search for "Convert Java File to Kotlin File" then press enter to convert the java files into kotlin files.
Now you can see the Java file is converted into kotlin file. the extension of the file chnaged from .java to .kt

After converting the java files into kotlin you cannot directly edit the code. still kotlin not configured.
You need to configure the kotlin in the gradle build system.
Kotlin not configured
select the config > android with gradle to add the kotlin into the gradle.

Kotlin android

Adding the kotlin into gradle make the changes in the gradle file.
Kotlin android


Once added the kotlin into the gradle in will ask you the sync the project.


Kotlin android
Sync
Once the sync is done , Now you application is ready to run.

You can't see any difference in java language android application and kotlin language android application UI.
It will be in the speed and processing.

MainActivty.Kt 

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

    }
}


Screenshot of the FirstKotlinApp



Monday, 22 May 2017

webview in android studio example

WebView is a view that display web pages inside your application. 
You can also specify HTML string and can show it inside your application using WebView. 
WebView makes turns your application into a web application.


To create webview first, you need to create webview in activity XML.


<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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">

    <WebView
        android:id="@+id/webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</android.support.constraint.ConstraintLayout>



Map the webview into the Activity java File.


and enable the setJavaScriptEnabled(true)

then load the url into the webview.

webview.loadUrl("");




        webView = (WebView) findViewById(R.id.webview);
        webView.getSettings().setLoadsImagesAutomatically(true);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        webView.setWebViewClient(new MyBrowser());
        webView.loadUrl("https://velmuruganandroidcoding.blogspot.in");

Methods of webview Class.


canGoBack() - This method specifies the WebView has a back history item.
canGoForward() - This method specifies the WebView has a forward history item.
clearHistory() - This method will clear the WebView forward and backward history.
destroy() - This method destroys the internal state of WebView.

findAllAsync(String find) - This method finds all instances of string and highlights them.


getProgress() - This method gets the progress of the current page.


getTitle() - This method returns the title of the current page.


getUrl() - This method returns the URL of the current page.



If you click on any link inside the webpage of the WebView, 

That page will not be loaded inside your WebView. 
In order to do that you need to extend your class from WebViewClient and override its method. 


private class MyBrowser extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    }


Example :

MainActivity.Java



package rajaapps.lifeandtechnology;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends AppCompatActivity {



    WebView webView ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        webView = (WebView) findViewById(R.id.webview);
        webView.getSettings().setLoadsImagesAutomatically(true);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        webView.setWebViewClient(new MyBrowser());
        webView.loadUrl("https://velmuruganandroidcoding.blogspot.in");

    }
    private class MyBrowser extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    }
}


main_activity.xml



<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
    tools:context="rajaapps.lifeandtechnology.MainActivity">

    <WebView
        android:id="@+id/webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</android.support.constraint.ConstraintLayout>


Don't forget to add internet permission
<uses-permission android:name="android.permission.INTERNET"/>


AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="rajaapps.lifeandtechnology">
    <uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>



Screenshot:
webview in android studio
webview in android studio

Download example