Search This Blog

Sunday, March 31, 2013

DialogFragment

android.app.DialogFragment, was introduced from API Level 11 (Android 3.0), displays a dialog window, floating on top of its activity's window.


public class MyDialogFragment extends DialogFragment {

            static MyDialogFragment newInstance() {

            String title = "My Fragment";

            MyDialogFragment f = new MyDialogFragment();
            Bundle args = new Bundle();
            args.putString("title", title);
            f.setArguments(args);
            return f;
            }

            @Override
            public Dialog onCreateDialog(Bundle savedInstanceState) {
                            String title = getArguments().getString("title");
                            Dialog myDialog = new AlertDialog.Builder(getActivity())
                                                   .setIcon(R.drawable.ic_launcher)
                                                   .setTitle(title)
                                                   .setPositiveButton("OK", 

                                                      new DialogInterface.OnClickListener() {
                     @Override
                     public void onClick(DialogInterface dialog, int which) {
                                      ((AndroidDialogFragmentActivity)getActivity()).okClicked();
                    }
                })
                                                  .setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {

                   @Override
                   public void onClick(DialogInterface dialog, int which) {
                                      ((AndroidDialogFragmentActivity)getActivity()).cancelClicked();
                   }
               })
              .create();

return myDialog;
}

}


in main.xml modify the following code.


<?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="fill_parent"
android:orientation="vertical" >

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<Button
android:id="@+id/opendialog"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Open Dialog" />

</LinearLayout>


now in your activity just change the following code and see the dialog

public class DialogFragmentActivity extends Activity {
                          /** Called when the activity is first created. */
                         @Override
                         public void onCreate(Bundle savedInstanceState) {
                                      super.onCreate(savedInstanceState);
                                      setContentView(R.layout.main);


                                Button buttonOpenDialog = (Button)findViewById(R.id.opendialog);
                                buttonOpenDialog.setOnClickListener(new Button.OnClickListener(){

                               @Override
                               public void onClick(View arg0) {
                                                  OpenDialog();
                                }});

                  }

                  void OpenDialog(){
                         MyDialogFragment myDialogFragment = MyDialogFragment.newInstance();
                         myDialogFragment.show(getFragmentManager(), "myDialogFragment");
                  }

                 public void okClicked() {
                          Toast.makeText(AndroidDialogFragmentActivity.this,
                                           "OK Clicked!",
                                           Toast.LENGTH_LONG).show();
                 }

                 public void cancelClicked() {
                                  Toast.makeText(AndroidDialogFragmentActivity.this,
                                                 "Cancel Clicked!",  Toast.LENGTH_LONG).show();
                  }
}

Draw bar chart in android

This is the same as the Last Tutorial i have posted. We just need to implement the following code in the View instead of the last tutorial.


public class DrawBarChart extends View {
Paint paint = new Paint();
int c[] = { Color.BLUE, Color.RED };
Canvas mCanvas = new Canvas();
private float[] val_exp;
private float[] val_inco;
Context context;
WindowManager mWinMgr;

public DrawBarChart(Context context) {
super(context);
paint = new Paint();
super.draw(mCanvas);
}

public DrawBarChart(Context context, AttributeSet attrs) {
super(context, attrs);
paint = new Paint();
super.draw(mCanvas);
}

public DrawBarChart(Context context, float[] val_exp, float[] val_inco) {
super(context);
paint = new Paint();
this.val_exp = val_exp;
this.val_inco = val_inco;
super.draw(mCanvas);
}

public void draw(Canvas canvas) {
int x = getWidth();
int y = getHeight();
float max = getMax();
paint.setColor(Color.parseColor("#78777D"));
paint.setStyle(Style.STROKE);
paint.setStrokeWidth(2);
canvas.drawRect(0, 0, x - 1, y - 1, paint);
int n = val_exp.length;
int gap = x / 12;
paint.setStyle(Style.FILL);
for (int i = 0; i < n; i++) {

paint.setColor(Color.BLACK);
//Bottom Numbers 1 to 12.
canvas.drawText("" + (i + 1), i * gap + (gap / 2), y - 5, paint);    

//Vertical Lines.
canvas.drawLine((float) (i + 0.5) * gap + 4, y - 15,
(float) (i + 0.5) * gap + 4, y - 25, paint);    
            
// Blue bars for Income.
paint.setColor(Color.BLUE);
canvas.drawLine(i * gap + 5, y - 20, (float) (i + 0.5) * gap + 3,
y - 20, paint);

float bHeIn =(max==0)?y-20:  y - (val_inco[i] * (y - 22) / max)- 20;

canvas.drawRect((float) i   * gap + 5, bHeIn,
(float) (i + 0.5) * gap + 3, y - 20, paint);

// Red bars for Expenses.
paint.setColor(Color.RED);
canvas.drawLine((float) (i + 0.5) * gap + 5, y - 20,
(float) (i + 1) * gap + 3, y - 20, paint);

float bHeEx =(max==0)?y-20:  y - (val_exp[i] * (y - 22) / max)- 20;

canvas.drawRect((float) (i + 0.5) * gap + 5, bHeEx,
(float) (i + 1) * gap + 3, y - 20, paint);
}
}

private float getMax() {
float max = 0;
for (float f : val_exp) {
if (f > max)
max = f;
}
for (float f : val_inco) {
if (f > max)
max = f;
}
return max;
}
}

And for drawing the chart of the values of the data you need to pass the values to the objects of the class as follow.    


           DrawBarChart barView;
           LinearLayout la;

           barView = new DrawBarChart(this, vals_exp,vals_inco);
          la.addView(barView);

Draw PieChart in android using View

Fitst of all make an Relative layout as the below in your XML file to Display Pie chart on that view.

<RelativeLayout

       android:id="@+id/piechart_lay"
       android:layout_width="150dip"
       android:layout_height="150dip"
       android:layout_margin="5dip"
       android:background="#eeffee"
       android:orientation="horizontal" >
</RelativeLayout>


Now we have to make a View which make the actual pie chart and draw and fill the color in the chart. Create one file let's say DrawPieChart.java extends View and add the following code snippet in it.

public class DrawPieChart extends View {

Paint paint = new Paint();
        //  Here you can Add number of different color according to max different colors to be displayed on Piechart
        int c[] = {Color.MAGENTA,Color.BLUE,Color.RED,Color.CYAN,Color.YELLOW,Color.GREEN};
Canvas mCanvas = new Canvas();
private int[] values;
Context context;

public DrawPieChart(Context context, int[] values) {
super(context);
paint = new Paint();
this.values = values;
// this.labels = labels;
super.draw(mCanvas);
}

public void draw(Canvas canvas) {
int x = getWidth();
int y = getHeight();
float t = getTotal();
paint.setColor(Color.parseColor("#78777D"));
paint.setStyle(Style.STROKE);
paint.setStrokeWidth(2);
canvas.drawRect(0, 0, x - 1, y - 1, paint);
int n = values.length;
float cuurPos = -90;
paint.setStyle(Style.FILL);
RectF rect = new RectF(20,20,x-20,y-20);
for (int i = 0; i < n; i++) {
paint.setColor(c[i]);
float thita =(t==0)?0: 360*values[i]/t;
canvas.drawArc(rect, cuurPos, thita, true, paint);
cuurPos = cuurPos+thita;
}
}

private float getTotal() {
int total = 0;
for (int i = 0; i < values.length; i++) {
total = total + values[i];
}
return total;
}
}

Now create an object of this class in your activity and pass the Array of the values to the object and it will create the Piechart in the Relative layout. You have to add this view in the Activity to your relative layout.


class Piechart extends Activity{


        RelativeLayout la;
DrawPieChart piView;
        int[] vals;


       @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.relative);
                la = (RelativeLayout) findViewById(R.id.pie_lay);
                getPieChart();
        }
        
        public void  getPieChart(){
             vals[] = new vals[YOUR SIZE OF ARRAY];
             vals = {12,14,23,35,23,56,78};
             piView = new DrawPieChart(Analisys.this, vals);
             
             la.removeAllViews();
     la.addView(piView); 
       }
}



Saturday, March 30, 2013

Streaming songs from Url in Default Media Player

Here i am posting with the example code of the streaming the songs from the Url in android with android default media player. 

First of all you just have to make the XML file with the following lines

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
android:focusable="true">
<EditText 
android:text="The song URL" 
android:layout_width="fill_parent" 
android:layout_height="wrap_content" 
android:id="@+id/EditTextSongURL"/>
<ImageButton 
android:layout_below="@+id/EditTextSongURL"
android:id="@+id/ButtonTestPlayPause" 
android:layout_height="wrap_content" 
android:layout_width="match_parent"
android:src="@drawable/button_play"/>
<SeekBar 
android:layout_below="@+id/ButtonTestPlayPause"
android:id="@+id/SeekBarTestPlay" 
android:layout_height="wrap_content" 
android:layout_width="match_parent"
android:thumb="@drawable/thumb_transparent"/>
</RelativeLayout>

Now in you main Activity class replace with the following code and enter the URL of your server song and hit play.

public class StreamingPlayer extends Activity implements OnClickListener, OnTouchListener, OnCompletionListener, OnBufferingUpdateListener{

private ImageButton buttonPlayPause;
private SeekBar seekBarProgress;
public EditText editTextSongURL;

private MediaPlayer mediaPlayer;
// this value contains the song duration in milliseconds. Loook at getDuration() method in MediaPlayer class
private int mediaFileLengthInMilliseconds; 

private final Handler handler = new Handler();

** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
             super.onCreate(savedInstanceState);
             setContentView(R.layout.main);
             initView();
}

/** This method initialise all the views in project*/
private void initView() {
             buttonPlayPause = (ImageButton)findViewById(R.id.ButtonTestPlayPause);
             buttonPlayPause.setOnClickListener(this);

             seekBarProgress = (SeekBar)findViewById(R.id.SeekBarTestPlay);
             seekBarProgress.setMax(99); // It means 100% .0-99
             seekBarProgress.setOnTouchListener(this);
             editTextSongURL = (EditText)findViewById(R.id.EditTextSongURL);
             editTextSongURL.setText(R.string.testsong_20_sec);

             mediaPlayer = new MediaPlayer();
             mediaPlayer.setOnBufferingUpdateListener(this);
             mediaPlayer.setOnCompletionListener(this);
}

/** Method which updates the SeekBar primary progress by current song playing position*/
private void primarySeekBarProgressUpdater() {
              seekBarProgress.setProgress((int)                                     (((float)mediaPlayer.getCurrentPosition()/mediaFileLengthInMilliseconds)*100)); // This math construction give a percentage of "was playing"/"song length"
                     if (mediaPlayer.isPlaying()) {
                                     Runnable notification = new Runnable() {
                                                         public void run() {
                                                                    primarySeekBarProgressUpdater();
                                                         }
                                     };
                    handler.postDelayed(notification,1000);
       }
}

@Override
public void onClick(View v) {

           if(v.getId() == R.id.ButtonTestPlayPause){
/** ImageButton onClick event handler. Method which start/pause mediaplayer playing */
             try {
                   // setup song URL to mediaplayer data source
                  mediaPlayer.setDataSource(editTextSongURL.getText().toString());
                  mediaPlayer.prepare();
                 } catch (Exception e) {
                  e.printStackTrace();
               }

mediaFileLengthInMilliseconds = mediaPlayer.getDuration();

           if(!mediaPlayer.isPlaying()){
                mediaPlayer.start();
                buttonPlayPause.setImageResource(R.drawable.button_pause);
           }else {
                mediaPlayer.pause();
                buttonPlayPause.setImageResource(R.drawable.button_play);
          }

          primarySeekBarProgressUpdater();
     }
}

@Override
public boolean onTouch(View v, MotionEvent event) {
           if(v.getId() == R.id.SeekBarTestPlay){
             /** Seekbar onTouch event handler. Method which seeks MediaPlayer to seekBar        primary progress position*/
                    if(mediaPlayer.isPlaying()){
                          SeekBar sb = (SeekBar)v;
                          int playPositionInMillisecconds = (mediaFileLengthInMilliseconds / 100) * sb.getProgress();
                         mediaPlayer.seekTo(playPositionInMillisecconds);
                    }
               }
          return false;
     }


@Override
public void onCompletion(MediaPlayer mp) {
       /** MediaPlayer onCompletion event handler. Method which calls then song playing is complete*/
           buttonPlayPause.setImageResource(R.drawable.button_play);
}

@Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
/** Method which updates the SeekBar secondary progress by current song loading from URL position*/
             seekBarProgress.setSecondaryProgress(percent);
      }
}

Sunday, March 24, 2013

Calling the POST method using the MultipartEntity with Image and Data

Here is the method to post the image and audio File along with the data.

For multipart you need to add the libraries along with the project as below.




1) Download httpcomponents-client-4.1.zip from http://james.apache.org/download.cgi#Apache_Mime4Jand add apache-mime4j-0.6.1.jar to your project.


2) Download httpcomponents-client-4.1-bin.zip from http://hc.apache.org/downloads.cgi and add httpclient-4.1.jar, httpcore-4.1.jar and httpmime-4.1.jar to your project.

and here is the method of the posting the image and data to service.

public int PostMerthodWithImage(byte[] data, String postStr, String pointNumber,
String name, String ext) {
try {
mHttpClient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(urlString); \\ pass the Url of the webservice here
MultipartEntity multipartEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
Log.i("log_tag", "name :" + name + "  ::::: And Ext :" + ext);

if (data != null) {
bab = new ByteArrayBody(data, name.trim() + ".".trim()
+ ext.trim());
image_video_name = name.trim() + ".".trim() + ext.trim();
multipartEntity.addPart("image_video", bab);
multipartEntity.addPart("image_video_name", new StringBody(
image_video_name, Charset.forName("UTF-8")));
Log.i("log_tag", "At send image_video_name :"
+ image_video_name);
} else {
bab = null;
image_video_name = null;
}
// multipartEntity.addPart("image_video", bab);
// Log.i("log_tag", "At send bytearray :" + bab.toString());
multipartEntity.addPart("point_id", new StringBody(pointNumber,
Charset.forName("UTF-8")));
Log.i("log_tag", "At send point_id :" + pointNumber);
multipartEntity.addPart("user_id",
new StringBody("1", Charset.forName("UTF-8")));
Log.i("log_tag", "At send user_id :" + "1");
multipartEntity.addPart("comment_text", new StringBody(postStr,
Charset.forName("UTF-8")));
Log.i("log_tag", "At send comment_text :" + postStr);
multipartEntity.addPart(
"date",
new StringBody("" + System.currentTimeMillis(), Charset
.forName("UTF-8")));
Log.i("log_tag", "At send date :" + System.currentTimeMillis());
httppost.setEntity(multipartEntity);
HttpResponse response1 = mHttpClient.execute(httppost);
HttpEntity r_entity = response1.getEntity();
String Response = EntityUtils.toString(r_entity);
JSONObject jobj = null;
try {
jobj = new JSONObject(Response);
} catch (JSONException e) {
e.printStackTrace();
}
try {
Joj = jobj.getString("status");
} catch (Exception e) {
}
Log.i("log_tag", "Response from server :" + Response);
mHttpClient.getConnectionManager().shutdown();
} catch (Exception e) {
Log.e(HttppostClient.class.getName(), e.getLocalizedMessage(), e);
}
if (Joj == "1") {
return 1;
} else {
return 0;
}

}

Animation : Fade-In Fade-out


Create XML file for fade-in animation, /res/anim/fadein.xml.


<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/linear_interpolator">
<alpha
android:fromAlpha="0.1"
android:toAlpha="1.0"
android:duration="2000"
/>
</set>


Create XML file for fade-out animation, /res/anim/fadeout.xml.
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/linear_interpolator">
<alpha
android:fromAlpha="1.0"
android:toAlpha="0.1"
android:duration="2000"
/>
</set>



Modify main.xml

<?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="fill_parent"
android:orientation="vertical" >

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<Button
android:id="@+id/fadein"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Fade In"/>
<Button
android:id="@+id/fadeout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Fade Out"/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:gravity="center">

<ImageView
android:id="@+id/image"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="@drawable/ic_launcher" />

</LinearLayout>

</LinearLayout>




main activity


public class AndroidAnimTranslateActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

Button buttonFadeIn = (Button)findViewById(R.id.fadein);
Button buttonFadeOut = (Button)findViewById(R.id.fadeout);
final ImageView image = (ImageView)findViewById(R.id.image);

final Animation animationFadeIn = AnimationUtils.loadAnimation(this, R.anim.fadein);
buttonFadeIn.setOnClickListener(new Button.OnClickListener(){

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
image.startAnimation(animationFadeIn);
}});

final Animation animationFadeOut = AnimationUtils.loadAnimation(this, R.anim.fadeout);
buttonFadeOut.setOnClickListener(new Button.OnClickListener(){

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
image.startAnimation(animationFadeOut);
}});
}
}


Tween animation: Rotate animation

Create /res/anim/rotate_center.xml for animation of rotating around center
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/linear_interpolator">
<rotate
android:fromDegrees="0"
android:toDegrees="360"
android:pivotX="50%"
android:pivotY="50%"
android:duration="2000"
android:startOffset="0"/>
</set>


Create /res/anim/rotate_corner.xml for animation of rotating around the upper-left corner


<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/linear_interpolator">
<rotate
android:fromDegrees="0"
android:toDegrees="360"
android:pivotX="0%"
android:pivotY="0%"
android:duration="2000"
android:startOffset="0"/>
</set>



modify main.xml as below.

<?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="fill_parent"
android:orientation="vertical" >

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<Button
android:id="@+id/rotatecenter"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Rotate around center"/>
<Button
android:id="@+id/rotatecorner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Rotate around corner"/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:gravity="center">

<ImageView
android:id="@+id/floatingimage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" />

</LinearLayout>

</LinearLayout>


main activitypackage com.exercise.AndroidAnimTranslate;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;

public class AndroidAnimTranslateActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

Button buttonRotateCenter = (Button)findViewById(R.id.rotatecenter);
Button buttonRotateCorner = (Button)findViewById(R.id.rotatecorner);
final ImageView floatingImage = (ImageView)findViewById(R.id.floatingimage);

final Animation animationRotateCenter = AnimationUtils.loadAnimation(this, R.anim.rotate_center);
buttonRotateCenter.setOnClickListener(new Button.OnClickListener(){

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
floatingImage.startAnimation(animationRotateCenter);
}});

final Animation animationRotateCorner = AnimationUtils.loadAnimation(this, R.anim.rotate_corner);
buttonRotateCorner.setOnClickListener(new Button.OnClickListener(){

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
floatingImage.startAnimation(animationRotateCorner);
}});
}
}

Sunday, March 3, 2013

Calling the web-service in android with POST and GET method

Hello guys Here i am posting the method of calling the webservice in android using POST and GET method.


public class RestClient {

   private ArrayList <NameValuePair> params;
   private ArrayList <NameValuePair> headers;

   private String url;

   private int responseCode;
   private String message;

   private String response;

   public String getResponse() {
       return response;
   }

   public String getErrorMessage() {
       return message;
   }

   public int getResponseCode() {
       return responseCode;
   }

   public RestClient(String url)
   {
       this.url = url;
       params = new ArrayList<NameValuePair>();
       headers = new ArrayList<NameValuePair>();
   }

   public void AddParam(String name, String value)
   {
       params.add(new BasicNameValuePair(name, value));
   }

   public void AddHeader(String name, String value)
   {
       headers.add(new BasicNameValuePair(name, value));
   }

   public void Execute(RequestMethod method) throws Exception
   {
       switch(method) {
           case GET:
           {
               //add parameters
               String combinedParams = "";
               if(!params.isEmpty()){
                   combinedParams += "?";
                   for(NameValuePair p : params)
                   {
                       String paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(),”UTF-8″);
                       if(combinedParams.length() > 1)
                       {
                           combinedParams  +=  "&" + paramString;
                       }
                       else
                       {
                           combinedParams += paramString;
                       }
                   }
               }

               HttpGet request = new HttpGet(url + combinedParams);

               //add headers
               for(NameValuePair h : headers)
               {
                   request.addHeader(h.getName(), h.getValue());
               }

               executeRequest(request, url);
               break;
           }
           case POST:
           {
               HttpPost request = new HttpPost(url);

               //add headers
               for(NameValuePair h : headers)
               {
                   request.addHeader(h.getName(), h.getValue());
               }

               if(!params.isEmpty()){
                   request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
               }

               executeRequest(request, url);
               break;
           }
       }
   }

   private void executeRequest(HttpUriRequest request, String url)
   {
       HttpClient client = new DefaultHttpClient();

       HttpResponse httpResponse;

       try {
           httpResponse = client.execute(request);
           responseCode = httpResponse.getStatusLine().getStatusCode();
           message = httpResponse.getStatusLine().getReasonPhrase();

           HttpEntity entity = httpResponse.getEntity();

           if (entity != null) {

               InputStream instream = entity.getContent();
               response = convertStreamToString(instream);

               // Closing the input stream will trigger connection release
               instream.close();
           }

       } catch (ClientProtocolException e)  {
           client.getConnectionManager().shutdown();
           e.printStackTrace();
       } catch (IOException e) {
           client.getConnectionManager().shutdown();
           e.printStackTrace();
       }
   }

   private static String convertStreamToString(InputStream is) {

       BufferedReader reader = new BufferedReader(new InputStreamReader(is));
       StringBuilder sb = new StringBuilder();

       String line = null;
       try {
           while ((line = reader.readLine()) != null) {
               sb.append(line + "\n");
           }
       } catch (IOException e) {
           e.printStackTrace();
       } finally {
           try {
               is.close();
           } catch (IOException e) {
               e.printStackTrace();
           }
       }
       return sb.toString();
   }
}

Now here is the calling example of the method.

RestClient client = new RestClient(URL of the webservice); 
client.AddParam("param1", "String of param1"); 
client.AddParam("param2", "String of param2"); 
client.AddParam("Email", email); 
client.AddParam("Passwd", passcode); 
          try { 
                   client.Execute(RequestMethod.POST);  //  OR GET 
              }   
            catch (Exception e) {  
                  e.printStackTrace(); 
            }
 String response = client.getResponse();