Pages

Showing posts with label calling. Show all posts
Showing posts with label calling. Show all posts

Monday, April 11, 2016

Calling REST Web Services with Android

Requesting REST web service:   you request REST web services by calling a URL with the parameters. like this
http://example.com/resources/getitems

an example of calling a REST web service:
String callWebErvice(String serviceURL){
// http get client
HttpClient client=new DefaultHttpClient();
HttpGet getRequest=new HttpGet();

try {
// construct a URI object
getRequest.setURI(new URI(serviceURL));
} catch (URISyntaxException e) {
Log.e("URISyntaxException", e.toString());
}

// buffer reader to read the response
BufferedReader in=null;
// the service response
HttpResponse response=null;
try {
// execute the request
response = client.execute(getRequest);
} catch (ClientProtocolException e) {
Log.e("ClientProtocolException", e.toString());
} catch (IOException e) {
Log.e("IO exception", e.toString());
}
try {
in=new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
} catch (IllegalStateException e) {
Log.e("IllegalStateException", e.toString());
} catch (IOException e) {
Log.e("IO exception", e.toString());
}
StringBuffer buff=new StringBuffer("");
String line="";
try {
while((line=in.readLine())!=null)
{
buff.append(line);
}
} catch (IOException e) {
Log.e("IO exception", e.toString());
return e.getMessage();
}


try {
in.close();
} catch (IOException e) {
Log.e("IO exception", e.toString());
}
// response, need to be parsed
return buff.toString();
}
Read More..

Monday, April 4, 2016

Fetching Result from a called activity Android Tutorial for Beginners – Part 5


The next logical step in learning the Android development is to look at how can you call or invoke one activity from another and get back data from the called activity back to the calling activity. For simplicity sake, let us name the first calling activity as parent activity and the invoked activity as the child activity.


For simplicity sake, I use an explicit intent for invoking the child activity. For simple invocation without expecting any data back, we use the method startActivity(). However, when we want a result to be returned by the child activity, we need to call it by the method startActivityForResult(). When the child activity finishes with the job, it should set the data in an intent and call the method setResult(resultcode, intent)to return the data through the intent.


The parent activity should have overridden the method onActivityResult(…)in order to be able to get the data and act upon it.


NOTE: for successful execution of this sequence of events, the child activity should call finish() after setResult(..)in order to give back the handle to the parent activity.


In summary, here are the methods to implement in the parent activity:
  • 1.  startActivtyForResult(..)
  • 2.  onActivityResult(…)

The child Activity should complete the work as usual and finally call:
  • 1.  setResult(…)
  • 2.  finish()

Let us delve into the example downloadable here:


The calling Activity is providing 2 buttons to view books and pens. On selecting one of them, either BooksActivityor PensActivityis called, which displays a list (using ListView) of the selected type of objects. The user can select one and the selected object is returned to the parent for display. (Note: this could be extended into a shopping cart example. I have kept it simple for the tutorial’s sake)


Since we are expecting to get back the selected object, the calling Activity’s code is like this:
     Intent bookIntent = new Intent();                bookIntent.setClass(CallingActivity.this,BooksActivity.class);
      startActivityForResult(bookIntent,BOOK_SELECT);
where BOOK_SELECT is just a constant to help us identify from which child activity the is result obtained, when there is more than 1 child activity, as in this case.


At this point the control is handed over to the BooksActivity. This displays the list of books and the user can scroll through and select a book. When the user selects a book, the selected book needs to be passed back to the CallingActivity. This is how it is done:
      Object o = this.getListAdapter().getItem(position);
      String book = o.toString();
      Intent returnIntent = new Intent();
      returnIntent.putExtra("SelectedBook",book);
      setResult(RESULT_OK,returnIntent);       
      finish();


The first 2 lines show how to get the selected book from the ListView. Then, you create a new intent object, set the selected book as an extra and pass it back through the setResult(…)method call. The result code is set to RESULT_OKsince the job has been successfully done.  After that the finish()method is called to give the control back to the parent activity.


In the parent, the method that gets the control is onActivityResult(…)
protected voidonActivityResult(int requestCode, int resultCode, Intent data)
      {
      switch(requestCode) {
      case BOOK_SELECT:
            if (resultCode == RESULT_OK) {
                String name = data.getStringExtra("SelectedBook");
                Toast.makeText(this, "You have chosen the book: " + " " + name, Toast.LENGTH_LONG).show();
                break;
            }
      ……….
      }
      }  


Here you notice that the BOOK_SELECTconstant is used to act upon the result. If the result code is RESULT_OK, we take the book selected from the “extra” of the intent that is returned from the child activity. data.getStringExtra("SelectedBook") is called to and the name returned is displayed through a Toast. 
Read More..

Wednesday, March 16, 2016

Calling SOAP Web Services with Android APIs

One of the most common functionalities required in mobile applications is to call a web service to retrieve data. This process involves requesting the web service with parameters, receiving the response and parsing it to obtain data.
Today the most common web services types are SOAP and REST. Android does not provide a built in SOAP client, there are many third party libraries that can be used, but well see how to call a SOAP web service with native android APIs.

Requesting SOAP web service:
Before proceeding to the code, lets take a look at the SOAP structure:


a soap request can be something like this:

POST /InStock HTTP/1.1
Host: www.example.org
Content-Type: application/soap+xml; charset=utf-8
Content-Length: length
SOAPAction: "http://www.w3schools.com/GetItems"

<?xml version="1.0"?>
<soap:Envelope

soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">
<soap:Header>
<m:Trans
soap_mustUnderstand="1">234
</m:Trans>
</soap:Header>
<soap:Body>
<m:GetPrice >
<m:Item>Apples</m:Item>
</m:GetPrice>
</soap:Body></soap:Envelope>


the SOAP request/response is sent as a SOAP Envelope which consists of a SOAP Header and a SOAP Body.

  1. SOAP Header: optional component of the envelop, contains application specific information, such as authentication.
  2. SOAP Body: the actual message sent to/received from the service.
  3. The header can contain a SOAP Action which identifies the desired function to be called by the service.
Calling the service:
to call the SOAP web service you have to do the following:
First: construct the SOAP envelope manually like this:
String envelope="<?xml version="1.0" encoding="utf-8"?>"+
"<soap:Envelope >"+
"<soap:Body>"+
"<GetItems >"+
"<startDate>%s</ startDate>"+
"<getAll>%s</getAll>"+
"</Items>"+
"</soap:Body>"+
"</soap:Envelope>";

where %s are place holders where you substitute request parameters in like this
String requestEnvelope=String.format(envelope, "10-5-2011","true");


Second: call the web service like this:
String CallWebService(String url,
String soapAction,
String envelope) {
final DefaultHttpClient httpClient=new DefaultHttpClient();
// request parameters
HttpParams params = httpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, 10000);
HttpConnectionParams.setSoTimeout(params, 15000);
// set parameter
HttpProtocolParams.setUseExpectContinue(httpClient.getParams(), true);

// POST the envelope
HttpPost httppost = new HttpPost(url);
// add headers
httppost.setHeader("soapaction", soapAction);
httppost.setHeader("Content-Type", "text/xml; charset=utf-8");

String responseString="";
try {

// the entity holds the request
HttpEntity entity = new StringEntity(envelope);
httppost.setEntity(entity);

// Response handler
ResponseHandler rh=new ResponseHandler() {
// invoked when client receives response
public String handleResponse(HttpResponse response)
throws ClientProtocolException, IOException {

// get response entity
HttpEntity entity = response.getEntity();

// read the response as byte array
StringBuffer out = new StringBuffer();
byte[] b = EntityUtils.toByteArray(entity);

// write the response byte array to a string buffer
out.append(new String(b, 0, b.length));
return out.toString();
}
};

responseString=httpClient.execute(httppost, rh);

}
catch (Exception e) {
Log.v("exception", e.toString());
}

// close the connection
httpClient.getConnectionManager().shutdown();
return responseString;
}

after calling this function, you will have the response as a String, something like this:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope >
<soap:Body>
<GetItemsResponse >
<GetItemsResult>

<Items>
<Item>
<name>string</name>
<description>string</ description >
</iPhoneCategory>
<iPhoneCategory>
<name>string</name>
<description>string</ description >
</ Item >
</Items>
</GetItemsResult>
</ GetItemsResponse >
</soap:Body>
</soap:Envelope>


this response needs to be parsed to extract the data.
Read More..

Sunday, February 21, 2016

Notifications Android Tutorial for Beginners Part 6


We have seen Activities and Intents. Now we need to move on to services. However, since services mostly interact with a user through notifications, I felt the need to introduce a simple program to deal with Notifications.


What are Notifications? The name itself implies their functionality. They are a way of alerting a user about an event that he needs to be informed about or even take some action on getting that information.


Notification on Android can be done in any of the following ways:
  • ·         Status Bar Notification
  • ·         Vibrate
  • ·         Flash lights
  • ·         Play a sound

From the Notification, you can allow the user to launch a new activity as well. Now we will look at status bar notification as this can be easily tested on the emulator.


To create a status bar notification, you will need to use two classes: Notification and NotificationManager.
  • ·         Notification – defines the properties of the status bar notification like the icon to display, the test to display when the notification first appears on the status bar and the time to display.
  • ·         NotificationManager is an android system service that executes and manages all notifications. Hence you cannot create an instance of the NotificationManagerbut you can retrieve a reference to it by calling the getSystemService()method.

Once you procure this handle, you invoke the notify()method on it by passing the notification object created.


So far, you have all the information to display on the status bar. However, when the user clicks the notification icon on the status bar, what detailed information should you show the user? This is yet to be created. This is done by calling the method setLatestEventInfo()on the notificationobject. What needs to be passed to this method, we will see with an example.


You can download the code for a very simple Notification example here:


The code is explained below:


Step 1: Procure a handle to the NotificationManager:


            privateNotificationManager mNotificationManager;
      …
mNotificationManager =
      (NotificationManager)getSystemService(NOTIFICATION_SERVICE);


Step 2: Create a notification object along with properties to display on the status bar


finalNotification notifyDetails =
new Notification(R.drawable.android,"New Alert, Click Me!",System.currentTimeMillis());



Step 3: Add the details that need to get displayed when the user clicks on the notification. In this case, I have created an intent to invoke the browser to show the website http://www.android.com


Context context = getApplicationContext();
     
CharSequence contentTitle = "Notification Details...";
     
CharSequence contentText = "Browse Android Official Site by clicking me";
Intent notifyIntent = new Intent(android.content.Intent.ACTION_VIEW,Uri.parse("http://www.android.com"));
     
PendingIntent intent =
      PendingIntent.getActivity(SimpleNotification.this, 0,
      notifyIntent, android.content.Intent.FLAG_ACTIVITY_NEW_TASK);
notifyDetails.setLatestEventInfo(context, contentTitle, contentText, intent);
Step 4: Now the stage is set. Notify.
       
      mNotificationManager.notify(SIMPLE_NOTFICATION_ID, notifyDetails);


Note that all of the above actions(except getting a handle to the NotificationManager) are done on the click of a button “Start Notification”. So all the details go into the setOnClickListener() method of the button.
Similarly, the notification, for the example sake is stopped by clicking a cancel notification button. And the code there is :
mNotificationManager.cancel(SIMPLE_NOTFICATION_ID);


Now, you may realize that the constant SIMPLE_NOTIFICATION_ID becomes the way of controlling, updating, stopping a current notification that is started with the same ID.


For more options like canceling the notification once the user clicks on the notification or to ensure that it does not get cleared on clicking the “Clear notifications” button, please see the android reference documentation. 
Read More..

Friday, March 14, 2014

Calling all Carriers Introducing AdSense for mobile search

In September 2007, we launched Adsense for mobile content so that publishers could join our mobile content network and monetize their sites with Google text ads.

Today, were happy to announce a new AdSense product for both mobile network operators and mobile website owners across the globe. AdSense for mobile search is a quick and easy way for carriers and mobile publishers to embed a Google search box on their mobile portals and web sites. Whether they are day-dreaming of Hawaii or trying to find the perfect Valentines day gift, mobile phone users will get instant access to Google search including comprehensive web search, local, image, and news results -- all formatted for their phones. Mobile operators and website owners share in the ad revenue generated by searches originating from their sites.

AdSense for mobile search is a Google-hosted solution, which means users will experience the same speed, reliability, and innovation that theyve come to expect from Google. And even though the results pages are served by Google, the pages can be cobranded with publishers logos and linked back to their sites. See the mock-up on the left.

If youre interested in beta-testing AdSense for mobile search, please fill out this form. And if you are coming to Barcelona next week for the Mobile World Congress, make sure to fill out the form by Friday, February 13. We are inviting a limited number of carriers and publishers for a private information session about AdSense for mobile search and would love to meet you. Note that filling out the form does not guarantee participation in the program.

Read More..