0

所以我为 Android 编写了一个 Java 类来从网站获取 JSON 并解析它:

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

}

所以这是我尝试访问的站点,这是示例输出:

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"}]}

这是读取 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);

我试图将 JSON 的一小部分输出到 TextView,但这不起作用。这是否意味着我必须事先完全解析它?

LogCat 也显示此错误:

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)

那么如何将我的应用程序连接到互联网(我已经设置了权限仍然无法正常工作)!任何帮助表示赞赏!

4

5 回答 5

2

您应该使用 aAsynctask来进行网络相关操作。

                 or

创建一个线程并在该线程内运行您的网络相关操作。

您正在尝试在 ui 线程上进行与网络相关的操作。这在 HoneyComb 之后是不可能的。

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

调用异步任务

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

异步任务

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();
    }
}
于 2013-07-02T06:22:42.120 回答
0

Raghunandan 已经对您所面临的问题进行了足够简短的解释......

为什么我们不必使用 MainThread(也称为 UI Thread)来做网络相关的操作?

Ans- 1. UI 线程有其他任务,例如渲染用户界面等。 2. 而不是使用已经超载其重要的操作系统相关任务的 UI 线程。

因此,最好用于Asynctask处理网络相关任务,这是其他线程来处理此类任务,例如 wasJava的 Thread 类。

以下链接是开源库,它虽小但先进,但对解析 JSON 更有帮助。

链接在这里

于 2013-07-02T06:37:46.850 回答
0

您好,既然您正在寻找 JSON 解析器,我可以向您推荐 GSON Builder GSON-LINK。可以在这里找到一个很好的教程:在此处输入链接描述

这个库的好处是您只需定义一次对象,并且可以在每种解析情况下使用它,并且您将拥有一个 DataObject :)

于 2013-07-02T06:32:28.810 回答
0

您应该在主线程之外的另一个线程上执行网络事务。为此使用 ASyncTask。

AsyncTask 的示例:http ://subinsebastien.tumblr.com/post/10319834334/simple-asynctask-example-in-android

于 2013-07-02T06:22:51.063 回答
0

NetworkOnMainThreadException 这意味着您不能将网络进程放在主线程上,而是使用异步任务http://developer.android.com/reference/android/os/AsyncTask.html

于 2013-07-02T06:24:08.817 回答