Search This Blog

Showing posts with label StringBuilder. Show all posts
Showing posts with label StringBuilder. Show all posts

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();

Sunday, December 30, 2012

Calling the PHP web service in android and fetch the result in Android

Suppose the url of the php webservice is as follow :

http://XX.XX.XXX.XX/~serverji/home_expanditure/gethistory.php?uid=4&month=10&year=2012

XX.XX.XXX.XX stands for the server IP.

And the response from the this url is like this :

{"date":["2012-10-13","2012-10-11","2012-10-08"],"category":["The Food Expense","rent","Communication costs"],"description":["nasto","google","fii"],"expenditure":["40","100","123"]}

Then we have to go for this kind of requesting to the url :


public class HistoryDto {
  String date;
  String category;
  String descri;
  float expe;
}


static String url = "http://XX.XX.XX.XXX/~serverji/home_expanditure/";


public static ArrayList<HistoryDto> gethistory(int month, String year) {
String result = "";
InputStream is = null;
ArrayList<HistoryDto> hisList = new ArrayList<HistoryDto>();

ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("uid", Myapplication
.getuserID()));
nameValuePairs.add(new BasicNameValuePair("month", "" + month));
nameValuePairs.add(new BasicNameValuePair("year", year));

try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url + "gethistory.php?");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// convert response to string
try {
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();
result = sb.toString().trim();

} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}

try {
JSONObject jObj = new JSONObject(result);
JSONArray JArray_date = jObj.getJSONArray("date");
JSONArray JArray_cat = jObj.getJSONArray("category");
JSONArray JArray_dis = jObj.getJSONArray("description");
JSONArray JArray_exp = jObj.getJSONArray("expenditure");
for (int i = 0; i < JArray_date.length(); i++) {
HistoryDto dto = new HistoryDto();
dto.date = JArray_date.getString(i);
dto.category = JArray_cat.getString(i);
dto.descri = JArray_dis.getString(i);
dto.expe = (float) JArray_exp.getDouble(i);

hisList.add(dto);
}

} catch (JSONException e) {
e.printStackTrace();
}
return hisList;
}



This is how we got the result to the ArrayList and populate in the android Activities.

Wednesday, February 8, 2012

Date Picker & Time Picker Dialog and set it into the String Format


First of all make an simple interface to open the Dialog and make that dialog open on the button click. For that you have to take two text view for storing the date and time and two button for opening the date and time dialog.


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView 
android:id="@+id/textview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textSize="30dp"
/>
    <Button 
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Date"
     />
      <TextView  
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/textview2"
    android:text=""
    android:textSize="30dp"
    />
     <Button 
     android:id="@+id/button2"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:text="time"
     />
</LinearLayout>




Now make a java file with the DatePickerDemo and put the following code into it.



import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.TimePicker;


public class DatePickerDemo extends Activity {



private static final int DATE_DIALOG_ID=1; // for date 
private static final  int TIME_DIALOG_ID=2; // for month 
private int d,mo,y,h,m; // for date & month variables 
Button b1,b2; // button objects 
TextView e1,e2;  // textview objects

// execution starts from here 
@Override
public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.datepicker);  // calling main.xml 
   e1=(TextView)findViewById(R.id.textview1); // getting textview1 id from main.xml 
     b1=(Button)findViewById(R.id.button1); // getting  button id from main.xml
         
b1.setOnClickListener(new OnClickListener() // setting listener for button one  
        
{

@Override
public void onClick(View arg0) {


// TODO Auto-generated method stub
showDialog(DATE_DIALOG_ID);   // generating dialog box 
}
});
        
final Calendar cal=Calendar.getInstance(); // allocating memory for calendar instance
d=cal.get(Calendar.DAY_OF_MONTH); // present date        
mo=cal.get(Calendar.MONTH); // present month
    y=cal.get(Calendar.YEAR); // present year
    updateDate();  // update date 
        
b2=(Button)findViewById(R.id.button2); // getting listener for button2 
   e2=(TextView)findViewById(R.id.textview2); 
   b2.setOnClickListener(new OnClickListener() // setting listener for button2 
        
{
@Override
public void onClick(View arg0) {


// TODO Auto-generated method stub
showDialog(TIME_DIALOG_ID);
}
});
        
h=cal.get(Calendar.HOUR); // getting  present hour & minute
m=cal.get(Calendar.MINUTE);
updateTime();  // updating time 
}


public void updateTime()
{
 
e2.setText(new StringBuilder().append(h).append('-').append(m));
 
}
public void updateDate()
{
 
e1.setText(new StringBuilder().append(d).append('-').append(mo+1).append('-').append(y));
 
}


private DatePickerDialog.OnDateSetListener datelistener=new DatePickerDialog.OnDateSetListener() 
{


@Override
public void onDateSet(DatePicker view,int year, int monthofyear, int day) 
{

                     y=year;
mo=monthofyear;
                  d=day;
updateDate();
}
};
 
private TimePickerDialog.OnTimeSetListener timelistener=new TimePickerDialog.OnTimeSetListener() 
{
@Override
public void onTimeSet(TimePicker view, int hourofday, int minute) 
{
// TODO Auto-generated method stub
h=hourofday;
m=minute;
updateTime();
}
};

protected Dialog onCreateDialog(int id) 
{
switch(id)
{
case DATE_DIALOG_ID:
return new DatePickerDialog(this,datelistener , y, mo, d);


case TIME_DIALOG_ID:
return new TimePickerDialog(this,timelistener,h,m,false);
}
return null;
}
}


This will show you how to pick the date from date picker android widget and time from TimePicker widget and convert Those date and Time into String format and  set it to the TextView.