Wednesday, December 25, 2013

XML DOM Parsing in Android.

      The Document Object Model (DOM) is an API for valid HTML and well-formed XML documents. It defines the logical structure of documents and the way of documents accessed and manipulated. It is a hierarchy-based parser that creates the object model for an entire model. It is highly recommended  for the small sized files or data because it store the data in memory. It is faster than the SAX parser.

XML Data Format:

  XML was created to structure, store and transport data. It will be easily readable by the humans as well machines. Follow the sample XML format. I am saving this data named studentDetails.xml in  res/raw folder.

<?xml version="1.0" encoding="UTF-8"?>
<students>
 <student>
  <no>1</no>
  <name>Tendulkar</name>
  <class>Computers</class>
  </student>

 <student>

  <no>2</no>
  <name>Ganguly</name>
  <class>EEE</class>
 </student>

 <student>

  <no>3</no>
  <name>Dravid</name>
  <class>CSE</class>
 </student>

 <student>

  <no>4</no>
  <name>Laxman</name>
  <class>CSIT</class>
  </student>

 <student>

  <no>5</no>
  <name>Kumble</name>
  <class>MCA</class>
  </student>

</students>



XML layout:
Create a xml layout to display the DOM results.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/NOtext"
    />
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/Nametext"
    />
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/Classtext"
    />
</RelativeLayout>

DomParserActivity:


package com.prakash_domparserdemo;

import java.io.InputStream;


import javax.xml.parsers.DocumentBuilder;

import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.app.Activity;

import android.os.Bundle;
import android.widget.TextView;

public class DomParserActivity extends Activity {

TextView notxt,nametxt,classtxt;  
 
@Override  
public void onCreate(Bundle savedInstanceState) {  
super.onCreate(savedInstanceState);  
setContentView(R.layout.domparser);  
notxt=(TextView)findViewById(R.id.NOtext); 
nametxt=(TextView)findViewById(R.id.Nametext); 
classtxt=(TextView)findViewById(R.id.Classtext); 
try {  
InputStream is = getAssets().open("details.xml");  
 
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();  
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();  
Document doc = dBuilder.parse(is);  
 
Element element=doc.getDocumentElement();  
element.normalize();  
 
NodeList nList = doc.getElementsByTagName("student");  
for (int i=0; i<nList.getLength(); i++) {  
 
Node node = nList.item(i);  
if (node.getNodeType() == Node.ELEMENT_NODE) {  
Element element2 = (Element) node;  
notxt.setText(notxt.getText()+"\nNo : " + getValue("no", element2)+"\n");  
nametxt.setText(nametxt.getText()+"Name : " + getValue("name", element2)+"\n");  
classtxt.setText(classtxt.getText()+"Class : " + getValue("class", element2)+"\n");
 
}  
}
    
} catch (Exception e) {e.printStackTrace();}  
 
}  
private static String getValue(String tag, Element element) {  
NodeList nodeList = element.getElementsByTagName(tag).item(0).getChildNodes();  
Node node = (Node) nodeList.item(0);  
return node.getNodeValue();  
}  
 
}  


Result screen:


Enjoy Coding!!!!



Read More »

Thursday, November 14, 2013

HTTP Requests to Rest-WCF/Web API service from C# MVC Apllication

      This tutorial explains you about the how to make HTTP requests to Rest-WCF/Web API service from C# MVC Client Application. HTTP is designed to enable communication between client and server. It works as a request-response between client and server. HTTP request methods are GET, HEAD, POST, PUT, DELETE, OPTIONS, TRACE and CONNECT. We use most commonly  POST, GET, PUT and DELETE methods. These methods correspond  to create, read, update and delete (CRUD) operations.

HTTP Post Method:
The HTTP POST is most-often utilized for creation of new resources. It simply submits data into specified resource.
I have created UserDetails model.

public class UserDetails
    {

        public int UserId { get; set; }
        public string FirstName { get; set; }
       public string LastName { get; set; }
       public string Email{ get; set; }
       public string Password{ get; set; }
       public string Phone{ get; set; }
    }



CODE:

//POST
public ActionResult SignUp()
        {
           UserDetails model = new UserDetails();
           WebClient clientpost = new WebClient();
            clientpost.Headers["Content-type"] = "application/json";
            MemoryStream streampost = new MemoryStream();
         
            model .UserId = 0;
            model .FirstName = "Teja";
            model .LastName = "Prakash";
            model .Email= "info@tejaprakash.com";
            model .Password= "password";
            model.Phone="xxx-xxx-xxxx"      

            DataContractJsonSerializer serializerpost = new                                                                                             DataContractJsonSerializer(typeof(UserDetails ));
         
            serializerpost.WriteObject(streampost, model);

            byte[] datapost = clientpost.UploadData("http://localhost:60273/PrakashSampleService.svc/Signup",              "POST", streampost.ToArray());

            streampost = new MemoryStream(datapost);
            serializerpost = new DataContractJsonSerializer(typeof(string));
            string result = (string)serializerpost.ReadObject(streampost);

            return View();
        }



HTTP Get Method:
The HTTP GET method is used to retrieve (or read) a representation of a resource. HTTP response codes- 200(OK), 404(NOT FOUND), 400(BAD REQUEST).

CODE:
   //GET
public ActionResult GetUserDetails(int userid)
        {

           UserDetails model = new UserDetails();

            string formatted_uri = string.Format("http://localhost:60273/PrakashSampleService.svc/{0}", userid);

            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(formatted_uri);
            HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();

            string json_response = string.Empty;
            using (StreamReader sr = new StreamReader(response.GetResponseStream()))
            {
                json_response = sr.ReadToEnd();
            }

            JavaScriptSerializer serializer = new JavaScriptSerializer();
            model  = serializer.Deserialize<model >(json_response);


            return View(model);

        }

HTTP PUT Method:
HTTP PUT is most-often utilized for update capabilities, PUT-ing to a known resource URI with the request body containing the newly-updated representation of the original resource.

CODE:
//PUT
public ActionResult UpdateProfile()
        {
           UserDetails model = new UserDetails();
       
            WebClient clientpost = new WebClient();
            clientpost.Headers["Content-type"] = "application/json";
            MemoryStream streampost = new MemoryStream();
       
            model .UserId = 1;
            model .FirstName = "Teja";
            model .LastName = "Prakash rao";
            model .Email= "info@tejaprakash.com";
            model .Password= "password";
            model.Phone="xxx-xxx-xxxx"  

            DataContractJsonSerializer serializerpost = new                                                                                            DataContractJsonSerializer(typeof(UserDetails ));

            serializerpost.WriteObject(streampost, model);

            byte[] datapost = clientpost.UploadData("http://localhost:60273/PrakashSampleService.svc/UpdateProfile",  "PUT",streampost.ToArray());

            streampost = new MemoryStream(datapost);
            serializerpost = new DataContractJsonSerializer(typeof(string));
            string result = (string)serializerpost.ReadObject(streampost);

            return View();
        }

HTTP Delete Method:
HTTP DELETE is pretty easy to understand. It is used to delete a resource identified by a URI.

CODE:
//DELETE
public ActionResult DeleteUser(int userid)
        {
         
            WebClient clientpost = new WebClient();
            clientpost.Headers["Content-type"] = "application/json";
            MemoryStream streampost = new MemoryStream();
     
            DataContractJsonSerializer serializerpost = new  DataContractJsonSerializer(typeof(String));
            serializerpost.WriteObject(streampost, userid);

            byte[] datapost = clientpost.UploadData("http://localhost:60273/PrakashSampleService.svc/DeleteUser", "DELETE", streampost.ToArray());

            streampost = new MemoryStream(datapost);
            serializerpost = new DataContractJsonSerializer(typeof(string));
            string result = (string)serializerpost.ReadObject(streampost);

            return View();


        }


This process works fine for both REST WCF and WEB API services.
Enjoy.....!!!!!
Read More »

Sunday, October 13, 2013

WCF Restful Service example.

      This tutorial explains you about a Restful WCF service. Windows Communication Foundation (WCF) is a tool usually used to implement and deploy a service-oriented architecture (SOA).Clients can consume multiple services; services can be consumed by multiple clients. Services are loosely coupled to each other.
WCF implements many advanced Web services (WS) standards such as WS-Addressing, WS-ReliableMessaging and WS-Security. With the release of .NET Framework 4.0, WCF also provides RSS Syndication Services, WS-Discovery, routing and better support for REST services.

ENDPOINTS:

A WCF service communicates with the world through end point only. Endpoints remember like 'ABC'.
A- Address
B-Binding
C-Contract

Address (WHERE): It specifies about the service location. Clients will use the URL to communicate with the service.
Address format of WCF transport schema look like below
[transport]://[machine or domain][:optional port]

WCF supports transport schemas like HTTP, TCP, IPC, MSMQ and Peer Network.
Examples:
HTTP address format: http://localhost/5124/service
TCP address format: net.tcp://localhost/5124/service
IPC address format: net.pipe://localhost/5124/pipe
MSMQ address format: net.msmq://localhost/5124/service


Binding (HOW): It specifies about communication type i.e. how client  can connect with the service or using which protocols finds the services (SOAP, HTTP, TCP, MSMQ etc.).
WCF supports 9 types of Bindings:
1. BasicHttpBinding: Basic Web service communication. This is designed to expose a WCF service as a legacy ASMX web service, so that old clients can work with new services. When used by the client, this binding enables new WCF clients to work with old ASMX services. No security by default.
2. WsHttpBinding: It  uses HTTP or HTTPS for transport, and is designed to offer a variety of features such as reliability, transactions, and security over the Internet.
3. WsDualHttpBinding: It is similar to the Ws Binding except it also support the duplex contract.
4. WsFederationHttpBinding: It supports federated security and transaction.
5. MsmqIntegrationBinding: It communicates directly with MSMQ application. It supports transaction.
6. NetMsmqBinding: This uses MSMQ for transport and is designed to offer support for disconnected queued calls. It supports transaction.
7. NetNamedPipeBinding/IPC binding: This uses named pipes as a transport for same-machine communication. This binding won't accept the outside calls. It supports duplex contract and transactions.
 8. NetPeerTCPBinding: This uses peer networking as a transport. The peer network-enabled client and services all subscribe to the same grid and broadcast messages to it. It supports duplex contracts.
9. NetTcpBinding/Tcp Binding: Communication between WCF Service across computers. It supports duplex contracts, reliability and transaction.

Contract (WHAT): It specifies the interface between client and server. It identifies what is exposed by the service.
WCF defines 4 types of contracts

Service Contract: It describes which operations the client can perform on the service. There are 2 types of Service Contracts are:
1. ServiceContract: This attribute is used to define the interface.
2. OperationContract: This attribute is used to define the method inside the interface.

DataContracts: It defines the data types, that are passed from and to the service. WCF defines implicit contracts for built-in types such as int and string, but we can easily define explicit opt-in data contracts for custom types. There are 2 types of Data Contracts are
1. DataContract: This attribute is used to define the class.
2. DataMember: This attribute is used to define the properties.

Message Contract: It allows the service to interact directly with messages. Message contracts can be typed or untyped, and are useful in interoperability cases and when there is an existing message format we have to comply with.

Fault Contracts: It define which errors are raised by the service, and how the service handles and propagates errors to its clients. It is easy to find, what errors has occurred.

Here, I have given info about Endpoints because it is very important for any WCF application.

How to create Basic WCF Service Application using VS 10/12:

1. Click on New Project. Then select WCF Service Application under WCF.



2. You will get solution like below


By default, you will get 'Hello' method with BasicHttpBinding. Now, you have to do your own work here.
The actual code starts from here. First, design your model by creating new class. We are using Data Contracts concept here. Have a look at below code.

 [DataContract]
    public class UserModel
    {
        [DataMember]
        public int UserId { get; set; }
        [DataMember]
        public string FirstName { get; set; }
        [DataMember]
        public string LastName { get; set; }
        [DataMember]
        public string Email { get; set; }
        [DataMember]
        public string Password { get; set; }
        [DataMember]
        public int Phone { get; set; }

    }

Then create a interface for the service i.e. give the operations which is operated by clients. Here, we are using Service Contract concept. It supports POST, GET, DELETE and PUT modes.  Follow the below code.

[ServiceContract]
    public interface IPrakashSampleService
    {

        [OperationContract]
        [WebInvoke(Method = "POST", UriTemplate = "/SignUp",
        RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        bool SignUp(UserModel user);

        [OperationContract]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle =                         WebMessageBodyStyle.WrappedRequest, UriTemplate = "GetUserDetails/{UserId}")]      
        UserModel GetUserDetails(string UserId);


        [OperationContract]
        [WebInvoke(Method = "DELETE", ResponseFormat = WebMessageFormat.Json, BodyStyle =                 WebMessageBodyStyle.WrappedRequest, UriTemplate = "DeleteUser/{UserId}")]      
        UserModel DeleteUser(string UserId);

        [OperationContract]
        [WebInvoke(Method = "PUT", UriTemplate = "/UpdateUser",
         RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        bool UpdateUser(UserModel user);

    }


Now, do some required changes in WEB.CONFIG file for REST.
Create a connection string to your DataBase.

<connectionStrings>
   
    <add name="SampleServices" connectionString="data source=TEJA-PC;Initial Catalog=DBNAME;User ID=USERNAME;Password=PASSWORD;" providerName="System.Data.SqlClient" />
 
  </connectionStrings>

  Then change the binding to webHttpBinding and declaring address, binding and contract. Follow the below code.

<system.serviceModel>
    <services>
      <service name="Prakash_RestWcfSample.PrakashSampleService" behaviorConfiguration="ServiceBehaviour">

        <endpoint address=""  binding="webHttpBinding" contract="Prakash_RestWcfSample.IPrakashSampleService" behaviorConfiguration="web">

        </endpoint>
      </service>
    </services>
    <bindings>
      <webHttpBinding>
        <binding name="webHttpBinding" crossDomainScriptAccessEnabled="true" />
      </webHttpBinding>
    </bindings>
    <behaviors>
      <endpointBehaviors>
        <behavior name="web">
          <webHttp automaticFormatSelectionEnabled="false" helpEnabled="true" />
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
         <behavior name="ServiceBehaviour">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
         </behavior>
        <behavior name="">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>

    <serviceHostingEnvironment multipleSiteBindingsEnabled="true"  aspNetCompatibilityEnabled="true"/>
  </system.serviceModel>

Now, time to write service methods in PrakashSampleService.svc. I have used SQL Server STORED_PROCEDURES here. But, we can use LINQ queries also.

First, declare a connection string.
   
 string strcon = ConfigurationManager.ConnectionStrings["SampleServices"].ToString();
        SqlConnection con = null;
        SqlCommand cmd = null;
        SqlDataAdapter da = null;
        DataSet ds = null;

// POST METHOD

 public bool SignUp(UserModel userInfo)
        {

                using (con = new SqlConnection(strcon))
                {
                    cmd = new SqlCommand() { Connection = con, CommandText =                                     "Proc_SaveUserDetails", CommandType = CommandType.StoredProcedure };             

                    if (con.State == ConnectionState.Closed)
                    {
                        con.Open();
                        cmd.Parameters.AddWithValue("@UserID", userInfo.UserId);
                   
                        cmd.Parameters.AddWithValue("@FName", userInfo.FirstName);
                        cmd.Parameters.AddWithValue("@LName", userInfo.LastName);
                        cmd.Parameters.AddWithValue("@Email", userInfo.Email);
                        cmd.Parameters.AddWithValue("@Password", userInfo.Password);
                        cmd.Parameters.AddWithValue("@Phone", userInfo.Phone);

                        cmd.Parameters.Add("@Message", SqlDbType.VarChar, 50).Direction =                                                    ParameterDirection.Output;  
              
                        cmd.ExecuteNonQuery();
                       
                        string message = cmd.Parameters["@Message"].Value.ToString();
                        if (message == "Sucess")
                        {
                           
                            //do something here.

                        }
                        else
                        {
                            //do something here.
                        }
                    }
                    con.Close();

                }
                return true;
         
        }

//GET Method

 public UserModel GetUserDetails(string userid)
        {
            UserModel getuserdetails = new UserModel();
           
            using (con = new SqlConnection(strcon))
            {
                if (con.State == ConnectionState.Closed)
                {
                    con.Open();
                    cmd = new SqlCommand() { Connection = con, CommandText = "Proc_GetUserDetails",  CommandType = CommandType.StoredProcedure };                          
                    cmd.Parameters.AddWithValue("@UserID", userid);
                    SqlDataReader reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {

                        getuserdetails.UserId = (int)reader["UserId"];
                        getuserdetails.FirstName = reader["FirstName"].ToString();
                        getuserdetails.LastName = reader["LastName"].ToString();
                        getuserdetails.Email = reader["Email"].ToString();
                        getuserdetails.Phone = (int)reader["Phone"];

                    }

                }
            }
            return getuserdetails;
        }



For help : your_service_url/help.You will find the all methods like below screen.
Ex: http://localhost:60273/PrakashSampleService.svc/help


The sample output in Json format:
Enjoy........!!
Read More »

Monday, September 9, 2013

Admob Ads SDK Integration in Android.

     This tutorial explains you that how to add Google mobile ads to your application. AdMob provides you text, image banners and full screen ads. The following steps are required to get ads..
1. First, you should have a Google account. If have already, then  login to AdMob site.
2. Add new app in AdMob site and get the Publisher ID.
3. Add AdMob SDK to your Android Apllication.
4. Some code required.

How to get your Publisher ID from AdMob Site?

First, you should have a Google account to add new app in AdMob site.
After logging, click on Sites & Apps and then select Add Site/App. Refer below pic.

Then select your platform and fill the fields to complete the registration.

                                                                                                       
                                               
Then Note down your Publisher ID from Manage settings.

Copy your Publisher ID and paste it in your code.


Add AdMob SDK to your Application.

First, check your AdMob SDK library installation in Android SDK Manager. If not installed then install it.


Open application properties. In JAVA Path, click Add External JAR. Get your AdMob JAR file from your Android SDK like D:\android-sdks\extras\google\admob_ads_sdk


After adding JAR file. Select Order and export and check the GoogleAdsAdmobSDK JAR. Click OK to finish.

Now, AdMob SDK added to your application.

Code:

 Android Manifest file:

Add Internet and Access Network permissions in manifest file.

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

Declare com.google.ads.AdActivity.

<activity 

android:name="com.google.ads.AdActivity"
                 android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" >
        
</activity>

Banner Ads:

Banner Ads used to display in small portion of screen. It available in different sizes for  different devices. See table for available sizes.

Create your Banner in XML:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

  <com.google.ads.AdView
     android:id="@+id/adView"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:layout_alignParentBottom="true"
     ads:adSize="SMART_BANNER"
     ads:adUnitId="MY_Publisher_ID"
     ads:loadAdOnCreate="true"
     ads:testDevices="TEST_EMULATOR, TEST_DEVICE_ID" >
  </com.google.ads.AdView>
    
</RelativeLayout>

Either you can do it in Activity also.

MainAcitivity code:

public class MainActivity extends Activity {

private AdView adView;
String MY_AD_UNIT_ID = "a152xxxxx3bcb3";

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

adView = new AdView(this, AdSize.SMART_BANNER, MY_AD_UNIT_ID);
 adView = (AdView)this.findViewById(R.id.adView);
adView.loadAd(new AdRequest());
           
}
}

The banner output looks like below screen.

 Interstitials Ads:

Interstitials ads will displays in full screen. But banners will takes a small portion of screen. Interstials ads are richer and heavy weight. It mostly used in loading pages.

Code:

public class InterstitialAdsActivity extends Activity implements AdListener{


String MY_AD_UNIT_ID = "a152xxxxxxbcb3";
private InterstitialAd interstitial;

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

// Create the interstitial
   interstitial = new InterstitialAd(this, MY_AD_UNIT_ID);

   // Create ad request
   AdRequest adRequest = new AdRequest();

   // Begin loading your interstitial
   interstitial.loadAd(adRequest);

   // Set Ad Listener to use the callbacks below
   interstitial.setAdListener(this);
  }

/** Called when an ad is received. */
   @Override
public void onReceiveAd(Ad ad) {
   Log.d("OK", "Received ad");
   if (ad == interstitial) {
     interstitial.show();
   }
 }

 /** Called when an ad is clicked and about to return to the application. */
@Override
public void onDismissScreen(Ad arg0) {
// TODO Auto-generated method stub
Toast.makeText(this, "onDismissScreen", Toast.LENGTH_SHORT).show();
}

/** Called when an ad was not received. */
@Override
public void onFailedToReceiveAd(Ad ad, ErrorCode arg1) {

   // Change the button text and disable the button.
   if (ad == interstitial) {
    
      Toast.makeText(this, "Failed to Receive Ad", Toast.LENGTH_SHORT).show();
   }
}

/**
   * Called when an ad is clicked and going to start a new Activity that will
   * leave the application (e.g. breaking out to the Browser or Maps
   * application).

   */
@Override
public void onLeaveApplication(Ad arg0) {
// TODO Auto-generated method stub
 if (ad == interstitial) {
     
       Toast.makeText(this, "Application ended", Toast.LENGTH_SHORT).show();
    }
}

/**
   * Called when an Activity is created in front of the app (e.g. an
   * interstitial is shown, or an ad is clicked and launches a new Activity).

   */
@Override
public void onPresentScreen(Ad arg0) {
// TODO Auto-generated method stub
 if (ad == interstitial) {
     
                Toast.makeText(this, "Present Screen", Toast.LENGTH_SHORT).show();
    }
}
}  

The output looks likes below screen...

Note: Download samples from developers.google.

Frequent errors:

1.If you get Runtime Exception error, then check your JAR file version  or  make sure that your manifest file contains all the required details are correct.
2. Uncaught ReferenceError: AFMA_getSdkConstants is not defined : Ice Cream Sandwich won't allow network operations in Main thread. Load it in separate thread.

                adView = new AdView(this, AdSize.SMART_BANNER, MY_AD_UNIT_ID);
adView = (AdView)this.findViewById(R.id.adView);

(new Thread() {
                public void run() {
            Looper.prepare();
   
  adView.loadAd(new AdRequest());
               }
               }).start();

Otherwise, check your network or internet connection once.

Enjoy with your ads............
Read More »

Sunday, September 8, 2013

Barcode Scanning in Android.

Let's see about the Barcode Scanning in android. There are so many SDK's present today for Scanning barcode like Zxing, Red-scanner and Zbar. Both Zxing and Zbar are open sources. We can integrate it easily. Zbar is more fast and simple than Zxing. I inspired with the Zbar scanner.

Here, we have a wonderful tutorial about the Zbar SDK  integration in Android. Follow the link.
https://github.com/DushyanthMaguluru/ZBarScanner

And for Zxing, https://code.google.com/p/zxing/.





Read More »

Saturday, August 31, 2013

Get public tweets from twitter API in Android.

      Twitter provides you public tweets and simple authentication now. Twitter uses Client Credentials Grant flow of OAuth 2.0 specifications for their latest version.
First, you should get your Consumer key and Consumer secret from Twitter Developer site. This both works as sensitive passwords for your application.

Flow:
1. Encode the both consumer key and consumer secret into set of credentials.
2. Make an request to POST oauth2/token. On successful, you will receive bearer token.
3. Attach screen name (twitterID) with your access token and get the data.

Encode Keys:

// URL encoding of consumer key.
String encodedConsumerKey = URLEncoder.encode("Your Consumer KEY here","UTF-8");

// URL encoding of consumer secret.    
String encodedConsumerSecret = URLEncoder.encode("Your Consumer Secret here","UTF-8");

//Concatenate the both strings with colon ':'.     
String authString = encodedConsumerKey +":"+encodedConsumerSecret;

//using base64 encode.    
String base64Encoded = Base64.encodeToString(authString.getBytes("UTF-8"), Base64.NO_WRAP);

Authentication: Get a Bearer Token

Request format for bearer token:

POST /oauth2/token HTTP/1.1
Host: api.twitter.com
User-Agent: My Twitter App v1.0.23
Authorization: Basic " place here base64encoded string"
Content-Type: application/x-www-form-urlencoded;charset=UTF-8
Content-Length: 29
Accept-Encoding: gzip

grant_type=client_credentials

Request Response:

HTTP/1.1 200 OK
Status: 200 OK
Content-Type: application/json; charset=utf-8
...
Content-Encoding: gzip
Content-Length: 140

{"token_type":"bearer","access_token":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA%2FZZZZZZZZZZZZZZZZ%3DAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}

The request must be in HTTP post and Authorization header contains value of  "Basic Base64 encoder string". There will be space between the Basic and base64 encoder string.
The Content -Type contains value like "application/x-www-form-urlencoded;charset=UTF-8" and grant_type should have value like "client_credentials".

Follow the below code to get the bearer token

//Use Http post to send request.
HttpClient httpclient = new DefaultHttpClient();
//Append twitter api url here.
String uriString = "https://api.twitter.com/oauth2/token";
HttpPost httppost = new HttpPost(uriString);
HttpParams httpParams = httppost.getParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
HttpConnectionParams.setSoTimeout(httpParams, 15000);
//Append EncodedString to Authorization Header.
httppost.setHeader("Authorization", "Basic " +base64EncodedString);
//Set Content type here.
httppost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
HttpResponse response =null;

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();        
nameValuePairs.add(new BasicNameValuePair("grant_type", "client_credentials"));        
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));        
response = httpclient.execute(httppost);      
String returnedJsonStr = EntityUtils.toString(response.getEntity());

 int statusCode = response.getStatusLine().getStatusCode();
Log.v("response",returnedJsonStr);
Log.v("response",Integer.toString(statusCode));
JSONObject jsonObject = new JSONObject(returnedJsonStr);
//Receive Bearer token here.
 receivedToken = jsonObject.getString("access_token");
Log.v("access_token",receivedToken);

On valid process, you will receive Access token here.

Get API requests with the bearer token:

Request Format:

GET /1.1/statuses/user_timeline.json?count=100&screen_name=twitterapi HTTP/1.1
Host: api.twitter.com
User-Agent: My Twitter App v1.0.23
Authorization: Bearer AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA%2FAAAAAAAAAAAA
                      AAAAAAAA%3DAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
Accept-Encoding: gzip

The bearer token may be used to issue requests to API endpoints which support application-only auth.
The request includes the normal Https and Authorization header value contains like "Bearer space bearer-token" . Without twitter signing you can get the data.

Follow the below code for API requests:

HttpClient httpclient = new DefaultHttpClient();
//Append twitter count and screen name with api URL 
HttpGet httpget = new HttpGet("https://api.twitter.com//1.1/statuses/user_timeline.json?count=100&screen_name="+twitter_id); 
//Append bearer token here.
httpget.setHeader("Authorization", "Bearer "+ receivedToken);
HttpResponse response;
try 
     {
               //Receive response here and make it .
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null)
{
       InputStream instream = entity.getContent();
       twitter_response= convertStreamToString(instream);
       instream.close();
       weets_array = new JSONArray(twitter_response);
       for (int i = 0; i < tweets_array.length(); i++)
           {
            String texts = tweets_array.getJSONObject(i).getString("text");
            HashMap<String, String> map = new HashMap<String, String>();
            map.put(KEY_TWITTES, texts);
            twittwrfeedsarray.add(map);
            JSONObject c = tweets_array.getJSONObject(0);
            JSONObject phone = c.getJSONObject("user");
            user_profile_pic_url = phone.getString("profile_image_url_https");
           }
  }
}
catch(Exception e)
{
}

Output ScreenShot:

Enjoy coding......




Read More »