Friday 31 May 2013

How to create custom Dialog Box in android ?

A dialog is a small window that prompts the user to make a decision or enter additional information. A dialog does not fill the screen and is normally used for modal events that require users to take an action before they can proceed.
Dialog is the way where user get notify by app in very clean manner.Dialog is useful for showing alert text, Simple information , show List ,and even you can get value from dialog also.
Android is provide default theme for dialog but if you want to create your own custom dialog then its very easy to build and it will improve your app's look.
So here i will show you a simple example to create custom dialog and same way  you can create any type of dialog as you want.
We will create separate class name with CustomDialogClass which will extent Dialog class and implement android.view.View.OnClickListener.
If you want to  do some action in dialog which need an Activity and Context then its simple you have to create on Constructor and pass  current activity and context as like CustomDialogClass( Activity act , Context ctx).
Yeah, if you want to pass some other params, then same way you have to add when you call your constructor.
So now we are going to build a custom dialog.We will start with XML User Interface .
?
 
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="center"
android:orientation="vertical" >
 
<ImageView
android:id="@+id/user_photo"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="@drawable/user_logo" />
</LinearLayout>
 
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="80dp"
    android:background="#3E80B4"
    android:orientation="vertical" >
 
    <TextView
        android:id="@+id/txt_dia"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="10dp"
        android:text="Do you realy want to exit ?"
        android:textColor="@android:color/white"
        android:textSize="15dp"
        android:textStyle="bold" >
    </TextView>
 
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:background="#3E80B4"
        android:orientation="horizontal" >
 
        <Button
            android:id="@+id/btn_yes"
            android:layout_width="100dp"
            android:layout_height="30dp"
            android:background="@android:color/white"
            android:clickable="true"
            android:text="Yes"
            android:textColor="#5DBCD2"
            android:textStyle="bold" />
 
        <Button
            android:id="@+id/btn_no"
            android:layout_width="100dp"
            android:layout_height="30dp"
            android:layout_marginLeft="5dp"
            android:background="@android:color/white"
            android:clickable="true"
            android:text="No"
            android:textColor="#5DBCD2"
            android:textStyle="bold" />
    </LinearLayout>
 
</LinearLayout>
 
 

<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="center"
android:orientation="vertical" >

<ImageView
android:id="@+id/user_photo"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="@drawable/user_logo" />
</LinearLayout> 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="80dp"
    android:background="#3E80B4"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/txt_dia"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="10dp"
        android:text="Do you realy want to exit ?"
        android:textColor="@android:color/white"
        android:textSize="15dp"
        android:textStyle="bold" >
    </TextView>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:background="#3E80B4"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/btn_yes"
            android:layout_width="100dp"
            android:layout_height="30dp"
            android:background="@android:color/white"
            android:clickable="true"
            android:text="Yes"
            android:textColor="#5DBCD2"
            android:textStyle="bold" />

        <Button
            android:id="@+id/btn_no"
            android:layout_width="100dp"
            android:layout_height="30dp"
            android:layout_marginLeft="5dp"
            android:background="@android:color/white"
            android:clickable="true"
            android:text="No"
            android:textColor="#5DBCD2"
            android:textStyle="bold" />
    </LinearLayout>

</LinearLayout>

CustomDialogClass.java
?
 
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
public class CustomDialogClass extends Dialog implements
android.view.View.OnClickListener {
 
    public Activity c;
    public Dialog d;
    public Button yes, no;
 
    public CustomDialogClass(Activity a) {
        super(a);
        // TODO Auto-generated constructor stub
        this.c = a;
    }
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.custom_dialog);
        yes = (Button) findViewById(R.id.btn_yes);
        no = (Button) findViewById(R.id.btn_no);
        yes.setOnClickListener(this);
        no.setOnClickListener(this);
 
    }
 
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_yes:
                c.finish();
                break;
            case R.id.btn_no:
                dismiss();
                break;
            default:
                break;
        }
        dismiss();
    }
}
 
 

public class CustomDialogClass extends Dialog implements
android.view.View.OnClickListener {

    public Activity c;
    public Dialog d;
    public Button yes, no;

    public CustomDialogClass(Activity a) {
        super(a);
        // TODO Auto-generated constructor stub
        this.c = a;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.custom_dialog);
        yes = (Button) findViewById(R.id.btn_yes);
        no = (Button) findViewById(R.id.btn_no);
        yes.setOnClickListener(this);
        no.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_yes:
                c.finish();
                break;
            case R.id.btn_no:
                dismiss();
                break;
            default:
                break;
        }
        dismiss();
    }
}

Now How to call it, in Activity or any ware in the app area ?
?
 
1
2
3
4
public void Show_Dialog(View v) {
    CustomDialogClass cdd = new CustomDialogClass(MainActivity.this);
    cdd.show();
}
 
 
?
 
1
new DownloadFilesTask().execute(url1, url2, url3);
 
 

new DownloadFilesTask().execute(url1, url2, url3);

Call above method in button's click event like android:onClick="Show_Dialog"
So how it looks  ?
Main ScreenCustom Dialog Screen
Here you can find same example. Check it out.
Hope you learn concept about concept about Custom Dialog and now you are able to crate your own custom dialog.

GitHub-download

Wednesday 29 May 2013

Edit Text Validation

Edit Text is a user input control where user can input something as string or any other data.Edit Text accept any type of data just drag and drop in XML but you have to setInputType to get in specific format data.

User Can get Text Value from Edit Text it can be in simple format or any specific format form above if any.

Simple way to get Text value from Edit Text when user click on Button.
?
 
01
02
03
04
05
06
07
08
09
10
11
12
13
14
public class EditText_Example extends Activity {
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
 
        setContentView(R.layout.main);
 
        final EditText edt = (Button) findViewById(R.id.EditText_Id);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                edt.getText().toStrign();
            }
        });
    }
}
 
 

public class EditText_Example extends Activity {
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        final EditText edt = (Button) findViewById(R.id.EditText_Id);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                edt.getText().toStrign();
            }
        });
    }
}


Here I will show some of the validation which we have to check manually while we are getting value form Edit Text.


  • PersonName

  • Email Address

  • Phone

  • Sign Number

PersonName :

Here we start with Person Name by default if you drag and set InputType="textPersonName"  it will not accept on name or alphabets that also accept numbers . so here i write a code for that only accept alphabets so now when you enter any text then that will check is it text or other symbol ?
Here i wrote a function which we will use in addTextChangedListener for validating valuw when user are typing the value.
?
 
01
02
03
04
05
06
07
08
09
10
11
12
public void Is_Valid_Person_Name(EditText edt) throws NumberFormatException {
    if (edt.getText().toString().length() <= 0) {
        edt.setError("Accept Alphabets Only.");
        valid_name = null;
    } else if (!edt.getText().toString().matches("[a-zA-Z ]+")) {
        edt.setError("Accept Alphabets Only.");
        valid_name = null;
    } else {
        valid_name = edt.getText().toString();
    }
 
}
 
 

public void Is_Valid_Person_Name(EditText edt) throws NumberFormatException {
    if (edt.getText().toString().length() <= 0) {
        edt.setError("Accept Alphabets Only.");
        valid_name = null;
    } else if (!edt.getText().toString().matches("[a-zA-Z ]+")) {
        edt.setError("Accept Alphabets Only.");
        valid_name = null;
    } else {
        valid_name = edt.getText().toString();
    }

}


Now call above function into addTextChangedListener
?
 
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
name.addTextChangedListener(new TextWatcher() {
 
    @Override
    public void onTextChanged(CharSequence s, int start, int before,
        int count) {
        // TODO Auto-generated method stub
    }
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
        int after) {
        // TODO Auto-generated method stub
    }
    @Override
    public void afterTextChanged(Editable s) {
        // TODO Auto-generated method stub
        Is_Valid_Person_Name(name); // pass your EditText Obj here.
    }
});
 
 

name.addTextChangedListener(new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence s, int start, int before,
        int count) {
        // TODO Auto-generated method stub
    }
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
        int after) {
        // TODO Auto-generated method stub
    }
    @Override
    public void afterTextChanged(Editable s) {
        // TODO Auto-generated method stub
        Is_Valid_Person_Name(name); // pass your EditText Obj here.
    }
});


Email Address :

InputType="phone"  when you enter number it accepted but not in Phone Number Format like if you Enter your Number 9898998989 . It will show same as but if you want to input in format then you have to call that on addTextChangedListener(new PhoneNumberFormattingTextWatcher());  So .its shows like 989-899-8989.
?
 
1
phone_number.addTextChangedListener(new PhoneNumberFormattingTextWatcher());
 
 

phone_number.addTextChangedListener(new PhoneNumberFormattingTextWatcher());


Sign Number :

InputType="numberSigned"   i check with minimum and maximum length are valid or not.?  call below function in

?
 
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
public void Is_Valid_Sign_Number_Validation(int MinLen, int MaxLen,
        EditText edt) throws NumberFormatException {
        if (edt.getText().toString().length() <= 0) {
            edt.setError("Sign Number Only");
            valid_sign_number = null;
        } else if (Double.valueOf(edt.getText().toString()) < MinLen ||
            Double.valueOf(edt.getText().length()) > MaxLen) {
            edt.setError("Out of Range " + MinLen + " or " + MaxLen);
            valid_sign_number = null;
        } else {
            valid_sign_number = edt.getText().toString();
            // Toast.makeText(getApplicationContext(),
            // ""+edt.getText().toString(), Toast.LENGTH_LONG).show();
        }
 
    } // END OF Edittext validation
 
 

public void Is_Valid_Sign_Number_Validation(int MinLen, int MaxLen,
        EditText edt) throws NumberFormatException {
        if (edt.getText().toString().length() <= 0) {
            edt.setError("Sign Number Only");
            valid_sign_number = null;
        } else if (Double.valueOf(edt.getText().toString()) < MinLen ||
            Double.valueOf(edt.getText().length()) > MaxLen) {
            edt.setError("Out of Range " + MinLen + " or " + MaxLen);
            valid_sign_number = null;
        } else {
            valid_sign_number = edt.getText().toString();
            // Toast.makeText(getApplicationContext(),
            // ""+edt.getText().toString(), Toast.LENGTH_LONG).show();
        }

    } // END OF Edittext validation


GitHub-download

Tuesday 28 May 2013

Asynctask android example - Part 1

Hello guys , here i will try to explain the concept of the Asynctask  in android.

Class Overview


AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent pacakge such as ExecutorThreadPoolExecutor and FutureTask.

An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called ParamsProgress and Result, and 4 steps, called onPreExecutedoInBackgroundonProgressUpdate and onPostExecute.

Rules:




  • The AsyncTask instance must be created in UI thread.

  • .execute must be invoked on the UI thread.

  • Never call  objMyTask.onPreExecute(), objMyTask.doInBackground(), objMyTask.onProgressUpdate(),  objMyTask.onPostExecute manually.

  • The AsyncTask can be executed only once (an exception will be thrown if a second execution is attempted.)


Method of AsynTask

  1. onPreExecute()

  2. doInBackground()

  3. onProgressUpdate()

  4. onPostExecute()




  • onPreExecute-This method is called first when you start AsyncTask using objAsync.execute().And mostly this method is use for initializing dialog(ProgressDialog,CustomDialog) and showing.



  • doInBackground-The main purpose of AsyncTask is accomplished by this method.Any non-UI thread process is running in this method.Such as Rss Feed Reader,Image and video Uploading and Downloading.You cant handle your View in this method.Because this method is non-UI thread.While any background process is running if you want to handle UI therea are  onProgressUpdate method. after completion of process this method send result to OnPostExecute.



  • onProgressUpdate-While backgrounding task is running ,you can handle your UI using this method .Such as status of downloading or uploading task.and this method is called from  doInBackground.Using publishProgress() you can call onProgressUpdate method to update UI while process is running.



  • onPostExecute -This method is called after the background computation finishes.The result of background process in passed in this method as parameters.And now you can dismiss progress dialog ,to indicate that background task is completed.



You can cancel AsyncTask using objAsyncTask.cancel().then you just check in doInBackground,




AsyncTask's generic types (Type of Parameters)


The three types used by an asynchronous task are the following:

  1. Params, the type of the parameters sent to the task upon execution.

  2. Progress, the type of the progress units published during the background computation.

  3. Result, the type of the result of the background computation.


Not all types are always used by an asynchronous task. To mark a type as unused, simply use the type Void:




See Example





 
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
private class DownloadFilesTask extends AsyncTask < URL, Integer, Long > {
    protected Long doInBackground(URL...urls) {
        int count = urls.length;
        long totalSize = 0;
        for (int i = 0; i < count; i++) {
            totalSize += Downloader.downloadFile(urls[i]);
            publishProgress((int)((i / (float) count) * 100));
            // Escape early if cancel() is called
            if (isCancelled()) break;
        }
        return totalSize;
    }
 
    protected void onProgressUpdate(Integer...progress) {
        setProgressPercent(progress[0]);
    }
 
    protected void onPostExecute(Long result) {
        showDialog("Downloaded " + result + " bytes");
    }
}
 
 

private class DownloadFilesTask extends AsyncTask < URL, Integer, Long > {
    protected Long doInBackground(URL...urls) {
        int count = urls.length;
        long totalSize = 0;
        for (int i = 0; i < count; i++) {
            totalSize += Downloader.downloadFile(urls[i]);
            publishProgress((int)((i / (float) count) * 100));
            // Escape early if cancel() is called
            if (isCancelled()) break;
        }
        return totalSize;
    }

    protected void onProgressUpdate(Integer...progress) {
        setProgressPercent(progress[0]);
    }

    protected void onPostExecute(Long result) {
        showDialog("Downloaded " + result + " bytes");
    }
}


Monday 27 May 2013

How to call Web Service from Android ?

This is first example about web service in android written by me.This will show you how android will communicate with remote server and fetch and send data to server.

List of things that is included in this post :

  • What is Web Service ?

  • How it's works?

  • How to Decode JSON?

  • How to create Custom Dialog ?

  • How to manage  AsyncTask ?

Note: I have wrote separate post of Custom Dialog and AsynTask So, i will not explain in depth.

What are Web Service ?

  • Web services are application components

  • Web services communicate using open protocols

  • Web services are self-contained and self-describing

  • Web services can be discovered using UDDI

  • Web services can be used by other applications

  • XML is the basis for Web services

How does it works ?

[caption id="" align="aligncenter" width="808"] How its' works ?[/caption]

How to Encode & Decode JSON in android?

Encode :
 
1
2
3
4
5
6
// Create JSON obj
JSONObject json = new JSONObject();
 
// encode your json value
json.put("user_name", "test");
json.put("password", "test123");
 
 

// Create JSON obj 
JSONObject json = new JSONObject();

// encode your json value 
json.put("user_name", "test");
json.put("password", "test123");


Decode

  • Decode JSON Object

  • Decode JSON Array

Decode Object 
 
1
2
JSONObject json_data = new JSONObject(response);
String value = json_data.getString("status");
 
 

JSONObject json_data = new JSONObject(response);
String value = json_data.getString("status");


Decode Array 
 
1
2
3
4
5
6
JSONArray jArray = new JSONArray(response);
for (int i = 0; i < jArray.length(); i++) {
    JSONObject json_data = jArray.getJSONObject(i);
    // add to list
    User_ID.add(json_data.getString("user_id"));
}
 
 

JSONArray jArray = new JSONArray(response);
for (int i = 0; i < jArray.length(); i++) {
    JSONObject json_data = jArray.getJSONObject(i);
    // add to list
    User_ID.add(json_data.getString("user_id"));
}


Now we are able to  encode and decode our value in JSON so now we are going to build android app that will
simply connect with server and send and receive simple value.

We have main five java files to maintain this app.

  • Android_WebService.java  [Task - Handle events and views]

  • AsyncTaskCompleteListener.java [Task - Interface for use response in other file]

  • Background_Task.java [Task - Manage Background task using  AsynTask]

  • Custom_alert_DialogClass.java [Task - Custom alert dialog to update UI]

  • Function.java [Task - All Global function and data member]

we are going to start with all one by one java file with comments so it would be easy to use and understand.

Android_WebService.java

This class will prepare the view and manage action like OnClick and Listener.Also we can say that this is root becasue reset of all other file are handleing in this class.
 
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
public class Android_WebService extends Activity implements
AsyncTaskCompleteListener {
 
    Function fun;
    Background_Task bTask;
    Button call_ws;
    String User_Name = null;
    String TAG = "Android_WebService_Error";
    ArrayList < String > User_Id = new ArrayList < String > ();
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Set_View();
 
        call_ws.setOnClickListener(new View.OnClickListener() {
 
            @Override
            public void onClick(View v) {
                try {
                    // check for internet connection
                    if (isNetworkAvailable() == true) {
 
                        // clear older parms value
                        fun.URL_Params.clear();
 
                        // add your params here
 
                        // fun.URL_Params.add(new
                        // BasicNameValuePair("key_value",""));
 
                        // pass your parms to constructor
                        bTask = new Background_Task(fun.URL_Params,
                            Android_WebService.this);
 
                        // show a message while loader is loading
                        fun.Alert_Msg = "Please Wait...\nWe are Authenticating your details";
                        fun.Show_Loader(Android_WebService.this, fun.Alert_Msg);
 
                        // call web service in asyn class
                        bTask.execute("http://chintankhetiya.wordpress.com/");
 
                    } else {
                        fun.Alert_Msg = "Sorry..\n Try to connect Internet first.";
                        fun.Show_Loader(Android_WebService.this, fun.Alert_Msg);
                    }
                } catch (Exception e) {
                    // TODO: handle exception
                    fun.Alert_Msg = "Sorry..\n Try to connect internet first.";
                    fun.Show_Loader(Android_WebService.this, fun.Alert_Msg);
                }
            }
        });
 
    }
 
    public void Call_My_Blog(View v) {
        Intent intent = new Intent(Android_WebService.this, My_Blog.class);
        startActivity(intent);
 
    }
 
    @Override
    public void onTaskComplete(String result) {
        // TODO Auto-generated method stub
        fun.Hide_Loader();
        if (result != null) {
 
            // call and edit below function as per your needs
            /*
             * Response_JSON_Object(result); Response_JSON_Array(result);
             */
 
            fun.Alert_Msg = "congrats ..\n You have create web-service example successfully.";
            fun.Show_Loader(Android_WebService.this, fun.Alert_Msg);
 
            final Timer t = new Timer();
            t.schedule(new TimerTask() {
                public void run() {
                    fun.Hide_Loader(); // when the task active then close the
                    // dialog
                    t.cancel(); // also just top the timer thread,
                    // otherwise, you may receive a crash report
                }
            }, fun.Dialog_Time_Limit); // after 2 second (or 2000
            // miliseconds), the task will
            // be active.
 
        } else {
            fun.Alert_Msg = "Sorry..\n We are not able connect with Chintan Khetiya's Blog due to slow Internet Connction.\n Reset WI-FI or Try Later";
            fun.Show_Loader(Android_WebService.this, fun.Alert_Msg);
 
            final Timer t = new Timer();
            t.schedule(new TimerTask() {
                public void run() {
                    fun.Hide_Loader(); // when the task active then close the
                    // dialog
                    t.cancel(); // also just top the timer thread,
                    // otherwise, you may receive a crash report
                }
            }, fun.Dialog_Time_Limit); // after 2 second (or 2000
            // miliseconds), the task will
            // be active.
 
        }
 
    }
 
    public String Response_JSON_Object(String Buffer_Response) {
        try {
            JSONObject json_data = new JSONObject(Buffer_Response);
            User_Name = json_data.getString("User_Name").toString();
            return User_Name;
        } catch (Exception e) {
            Log.e(TAG, "Json Object issue" + e);
        }
        return User_Name;
 
    }
 
    public ArrayList < String > Response_JSON_Array(String Buffer_Response) {
        try {
            JSONArray jArray = new JSONArray(Buffer_Response);
            for (int i = 0; i < jArray.length(); i++) {
                JSONObject json_data = jArray.getJSONObject(i);
                // add to list
                User_Id.add(json_data.getString("user_id"));
            }
 
        } catch (Exception e) {
            // TODO: handle exception
            Log.e(TAG, "Json array issue" + e);
        }
        return User_Id;
    }
 
    public void Set_View() {
        fun = new Function(getApplicationContext());
        call_ws = (Button) findViewById(R.id.call);
 
    }
 
    public boolean isNetworkAvailable() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = cm.getActiveNetworkInfo();
        // if no network is available networkInfo will be null
        // otherwise check if we are connected
        if (networkInfo != null && networkInfo.isConnected()) {
            return true;
        }
        return false;
    }
}
 
 

public class Android_WebService extends Activity implements
AsyncTaskCompleteListener {

    Function fun;
    Background_Task bTask;
    Button call_ws;
    String User_Name = null;
    String TAG = "Android_WebService_Error";
    ArrayList < String > User_Id = new ArrayList < String > ();

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

        call_ws.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                try {
                    // check for internet connection
                    if (isNetworkAvailable() == true) {

                        // clear older parms value
                        fun.URL_Params.clear();

                        // add your params here

                        // fun.URL_Params.add(new
                        // BasicNameValuePair("key_value",""));

                        // pass your parms to constructor
                        bTask = new Background_Task(fun.URL_Params,
                            Android_WebService.this);

                        // show a message while loader is loading
                        fun.Alert_Msg = "Please Wait...\nWe are Authenticating your details";
                        fun.Show_Loader(Android_WebService.this, fun.Alert_Msg);

                        // call web service in asyn class
                        bTask.execute("http://chintankhetiya.wordpress.com/");

                    } else {
                        fun.Alert_Msg = "Sorry..\n Try to connect Internet first.";
                        fun.Show_Loader(Android_WebService.this, fun.Alert_Msg);
                    }
                } catch (Exception e) {
                    // TODO: handle exception
                    fun.Alert_Msg = "Sorry..\n Try to connect internet first.";
                    fun.Show_Loader(Android_WebService.this, fun.Alert_Msg);
                }
            }
        });

    }

    public void Call_My_Blog(View v) {
        Intent intent = new Intent(Android_WebService.this, My_Blog.class);
        startActivity(intent);

    }

    @Override
    public void onTaskComplete(String result) {
        // TODO Auto-generated method stub
        fun.Hide_Loader();
        if (result != null) {

            // call and edit below function as per your needs
            /*
             * Response_JSON_Object(result); Response_JSON_Array(result);
             */

            fun.Alert_Msg = "congrats ..\n You have create web-service example successfully.";
            fun.Show_Loader(Android_WebService.this, fun.Alert_Msg);

            final Timer t = new Timer();
            t.schedule(new TimerTask() {
                public void run() {
                    fun.Hide_Loader(); // when the task active then close the
                    // dialog
                    t.cancel(); // also just top the timer thread,
                    // otherwise, you may receive a crash report
                }
            }, fun.Dialog_Time_Limit); // after 2 second (or 2000
            // miliseconds), the task will
            // be active.

        } else {
            fun.Alert_Msg = "Sorry..\n We are not able connect with Chintan Khetiya's Blog due to slow Internet Connction.\n Reset WI-FI or Try Later";
            fun.Show_Loader(Android_WebService.this, fun.Alert_Msg);

            final Timer t = new Timer();
            t.schedule(new TimerTask() {
                public void run() {
                    fun.Hide_Loader(); // when the task active then close the
                    // dialog
                    t.cancel(); // also just top the timer thread,
                    // otherwise, you may receive a crash report
                }
            }, fun.Dialog_Time_Limit); // after 2 second (or 2000
            // miliseconds), the task will
            // be active.

        }

    }

    public String Response_JSON_Object(String Buffer_Response) {
        try {
            JSONObject json_data = new JSONObject(Buffer_Response);
            User_Name = json_data.getString("User_Name").toString();
            return User_Name;
        } catch (Exception e) {
            Log.e(TAG, "Json Object issue" + e);
        }
        return User_Name;

    }

    public ArrayList < String > Response_JSON_Array(String Buffer_Response) {
        try {
            JSONArray jArray = new JSONArray(Buffer_Response);
            for (int i = 0; i < jArray.length(); i++) {
                JSONObject json_data = jArray.getJSONObject(i);
                // add to list
                User_Id.add(json_data.getString("user_id"));
            }

        } catch (Exception e) {
            // TODO: handle exception
            Log.e(TAG, "Json array issue" + e);
        }
        return User_Id;
    }

    public void Set_View() {
        fun = new Function(getApplicationContext());
        call_ws = (Button) findViewById(R.id.call);

    }

    public boolean isNetworkAvailable() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = cm.getActiveNetworkInfo();
        // if no network is available networkInfo will be null
        // otherwise check if we are connected
        if (networkInfo != null && networkInfo.isConnected()) {
            return true;
        }
        return false;
    }
}


AsyncTaskCompleteListener.java

This is separate class to handle incoming parmas value form root class and run task in background thread.
It will redirect when task will complete.
 
1
2
3
4
public interface AsyncTaskCompleteListener {
    // it will call when background process finish
    public void onTaskComplete(String result);
}
 
 

public interface AsyncTaskCompleteListener {
    // it will call when background process finish
    public void onTaskComplete(String result);
}


Background_Task.java
 
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
public class Background_Task extends AsyncTask {
 
    public Activity activity;
    Context context;
    public AsyncTaskCompleteListener callback;
    ArrayList URL_Params = new ArrayList();
    Function fun = new Function();
    ProgressDialog Loader_Dialog;
    Custom_alert_DialogClass cad;
 
    public Background_Task(ArrayList URL_Params, Activity act) {
        this.URL_Params = URL_Params;
 
        this.activity = act;
        this.callback = (AsyncTaskCompleteListener) act;
    }
 
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        try {
 
            Log.i("onPre", "call");
        } catch (Exception e) {
            // TODO: handle exception
            Log.e("onPre", "" + e);
        }
 
    }
 
    @Override
    protected String doInBackground(String...web_url) {
        try {
            // this will send req in post
            // here [0] mean URL & passing params
            Log.i("onDO", "call");
 
            fun.Send_Simple_Detail_To_Server(web_url[0], URL_Params);
 
            Log.i("onDO", "SEND");
 
            // this will get stream response
            fun.Buffer_Response();
            Log.i("onDO", "GET RES");
 
        } catch (Exception e) {
            // TODO: handle exception
            Log.e("onDo", "" + e);
        }
 
        return fun.Buffer_String_Response;
    }
 
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        // check is dialog open ? THEN HIDE DIALOG
        try {
            Log.i("onPOST", "DONE");
            Log.i("onPOST", "" + result);
 
            callback.onTaskComplete(result);
        } catch (Exception e) {
            Log.e("onPost", "" + e);
            // TODO: handle exception
        }
 
    }
 
}
 
 

public class Background_Task extends AsyncTask {

    public Activity activity;
    Context context;
    public AsyncTaskCompleteListener callback;
    ArrayList URL_Params = new ArrayList();
    Function fun = new Function();
    ProgressDialog Loader_Dialog;
    Custom_alert_DialogClass cad;

    public Background_Task(ArrayList URL_Params, Activity act) {
        this.URL_Params = URL_Params;

        this.activity = act;
        this.callback = (AsyncTaskCompleteListener) act;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        try {

            Log.i("onPre", "call");
        } catch (Exception e) {
            // TODO: handle exception
            Log.e("onPre", "" + e);
        }

    }

    @Override
    protected String doInBackground(String...web_url) {
        try {
            // this will send req in post
            // here [0] mean URL & passing params
            Log.i("onDO", "call");

            fun.Send_Simple_Detail_To_Server(web_url[0], URL_Params);

            Log.i("onDO", "SEND");

            // this will get stream response
            fun.Buffer_Response();
            Log.i("onDO", "GET RES");

        } catch (Exception e) {
            // TODO: handle exception
            Log.e("onDo", "" + e);
        }

        return fun.Buffer_String_Response;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        // check is dialog open ? THEN HIDE DIALOG
        try {
            Log.i("onPOST", "DONE");
            Log.i("onPOST", "" + result);

            callback.onTaskComplete(result);
        } catch (Exception e) {
            Log.e("onPost", "" + e);
            // TODO: handle exception
        }

    }

}


Custom_alert_DialogClass.java

Custom Dialog to updating UI status so user get notify that what is going on.
 
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
public class Custom_alert_DialogClass extends Dialog {
 
    public Activity a;
    public String Msg;
    public Dialog d;
    public Button no;
    public Context context;
    public TextView alert_infromation_text;
    ProgressBar pb;
    LinearLayout exit_layout;
 
    public Custom_alert_DialogClass(Activity a, String Msg) {
        super(a);
        // TODO Auto-generated constructor stub
        this.a = a;
        this.Msg = Msg;
 
    }
 
    /**
     * Constructor for Custom_alert_DialogClass.java Called for initializing
     * object of Custom_alert_DialogClass.java.
     *
     * @param function
     * @param alert_Msg
     */
    public Custom_alert_DialogClass(Context c, String alert_Msg) {
        // TODO Auto-generated constructor stub
 
        super(c);
        this.context = c;
        this.Msg = alert_Msg;
 
    }
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.custom_alert_dialog);
        Create_Alert_DialogView();
 
        no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                dismiss();
 
                a.finish();
 
            }
        });
 
    }
 
    public void Create_Alert_DialogView() {
 
        no = (Button) findViewById(R.id.Dailog_Exit);
        exit_layout = (LinearLayout) findViewById(R.id.exit_layout);
        exit_layout.setVisibility(View.GONE);
        alert_infromation_text = (TextView) findViewById(R.id.alert_infromation_text);
        alert_infromation_text.setText(Msg);
        pb = (ProgressBar) findViewById(R.id.progressBar1);
        no.setVisibility(View.GONE);
    }
 
}
 
 

public class Custom_alert_DialogClass extends Dialog {

    public Activity a;
    public String Msg;
    public Dialog d;
    public Button no;
    public Context context;
    public TextView alert_infromation_text;
    ProgressBar pb;
    LinearLayout exit_layout;

    public Custom_alert_DialogClass(Activity a, String Msg) {
        super(a);
        // TODO Auto-generated constructor stub
        this.a = a;
        this.Msg = Msg;

    }

    /**
     * Constructor for Custom_alert_DialogClass.java Called for initializing
     * object of Custom_alert_DialogClass.java.
     * 
     * @param function
     * @param alert_Msg
     */
    public Custom_alert_DialogClass(Context c, String alert_Msg) {
        // TODO Auto-generated constructor stub

        super(c);
        this.context = c;
        this.Msg = alert_Msg;

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.custom_alert_dialog);
        Create_Alert_DialogView();

        no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                dismiss();

                a.finish();

            }
        });

    }

    public void Create_Alert_DialogView() {

        no = (Button) findViewById(R.id.Dailog_Exit);
        exit_layout = (LinearLayout) findViewById(R.id.exit_layout);
        exit_layout.setVisibility(View.GONE);
        alert_infromation_text = (TextView) findViewById(R.id.alert_infromation_text);
        alert_infromation_text.setText(Msg);
        pb = (ProgressBar) findViewById(R.id.progressBar1);
        no.setVisibility(View.GONE);
    }

}


Function.java

All data member and function are written here so it will easy to execute and understand.
 
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
public class Function {
    public ConnectivityManager cm;
    public NetworkInfo ni;
    public InputStream is;
    Context ctx;
    JSONObject jObjec = new JSONObject();
    String Buffer_String_Response = null;
    Custom_alert_DialogClass cad;
    public ArrayList URL_Params = new ArrayList();
    String Alert_Msg;
    long Dialog_Time_Limit = 3000;
 
    public Function(Context context) {
        this.ctx = context;
    }
 
    public Function() {
 
    }
 
    public void Send_JSON_Encode_Detail_To_Server(String URL, JSONObject jobj) {
        try {
 
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(URL);
            httppost.setHeader("Content-type", "application/json");
            StringEntity se = new StringEntity(jobj.toString());
            se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                "application/json"));
            httppost.setEntity(se);
            HttpResponse response = httpclient.execute(httppost);
            String temp = EntityUtils.toString(response.getEntity());
            Log.i("tag", temp);
 
        } catch (ConnectTimeoutException e) {
            Log.e("Timeout Exception: ", e.toString());
 
        } catch (SocketTimeoutException ste) {
            Log.e("Timeout Exception: ", ste.toString());
 
        } catch (Exception e) {
            Log.e("HTTP_Execption", "Error in http connection " + e.toString());
 
        }
    }
 
    public void Send_Simple_Detail_To_Server(String URL,
        ArrayList nameValuePairs)
 
    {
        try {
 
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(URL);
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
 
            is = entity.getContent();
 
        } catch (ConnectTimeoutException e) {
            Log.e("Timeout Exception: ", e.toString());
 
        } catch (SocketTimeoutException ste) {
            Log.e("Timeout Exception: ", ste.toString());
 
        } catch (Exception e) {
            Log.e("HTTP_Execption", "Error in http connection " + e.toString());
 
        }
    }
 
    public void Buffer_Response() {
        try {
            Buffer_String_Response = null;
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            Buffer_String_Response = sb.toString();
 
        } catch (Exception e) {
            Log.e("Loading Runnable Error converting result :", e.toString());
 
        }
 
    }
 
    public void Show_Loader(Activity a, String Text_Message) {
 
        cad = new Custom_alert_DialogClass(a, Text_Message);
        cad.show();
    }
 
    public void Hide_Loader()
 
    {
        if (cad != null && cad.isShowing()) {
            cad.dismiss();
        }
 
    }
 
}
 
 

public class Function {
    public ConnectivityManager cm;
    public NetworkInfo ni;
    public InputStream is;
    Context ctx;
    JSONObject jObjec = new JSONObject();
    String Buffer_String_Response = null;
    Custom_alert_DialogClass cad;
    public ArrayList URL_Params = new ArrayList();
    String Alert_Msg;
    long Dialog_Time_Limit = 3000;

    public Function(Context context) {
        this.ctx = context;
    }

    public Function() {

    }

    public void Send_JSON_Encode_Detail_To_Server(String URL, JSONObject jobj) {
        try {

            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(URL);
            httppost.setHeader("Content-type", "application/json");
            StringEntity se = new StringEntity(jobj.toString());
            se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                "application/json"));
            httppost.setEntity(se);
            HttpResponse response = httpclient.execute(httppost);
            String temp = EntityUtils.toString(response.getEntity());
            Log.i("tag", temp);

        } catch (ConnectTimeoutException e) {
            Log.e("Timeout Exception: ", e.toString());

        } catch (SocketTimeoutException ste) {
            Log.e("Timeout Exception: ", ste.toString());

        } catch (Exception e) {
            Log.e("HTTP_Execption", "Error in http connection " + e.toString());

        }
    }

    public void Send_Simple_Detail_To_Server(String URL,
        ArrayList nameValuePairs)

    {
        try {

            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(URL);
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();

            is = entity.getContent();

        } catch (ConnectTimeoutException e) {
            Log.e("Timeout Exception: ", e.toString());

        } catch (SocketTimeoutException ste) {
            Log.e("Timeout Exception: ", ste.toString());

        } catch (Exception e) {
            Log.e("HTTP_Execption", "Error in http connection " + e.toString());

        }
    }

    public void Buffer_Response() {
        try {
            Buffer_String_Response = null;
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            Buffer_String_Response = sb.toString();

        } catch (Exception e) {
            Log.e("Loading Runnable Error converting result :", e.toString());

        }

    }

    public void Show_Loader(Activity a, String Text_Message) {

        cad = new Custom_alert_DialogClass(a, Text_Message);
        cad.show();
    }

    public void Hide_Loader()

    {
        if (cad != null && cad.isShowing()) {
            cad.dismiss();
        }

    }

}


Don't forget to update your manifest with Permission
 
1
2
uses - permission android: name = "android.permission.INTERNET"
uses - permission android: name = "android.permission.ACCESS_NETWORK_STATE
 
 

uses - permission android: name = "android.permission.INTERNET"
uses - permission android: name = "android.permission.ACCESS_NETWORK_STATE


Get Full Source code 

GitHub-download