Search This Blog

Friday 17 February 2012

YQL open api

Many of the developers knows that the yql is well structured open api which can be used to retrieve the stock rates,photographs from flicker ,tweets of the person,statuses of the facebook etc. I dealt with this api and found it very beneficial for making the applications in various fields whether it is an app related to social networking entertainment and many if you want to use the yql you have to just query its database through the link and then it will return you the data either in the json(java script object notation) or in the xml format to view its console you can go here YQL console.
private static String convertStreamToString(InputStream is) {
        /*
         * To convert the InputStream to String we use the BufferedReader.readLine()
         * method. We iterate until the BufferedReader return null which means
         * there's no more data to read. Each line will appended to a StringBuilder
         * and returned as String.
         */
        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();
    }
 
    /* This is a test function which will connects to a given
     * rest service and prints it's response to Android Log with
     * labels "Praeda".
     */
    public void  connect(String url)
    {tv=(TextView)findViewById(R.id.TextView06);
tv1=(TextView)findViewById(R.id.TextView07);
tv2=(TextView)findViewById(R.id.TextView08);
tv3=(TextView)findViewById(R.id.TextView09);
tv4=(TextView)findViewById(R.id.TextView10);
   
        HttpClient httpclient = new DefaultHttpClient();
 
        // Prepare a request object
        HttpGet httpget = new HttpGet(url); 
 
        // Execute the request
        HttpResponse response;
        try {
            response = httpclient.execute(httpget);
            // Examine the response status
            Log.i("Praeda",response.getStatusLine().toString());
 
            // Get hold of the response entity
            HttpEntity entity = response.getEntity();
            // If the response does not enclose an entity, there is no need
            // to worry about connection release
            
            if (entity != null) {
 
                // A Simple JSON Response Read
                InputStream instream = entity.getContent();
                String result= convertStreamToString(instream);
                Log.i("Praedaresult",result);
 
                // A Simple JSONObject Creation
                JSONObject json=new JSONObject(result);
                Log.i("Praedaobject","<jsonobject>\n"+json.toString()+"\n</jsonobject>");
 
                // A Simple JSONObject Parsing
               // JSONArray nameArray=json.names();
                //Log.i("query",nameArray.toString());
                //JSONObject query=json.getJSONObject("query");
                //Log.i("query",query.toString());
                //JSONArray results=query.getJSONArray("results");
                //Log.i("rslts",results.toString());
               // JSONArray quote=results.getJSONArray("quote");
                //JSONObject quote=results.getJSONObject("quote");
                //Log.i("quote",quote.toString());
                JSONObject query=json.getJSONObject("query");
                Log.i("query",query.toString());
                JSONObject results=query.getJSONObject("results");
                Log.i("rslt",results.toString());
                JSONObject quote=results.getJSONObject("quote");
                Log.i("quote",quote.toString());
                for(int i=0;i<quote.length();i++)
                {
               
//                    Log.i("Praedafor","<jsonname"+i+">\n"+nameArray.getString(i)+"\n</jsonname"+i+">\n"
//                            +"<jsonvalue"+i+">\n"+valArray.getString(i)+"\n</jsonvalue"+i+">");
                //JSONObject quotes = results.getJSONObject(i)
                    //.getJSONObject("quote");
//                 Log,i
                //Log.i("name",quote.getString("Name"));
                //Log.i("name","pahunch");
                //Log.i("name",quote.getString("Symbol"));
               
                //Log.i("name",quote.getString("DaysLow"));
               
                //Log.i("name",quote.getString("DaysHigh"));
               
                //Log.i("name",quote.getString("Open"));
               
                //Log.i("name",quote.getString("PreviousClose"));
                String symbol=quote.getString("Symbol");
                tv.setText(symbol);
                String dayslow=quote.getString("DaysLow");
                tv1.setText(dayslow);
            //tv1.setText(quote.getString("DaysLow"));
            tv2.setText(quote.getString("DaysHigh"));
            tv3.setText(quote.getString("Open"));
            tv4.setText(quote.getString("Change"));
                }
 
                // A Simple JSONObject Value Pushing
                //json.put("execution-start-time", "sample value");
                Log.i("Praeda","<jsonobject>\n"+json.toString()+"\n</jsonobject>");
                //Log.i("Praeda12",json.get("").toString());
 
                // Closing the input stream will trigger connection release
                instream.close();
            }
 
 
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.getMessage();
        }
        
    }
 
}
Its a simple call to the url and how to retrieve the data from the json format hope it would be beneficial for you if any queries then you can drop a comment.!!!!!!!!

6 comments:

  1. Great tutorial code, but it doesnt seem to work in terms of displaying anything to the screen on my android emulator. I thought you needed to connect to the yql service if you wanted to access things like stock quotes. I would add a suggestion but I'm very new to this and still learning. If you could help with adding whatever code I would need to access the yql and store data on stock quotes like the bid,ask,open,close,etc.. and display it to some textview in the xml I would be humbly in your debt.

    Thanks a bundle ^^,

    ReplyDelete
  2. just surf the yql console site and see the tags in xml which when you will parse can easily be displayed to the textview like in the above example you can see i have got the output from the yahoo api in the json format and you have the option to take output in xml format and for that you can use the XMLParser of android.

    ReplyDelete
  3. throws java.net.UnknownHostException for me.

    09-07 00:00:26.675: W/System.err(469): java.net.UnknownHostException: finance.yahoo.com
    09-07 00:00:26.755: W/System.err(469): at java.net.InetAddress.lookupHostByName(InetAddress.java:513)
    09-07 00:00:26.755: W/System.err(469): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:278)
    09-07 00:00:26.755: W/System.err(469): at java.net.InetAddress.getAllByName(InetAddress.java:242)
    09-07 00:00:26.755: W/System.err(469): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:136)
    09-07 00:00:26.755: W/System.err(469): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
    09-07 00:00:26.755: W/System.err(469): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
    09-07 00:00:26.765: W/System.err(469): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:348)
    09-07 00:00:26.765: W/System.err(469): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
    09-07 00:00:26.765: W/System.err(469): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
    09-07 00:00:26.765: W/System.err(469): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
    09-07 00:00:26.765: W/System.err(469): at com.aforapps.currency.exchange.RestClient.connect(RestClient.java:65)
    09-07 00:00:26.765: W/System.err(469): at com.aforapps.currency.exchange.ExchangeUpdateService.buildUpdate(ExchangeUpdateService.java:43)
    09-07 00:00:26.765: W/System.err(469): at com.aforapps.currency.exchange.ExchangeUpdateService.onStart(ExchangeUpdateService.java:31)
    09-07 00:00:26.765: W/System.err(469): at android.app.Service.onStartCommand(Service.java:420)
    09-07 00:00:26.765: W/System.err(469): at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3059)
    09-07 00:00:26.765: W/System.err(469): at android.app.ActivityThread.access$3600(ActivityThread.java:126)
    09-07 00:00:26.765: W/System.err(469): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2101)
    09-07 00:00:26.765: W/System.err(469): at android.os.Handler.dispatchMessage(Handler.java:99)
    09-07 00:00:26.765: W/System.err(469): at android.os.Looper.loop(Looper.java:123)
    09-07 00:00:26.765: W/System.err(469): at android.app.ActivityThread.main(ActivityThread.java:4633)
    09-07 00:00:26.765: W/System.err(469): at java.lang.reflect.Method.invokeNative(Native Method)
    09-07 00:00:26.765: W/System.err(469): at java.lang.reflect.Method.invoke(Method.java:521)
    09-07 00:00:26.765: W/System.err(469): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
    09-07 00:00:26.765: W/System.err(469): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
    09-07 00:00:26.765: W/System.err(469): at dalvik.system.NativeStart.main(Native Method)

    ReplyDelete
  4. may be you haven't add the permission in the manifest file as android.Permission.INTERNET or i can say is the problem of yahoo api sometimes it doesn't reply with the result the solution is to try later

    ReplyDelete
  5. Yeah, sorry i forgot Internet permission. Now that I have, it is still throwing the same exception. Can you please give me a sample url to test. I think I am giving wrong input to it.

    ReplyDelete
  6. I got it. I was sending wrong url. Thanks for the code. Nice tutorial

    ReplyDelete