Tuesday 20 October 2015

Android WebService Tutorial

WebService - AsyncTask - JSON Parsing -  ListView

Scope:

In this Tutorial , I will be explaining about how to invoke a webservice [RESTFUL] from Android.

How to handle the webservice response [JSON]

How to parse the response and display it in a ListView.

Introduction:

Why do we invoke webservice? 

In recent times almost all the websites are going with a mobile application. So, mobiles applications, very often you should get data from a Web Service to update content displayed to users.

JSON?

RESFUL webservices return their response in the form of JSON .  JSON is best alternaive to XML .
JSON is very light weight, structured, easy to parse and much human readable.

Sample JSON:
{
    "contacts": [
        {
                
                "name": "Prabhuraj",
                "email": "prabhuraj@gmail.com",
                "job": {
                    "designation": "Developer",
                    "city": "Chennai",
                       }
        },
        {
                "name": "Johnny Depp",
                "email": "johnny_depp@gmail.com",
                "job": {
                  "designation": "SeniorDeveloper",
                    "city": "Hyderabad",

                }
        }, ........
]
}

Here Square bracket ([) represents starting of an JSONArray node whereas curly bracket ({) represents JSONObject.

Creating a new Android Project in Android Studio


1. Create a new project in Android Studio from file-> new -> new project  [give the name you want]

A default activity and a Layout xml will be created. I named it as WebServiceExampleActivity and activity_web_service_example.xml

2. Modify the Manifest file to include permission as


<manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="example.com.example2" >

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


3. Am going to display the parsed JSON  in a ListView, so declaring a ListView widget in my Layout xml.


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"     android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"     android:paddingRight="@dimen/activity_horizontal_margin"     android:paddingTop="@dimen/activity_vertical_margin"     android:paddingBottom="@dimen/activity_vertical_margin"     tools:context="example.com.example2.ListViewExampleActivity">     <ListView         android:id="@+id/list"         android:layout_width="match_parent"         android:layout_height="wrap_content"></ListView> </RelativeLayout>


4. My WebServiceExampleActivity

package example.com.example2;



import android.app.Activity;

import android.os.AsyncTask;

import android.os.Bundle;

import android.widget.ArrayAdapter;

import android.widget.ListView;



import org.apache.http.HttpEntity;

import org.apache.http.HttpResponse;

import org.apache.http.client.ClientProtocolException;

import org.apache.http.client.HttpClient;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.impl.client.DefaultHttpClient;

import org.apache.http.protocol.BasicHttpContext;

import org.apache.http.protocol.HttpContext;

import org.apache.http.util.EntityUtils;

import org.json.JSONArray;

import org.json.JSONException;

import org.json.JSONObject;

import java.io.IOException;

import java.util.ArrayList;

import java.util.List;



public class WebServiceExampleActivity extends Activity {

    ArrayList<String> arrayList = new ArrayList<String>();

    ListView listView;

    static String response = null;

    private static final String TAG_CONTACTS = "contacts";

    private static final String TAG_NAME = "name";

    JSONArray contacts = null;


    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_web_service_example);

        listView = (ListView) findViewById(R.id.mylist);

        new GetContacts().execute();

    }


// webservice call I have written as a sepearate method for readability 

    public String servicecall(){

        HttpClient httpClient = new DefaultHttpClient();

        HttpContext localContext = new BasicHttpContext();

        HttpGet httpGet = new HttpGet("http://api.androidhive.info/contacts/");

        String text = null;

        try {

            HttpResponse httpresponse = httpClient.execute(httpGet, localContext);

            HttpEntity entity = httpresponse.getEntity();

            response = EntityUtils.toString(entity);



        } catch (ClientProtocolException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        }

        return response;

    }



    public class GetContacts extends AsyncTask<Void, Void, List<String>> {


        @Override

        protected void onPreExecute() {

            super.onPreExecute();

          }


// doInBackground is by default void returns null. Here since I am using a List to store the //values, its declarations is modified as protected List<String> doInBackground().

// When this is modified, automatically the parameter in postexecute is modified.
        @Override

        protected List<String> doInBackground(Void... params) {

            String jsonresponse = servicecall();



            if (jsonresponse != null){

                try {

                    JSONObject jsonObject = new JSONObject(jsonresponse);

                    contacts = jsonObject.getJSONArray(TAG_CONTACTS);

                    for (int i=0 ; i<= contacts.length(); i++){

                        JSONObject innerobject = contacts.getJSONObject(i);

                        String name = innerobject.getString("name");

                        arrayList.add(name);

                    }

                } catch (JSONException e) {

                    e.printStackTrace();

                }

            }

            return arrayList;

        }


// ArrayAdapter should always be  ArrayAdapter<String>  though we are using a List. The conte//nts are String. This will throw error if its modified as ArrayAdapter<<List<String>>

        @Override

        protected void onPostExecute(List<String> result) {

            ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,arrayList);

            listView.setAdapter(arrayAdapter);

        }
    }

}



Sunday 27 September 2015

ViewPager Tutorial

Android provides this widget ViewPager to swipe among views. You can swipe left to right or viceversa. In this tutorial, I am going to explain a easiest way to use this widget.  

Step 1: Declare ViewPager in your main layout

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:id="@+id/relativeLayout">


    <android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </android.support.v4.view.ViewPager>

</RelativeLayout>


Step 2: Modify your main activity to access your ViewPagerAdapter and set it in your ViewPager.



import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.Menu;

public class MainActivity extends Activity {

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  ViewPagerAdapter adapter = new ViewPagerAdapter(this, res);
  ViewPager myPager = (ViewPager) findViewById(R.id.images);
  myPager.setAdapter(adapter);
  myPager.setCurrentItem(0);
 }

 private int res[] = { R.drawable.chennai, R.drawable.mumbai,
   R.drawable.delhi, R.drawable.calcutta};
}


Step 3: Create your PagerAdapter.

import android.app.Activity;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;

public class ViewPagerAdapter extends PagerAdapter {

 Context context;
 int [] res;

 public ViewPagerAdapter(Context context, int[] res) {
  this.res= res;
  this.context = context;
 }

 public int getCount() {
  return res.length;
 }

 public Object instantiateItem(View collection, int position) {
  ImageView view = new ImageView(activity);
  view.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
    LayoutParams.FILL_PARENT));
  view.setScaleType(ScaleType.FIT_XY);
  view.setBackgroundResource(res[position]);
  ((ViewPager) collection).addView(view, 0);
  return view;
 }

 @Override
 public void destroyItem(View arg0, int arg1, Object arg2) {
  ((ViewPager) arg0).removeView((View
}

Mandatory Methods:


getCount() – This method should return the number of views available, i.e., number of pages to be displayed/created in the ViewPager. instantiateItem() – This method should create the page for the given position passed to it as an argument. In our case, we inflate() our layout resource to create the hierarchy of view objects and then set resource for the ImageView in it. Finally, the inflated view is added to the container (which should be the ViewPager) and return it as well. destroyItem() – Removes the page from the container for the given position. We simply removed object using removeView() but could’ve also used removeViewAt() by passing it theposition. isViewFromObject() – The object returned by instantiateItem() is a key/identifier. This method checks whether the View passed to it (representing the page) is associated with that key or not. It is required by a PagerAdapter to function properly. For our example, the implementation of this method is really simple, we just compare the two instances and return the evaluated boolean.

References:
http://www.androidbegin.com/tutorial/android-viewpager-gallery-images-and-texts-tutorial/
http://androidtrainningcenter.blogspot.in/2012/10/viewpager-example-in-android.html
http://codetheory.in/android-image-slideshow-using-viewpager-pageradapter/

Saturday 20 June 2015

Easiest Android Fragments Tutorial


In this tutorial, we will go through the following topics

  • What is a Fragment?
  • Why should we go for Fragment?
  • Different Approaches for creating a Fragment
What is a Fragment ?

  • A Fragment is a piece of an application's user interface or behavior that can be placed in an Activity.
  • A Fragment enables more modular Activity design. Its a kind of Sub-Activity.It has its own LifeCycle.
  • A Fragment represents a portion of a user interface or an operation that runs within an Activity.
Why should we go for Fragment?
  • The main reason why one should go for Fragments is  the convenience of reusing the components in different layouts. 
  • With the fragments we have more flexibility and can remove the limitation of having a single activity on the screen at a time. 
  • Now we can have a single activity but each activity can comprise of multiple fragments which will have their own layout, events and complete life cycle.

Different Approaches for creating a Fragment:

There are 2 different approaches for calling a Fragment from an Activity.
  1. Calling it from Activity's XML [Layout]
  2. Calling it from Java code [MainActivity]


Type 1: Creating a Fragment and Calling it from Activitys XML Layout

1.1 Create a Layout for the Fragment.

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"    // Height is given as wrap_content so as to distinguish between Fragment and Acivity
    android:background="#00bbff"                // To distinguish between Fragment and Acivity
    tools:context="in.blogspot.easyandroidtutorial.workouts.FirstFragment">

    <TextView
        android:padding="70dp"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="@string/hello_blank_fragment" />

</FrameLayout>

1.2 Create your FirstFragment class that extends Fragment class.

package in.blogspot.easyandroidtutorial.workouts;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class FirstFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_first, container, false);
    }
}
 
1.3 Create your MainActivity

package in.blogspot.easyandroidtutorial.workouts;

import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;


public class MyActivity extends Activity {

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

1.4 Modify your MainAcivity's layout to call the fragment created in 1.1

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:id="@+id/myact"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:background="#ffbb00"    // To distinguish between Fragment and Acivity
    tools:context="in.blogspot.easyandroidtutorial.workouts.MyActivity">

    <fragment
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:name="in.blogspot.easyandroidtutorial.workouts.FirstFragment"
        android:id="@+id/fragment"
        android:layout_alignParentTop="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

</RelativeLayout>





Type 2: Creating a Fragment and Calling it from MainActivity's Java code  

Here the Steps 1.1, 1.2 are same.

2.3 Create your MainActivity's Layout

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:id="@+id/myact"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:background="#ffbb00"
    tools:context="in.blogspot.easyandroidtutorial.workouts.MyActivity">

</RelativeLayout>

2.4 Modify your MainActivity to call your FirstFragment

package in.blogspot.easyandroidtutorial.workouts;

import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;


public class MyActivity extends Activity {

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

       // Getting the FragmentManager instance associated with this class
        FragmentManager fm = getFragmentManager(); 
        FragmentTransaction ft = fm.beginTransaction();

        FirstFragment firstFragment = new FirstFragment();

      // Add the FirstFragment instance to your MainActivitys Layout
        ft.add(R.id.myact, firstFragment);

        ft.commit();
    }

That's it. Done. 

Output:






Your comments on this tutorial are most Welcome. Please help improving this blog by your valuable comments. Thanks. Happy Coding




Wednesday 17 June 2015

Easiest RecyclerView Example

RecyclerView ?

The RecyclerView is a new ViewGroup  similar to and much more than a LisView.
It is supossed to be the successor of ListView and GridView with Material Design Style.
It can be found in the latest support-v7 version.

How to use RecyclerView ?

The 2 mandatory elements require to create a RecyclerView are.

–Your Adapter that extends RecyclerView.Adapter and implements your ViewHolder
– LayoutManager [Default layout manager -LinearLayoutManager.]


Note: Your ViewHolder class is a simple class with a constructor to find the views in your layout.

Step 1: Add dependency in your build.gradle

dependencies {
    
    compile 'com.android.support:recyclerview-v7:21.0.+'
}

Step 2: Add RecyclerView in Layout 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:scrollbars="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />

</LinearLayout>


Step 3:  Design your RowView

<?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="match_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="40dp"
        android:id="@+id/list_item"
        xmlns:android="http://schemas.android.com/apk/res/android" />


</LinearLayout>

Step 4: Create your Adapter for RecyclerView. and your ViewHolder class

The new RecyclerView.Adapter abstract/generic class is similar in behavior to the old BaseAdapter. There are 3  methods you need to implement:

onCreateViewHolder – It creates the ViewHolder for speciic row display.It inflates the row layout for the row and creates a ViewHolder with that layout.

onBindViewHolder – It updates the row’s View components with data from the dataset.Called by the RecyclerView when it needs to display the data at the position/row specified as a parameter.

getItemCount – It returns the number of rows in the associated data set.

Code:

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

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
    private String[] dataSource;
    public RecyclerAdapter(String[] dataArgs){
        dataSource = dataArgs;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        // create a new view
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item, parent, false);
        ViewHolder viewHolder = new ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        holder.textView.setText(dataSource[position]);
    }

    @Override
    public int getItemCount() {
        return dataSource.length;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder{
        public TextView textView;
        public ViewHolder(View itemView) {
            super(itemView);
            textView = (TextView) itemView;
        }
    }
}

Step 5: Modify your MainAcivity to use the RecyclerView

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

public class MainActivity extends Activity {
    private RecyclerView recyclerView;
    private RecyclerView.Adapter adapter;
    private RecyclerView.LayoutManager layoutManager;
    String[] dataArray = new String[]{"JellyBean","KitKat","Lollipop"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        recyclerView.setHasFixedSize(true);
        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new RecyclerAdapter(dataArray);
        recyclerView.setAdapter(adapter);
    }
}


OutPut:





Another excellent tutorial on RecyclerView is available at

https://www.binpress.com/tutorial/android-l-recyclerview-and-cardview-tutorial/156

http://www.vogella.com/tutorials/AndroidRecyclerView/article.html

http://blog.lovelyhq.com/creating-lists-with-recyclerview-in-android/

Monday 8 June 2015

Easiest ListView Example

This is a simplest Android Example for Android ListView

Introduction:

Android ListView is a view group that displays a list of scrollable items.

Android provides ListView and ExpandableListView classes for displaying scrollable list of items.

Note 1: When creating your main activity , you can extend ListActivity to use the default ListView but make sure you declare it as,

<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/mainText"
android:id="@android:id/list"


Also, you can assign the list adapter as

setListAdapter(myAdapter);

Thats the only difference.

Note 2: Important: Though you have a  ArrayList of Strings as source for listview, whenever you use the ArrayAdapter it should be declared as ArrayAdapter<String>

Adapter:
An adapter manages the data model and adapts it to the individual entries in the widget. An adapter extends the BaseAdapter class.

Default Adapters:
Android provides default adapter implementations; the most important are ArrayAdapter and CursorAdapter. ArrayAdapter can handle data based on Arrays or java.util.List. SimpleCursorAdapter can handle database related data.


Step 1 : Create a layout file with ListView
Step 2 : In your Activity, access the ListView created in Step 1 and perform the possible desired actions


  • Get ListView object from xml
  • Defined Array values to show in ListView
  • Define a new Adapter
  • Assign adapter to ListView
  • Implement ListView Item Click Listener





Step 1 : Create a layout file with ListView

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MyListView">

    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/listview1"></ListView>

</RelativeLayout>




Step 2 :  In your Activity, access the ListView created in Step 1 and perform the possible desired actions.


public class MyListView extends Activity {
    ListView lv;

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

        lv = (ListView)findViewById(R.id.listview1);     // Get ListView object from xml

        String values[] = {"Jellybean","Kitkat","Lollipop"};  // Defined Array values to show in ListView

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, android.R.id.text1,values);   // Define a new Adapter

        lv.setAdapter(adapter);  // Assign adapter to ListView

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {    //Implement ListView Item Click Listener
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                int position = i;

                String x = (String)lv.getItemAtPosition(i);

                Toast.makeText(getApplicationContext(),"the selected item is " +x+" and at postion "+position, Toast.LENGTH_LONG).show();;
            }
        });

    }



OutPut : 










Excellent Tutorial on Customized Adapter is available in 

http://www.codelearn.org/android-tutorial/android-listview