Anurupa_Dey
Anurupa_Dey

Reputation: 113

Parsing JSON from Website

So I wrote a Java class for Android to fetch JSON from a website and Parse it:

public class Communicator {


    public String executeHttpGet(String URL) throws Exception 
    {
        BufferedReader in = null;
        try 
        {
            HttpClient client = new DefaultHttpClient();
            HttpGet request = new HttpGet();
            request.setURI(new URI(URL));
            HttpResponse response = client.execute(request);
            InputStream ips  = response.getEntity().getContent();
            BufferedReader buf = new BufferedReader(new InputStreamReader(ips,"UTF-8"));

            StringBuilder sb = new StringBuilder();
            String s;
            while(true )
            {
                s = buf.readLine();
                if(s==null || s.length()==0)
                    break;
                sb.append(s);

            }
            buf.close();
            ips.close();
            return sb.toString();
        } 
        finally 
        {
            if (in != null) 
            {
                try 
                {
                    in.close();
                } 
                catch (IOException e)    
                {
                    Log.d("Exceptions !", e.toString());
                }
            }
        }
    }

}

So here is the site that I try to access and here's the sample output:

http://www.railpnrapi.com/6520652825

{"tnum":"15694","tname":"BARAK VALLEY EX","tdate":"25-7-2013","from":"SCL","to":"LMG","class":"SL","charted":true,"numofpax":1,"pax":[{"coach":"S1","berth":"8","quota":"GN","status":"CNF"}]}

And here is the INCOMPLETE code to read the JSON :

String page = new Communicator().executeHttpGet(url);
System.out.println(page)
JSONObject jsonObj = new JSONObject(page);
String id = jsonObj.getString("tname");
TextView t1 = (TextView)findViewById(R.id.textView1);
t1.setText(id);

I tried to output just a small part of the JSON to a TextView but this doesn't work. Does this mean I have to parse it completely beforehand?

Also LogCat shows this errors:

07-02 06:18:08.889: W/System.err(831): android.os.NetworkOnMainThreadException
07-02 06:18:08.899: W/System.err(831):  at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
07-02 06:18:08.899: W/System.err(831):  at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
07-02 06:18:08.899: W/System.err(831):  at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
07-02 06:18:08.899: W/System.err(831):  at java.net.InetAddress.getAllByName(InetAddress.java:214)
07-02 06:18:08.899: W/System.err(831):  at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
07-02 06:18:08.899: W/System.err(831):  at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
07-02 06:18:08.899: W/System.err(831):  at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
07-02 06:18:08.899: W/System.err(831):  at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
07-02 06:18:08.909: W/System.err(831):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
07-02 06:18:08.909: W/System.err(831):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
07-02 06:18:08.909: W/System.err(831):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
07-02 06:18:08.909: W/System.err(831):  at com.example.in.ddas.indianrailpnr.Communicator.executeHttpGet(Communicator.java:27)
07-02 06:18:08.909: W/System.err(831):  at com.example.in.ddas.indianrailpnr.PNRActivity$1.onTouch(PNRActivity.java:74)
07-02 06:18:08.919: W/System.err(831):  at android.view.View.dispatchTouchEvent(View.java:7241)
07-02 06:18:08.919: W/System.err(831):  at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2174)
07-02 06:18:08.919: W/System.err(831):  at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1917)
07-02 06:18:08.919: W/System.err(831):  at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2174)
07-02 06:18:08.919: W/System.err(831):  at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1917)
07-02 06:18:08.919: W/System.err(831):  at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2174)
07-02 06:18:08.929: W/System.err(831):  at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1917)
07-02 06:18:08.929: W/System.err(831):  at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2174)
07-02 06:18:08.929: W/System.err(831):  at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1917)
07-02 06:18:08.929: W/System.err(831):  at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2174)
07-02 06:18:08.929: W/System.err(831):  at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1917)
07-02 06:18:08.939: W/System.err(831):  at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:1953)
07-02 06:18:08.939: W/System.err(831):  at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1405)
07-02 06:18:08.939: W/System.err(831):  at android.app.Activity.dispatchTouchEvent(Activity.java:2410)
07-02 06:18:08.939: W/System.err(831):  at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1901)
07-02 06:18:08.939: W/System.err(831):  at android.view.View.dispatchPointerEvent(View.java:7426)
07-02 06:18:08.949: W/System.err(831):  at android.view.ViewRootImpl.deliverPointerEvent(ViewRootImpl.java:3220)
07-02 06:18:08.949: W/System.err(831):  at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:3165)
07-02 06:18:08.949: W/System.err(831):  at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:4292)
07-02 06:18:08.949: W/System.err(831):  at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:4271)
07-02 06:18:08.949: W/System.err(831):  at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:4363)
07-02 06:18:08.959: W/System.err(831):  at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:179)
07-02 06:18:08.959: W/System.err(831):  at android.os.MessageQueue.nativePollOnce(Native Method)
07-02 06:18:08.959: W/System.err(831):  at android.os.MessageQueue.next(MessageQueue.java:125)
07-02 06:18:08.959: W/System.err(831):  at android.os.Looper.loop(Looper.java:124)
07-02 06:18:08.969: W/System.err(831):  at android.app.ActivityThread.main(ActivityThread.java:5041)
07-02 06:18:08.969: W/System.err(831):  at java.lang.reflect.Method.invokeNative(Native Method)
07-02 06:18:08.969: W/System.err(831):  at java.lang.reflect.Method.invoke(Method.java:511)
07-02 06:18:08.969: W/System.err(831):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
07-02 06:18:08.969: W/System.err(831):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
07-02 06:18:08.969: W/System.err(831):  at dalvik.system.NativeStart.main(Native Method)

So how do I connect my app to the internet (I have already set the permission still it doesn't work)! Any Help appreciated !

Upvotes: 0

Views: 361

Answers (5)

Raghunandan
Raghunandan

Reputation: 133560

You should use a Asynctask for doing network related operation.

                 or

Create a thread and run your network related operation inside the thread.

You are trying to do nework related operation on the ui thread. which in not possible post HoneyComb.

http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html

Invoke asynctask

   new TheTask().execute("myurl"); // invoke on ui thread.

AsyncTask

http://developer.android.com/reference/android/os/AsyncTask.html

class TheTask extends AsyncTask<String,Void,Void>
{

    @Override
    protected String doInBackground(String... params) {
             //params[0] is the url
        // TODO Auto-generated method stub
         // your network related operarion
             String result = executeHttpGet(params[0]);
        return result;
    }

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
            if(result!=null)
            {
                   // parse json string
            }   
    }

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
    }
}

Upvotes: 2

Gru
Gru

Reputation: 2694

Raghunandan had explained brief enough the issue you are facing....

Why we don't have to use MainThread (called UI Thread also) to do network related operations?

Ans- 1. UI Thread have other task for e.g. Render the user interface etc. 2. Instead of using UI thread which already overloaded with its important OS related task.

So its better to use Asynctask to work on network related task which is other thread to handle such tasks like was Java's Thread class.

Following link is opensource library which is little but advanced but much more helpful to parse JSON.

Here is the link

Upvotes: 0

A.S.
A.S.

Reputation: 4574

Hei there, since you are looking for a JSON Parser I can recommend you the GSON Builder GSON-LINK. A good tutorial can be found here: enter link description here

The benefit of this lib is that you only have to define your object once and can use it in every parsing situation, and you will have a DataObject :)

Upvotes: 0

Rico Harisin
Rico Harisin

Reputation: 3409

NetworkOnMainThreadException it's mean you cannot put network process on main thread use async task instead http://developer.android.com/reference/android/os/AsyncTask.html

Upvotes: 0

harmjanr
harmjanr

Reputation: 937

You should do Network things on another thread than the main thread. Use an ASyncTask for this.

An example of an AsyncTask: http://subinsebastien.tumblr.com/post/10319834334/simple-asynctask-example-in-android

Upvotes: 0

Related Questions