GSON和谷歌 [英] Gson and Google

查看:90
本文介绍了GSON和谷歌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的code:

 公共字符串测试(){
        网址URL = NULL;
        尝试{
            URL =新URL(\"http://api.heroesofnewerth.com/player_statistics/ranked/nickname/Hieratic/?token=0CZGH8ZI7UR8J2GN\");
        }赶上(MalformedURLException的E1){
            // TODO自动生成catch块
            e1.printStackTrace();
        }
        读者的BufferedReader = NULL;
        字符串x =;
        尝试{
            读者=新的BufferedReader(新的InputStreamReader(url.openStream(),UTF-8));
            为(字符串线;(线= reader.readLine())=无效;!){
                的System.out.println(线);
                X =线;
            }
        }赶上(IOException异常五){
            // TODO自动生成catch块
            e.printStackTrace();
        } {最后
            如果(!读者= NULL){尝试reader.close();}赶上(IOException异常忽略){
            } {}
        }
        JsonElement根=新JsonParser()解析(X)。
        返回X;
    }
}

现在我想插入文本分为以下TextView的。

 保护无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.activity_create_competetion);    TextView的电视=(的TextView)findViewById(R.id.competetion_text);
    JsonCollector JC =新JsonCollector();    tv.setText(jc.test());

然而,当我尝试运行它。我得到以下错误:

 致命异常:主要
 E / AndroidRuntime(1800):了java.lang.RuntimeException:无法启动活动ComponentInfo {com.example.konkurrencesigner / com.example.konkurrencesigner.CreateCompetetion}:android.os.NetworkOnMainThreadException
    在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
 E / AndroidRuntime(1800):在android.app.ActivityThread.access $ 600(ActivityThread.java:141)
 E / AndroidRuntime(1800):在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1234)
 E / AndroidRuntime(1800):在android.os.Handler.dispatchMessage(Handler.java:99)
  E / AndroidRuntime(1800):在android.os.Looper.loop(Looper.java:137)
    E / AndroidRuntime(1800):在android.app.ActivityThread.main(ActivityThread.java:5039)
    E / AndroidRuntime(1800):在java.lang.reflect.Method.invokeNative(本机方法)
    E / AndroidRuntime(1800):在java.lang.reflect.Method.invoke(Method.java:511)
    E / AndroidRuntime(1800):在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:793)
    E / AndroidRuntime(1800):在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
    E / AndroidRuntime(1800):在dalvik.system.NativeStart.main(本机方法)
    E / AndroidRuntime(1800):因:android.os.NetworkOnMainThreadException
    E / AndroidRuntime(1800):在android.os.StrictMode $ AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
    E / AndroidRuntime(1800):在java.net.InetAddress.lookupHostByName(InetAddress.java:385)
     E / AndroidRuntime(1800):在java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
 E / AndroidRuntime(1800):在java.net.InetAddress.getAllByName(InetAddress.java:214)
 E / AndroidRuntime(1800):在libcore.net.http.HttpConnection<&初始化GT;(HttpConnection.java:70)。
 E / AndroidRuntime(1800):在libcore.net.http.HttpConnection<&初始化GT;(HttpConnection.java:50)。
 E / AndroidRuntime(1800):在libcore.net.http.HttpConnection $ Address.connect(HttpConnection.java:340)
E / AndroidRuntime(1800):在libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
 E / AndroidRuntime(1800):在libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
 E / AndroidRuntime(1800):在libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:316)
    E / AndroidRuntime(1800):在libcore.net.http.HttpEngine.connect(HttpEngine.java:311)
 E / AndroidRuntime(1800):在libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:290)
 E / AndroidRuntime(1800):在libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:240)
 E / AndroidRuntime(1800):在libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:282)

谁能告诉我为什么发生这种情况?

请注意,我已经添加下面一行在我的Andr​​oid清单:

 <使用许可权的android:NAME =android.permission.INTERNET对/>


解决方案

您是在主线程上做HTTP通信,这就是为什么你得到一个 NetworkOnMainThreadException 。做在一个单独的线程,使用 的AsyncTask 将是一个理想的解决方案,这里是你如何实现它的例子:

 私人TextView的电视;@覆盖
保护无效的onCreate(捆绑savedInstanceState){    super.onCreate(savedInstanceState);
    的setContentView(R.layout.activity_create_competetion);    电视=(的TextView)findViewById(R.id.competetion_text);
    JsonCollector JC =新JsonCollector();    //创建并执行新的AsyncTask,TextView的意志
    当任务完成//进行异步更新。
    updateTextView();
}私人无效updateTextView(){
    新的AsyncTask<太虚,太虚,字符串>(){        @覆盖
        / *运行在独立的线程* /
        保护字符串doInBackground(虚空...... PARAMS){
            字符串结果= NULL;
            读者的BufferedReader = NULL;
            尝试{
                网址URL =新URL(\"http://api.heroesofnewerth.com/player_statistics/ranked/nickname/Hieratic/?token=0CZGH8ZI7UR8J2GN\");
                读者=新的BufferedReader(新的InputStreamReader(url.openStream(),UTF-8));
                为(字符串线;(线= reader.readLine())=无效;!){
                    的System.out.println(线);
                    结果=线;
                }
            }赶上(例外五){
                e.printStackTrace();
            } {最后
                如果(读者!= NULL){
                    尝试{
                        reader.close();
                    }赶上(IOException异常五){
                        // 忽视
                    }
                }
            }            返回结果;
        }        @覆盖
        / *运行UI /主线程就当doInBackground()
         *已完成* /
        保护无效onPostExecute(字符串结果){
            如果(结果!= NULL){
                //更新的TextView只有当我们得到了一个结果
                //从HTTP请求
                tv.setText(结果);
            }
        }    }。执行();
}

I have the following code:

public String test(){
        URL url = null;
        try {
            url = new URL("http://api.heroesofnewerth.com/player_statistics/ranked/nickname/Hieratic/?token=0CZGH8ZI7UR8J2GN");
        } catch (MalformedURLException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        BufferedReader reader = null;
        String x = "";
        try {
            reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
            for (String line; (line = reader.readLine()) != null;) {
                System.out.println(line);
                x = line;
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally{
            if (reader !=null) try{reader.close();} catch (IOException ignore) {
            }{}
        }
        JsonElement root = new JsonParser().parse(x);
        return x;
    }
}

now i want to insert the text into the following textView.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_create_competetion);

    TextView tv = (TextView) findViewById(R.id.competetion_text);
    JsonCollector jc = new JsonCollector();

    tv.setText(jc.test());

However when i try to run it. i get the following error:

FATAL EXCEPTION: main
 E/AndroidRuntime(1800): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.konkurrencesigner/com.example.konkurrencesigner.CreateCompetetion}: android.os.NetworkOnMainThreadException
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
 E/AndroidRuntime(1800):    at android.app.ActivityThread.access$600(ActivityThread.java:141)
 E/AndroidRuntime(1800):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
 E/AndroidRuntime(1800):    at android.os.Handler.dispatchMessage(Handler.java:99)
  E/AndroidRuntime(1800):   at android.os.Looper.loop(Looper.java:137)
    E/AndroidRuntime(1800):     at android.app.ActivityThread.main(ActivityThread.java:5039)
    E/AndroidRuntime(1800):     at java.lang.reflect.Method.invokeNative(Native Method)
    E/AndroidRuntime(1800):     at java.lang.reflect.Method.invoke(Method.java:511)
    E/AndroidRuntime(1800):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
    E/AndroidRuntime(1800):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
    E/AndroidRuntime(1800):     at dalvik.system.NativeStart.main(Native Method)
    E/AndroidRuntime(1800): Caused by: android.os.NetworkOnMainThreadException
    E/AndroidRuntime(1800):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
    E/AndroidRuntime(1800):     at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
     E/AndroidRuntime(1800):    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
 E/AndroidRuntime(1800):    at java.net.InetAddress.getAllByName(InetAddress.java:214)
 E/AndroidRuntime(1800):    at libcore.net.http.HttpConnection.<init>(HttpConnection.java:70)
 E/AndroidRuntime(1800):    at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
 E/AndroidRuntime(1800):    at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340)
E/AndroidRuntime(1800):     at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
 E/AndroidRuntime(1800):    at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
 E/AndroidRuntime(1800):    at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:316)
    E/AndroidRuntime(1800):     at libcore.net.http.HttpEngine.connect(HttpEngine.java:311)
 E/AndroidRuntime(1800):    at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:290)
 E/AndroidRuntime(1800):    at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:240)
 E/AndroidRuntime(1800):    at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:282)

Can anyone tell me why this is happening?

please note that i have already added the following line in my android manifest:

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

解决方案

You are doing HTTP communication on the main thread, that's why you're getting a NetworkOnMainThreadException. Do it in a separate thread, using an AsyncTask would be an ideal solution, here's an example of how you could implement it:

private TextView tv;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_create_competetion);

    tv = (TextView) findViewById(R.id.competetion_text);
    JsonCollector jc = new JsonCollector();

    // Create and execute a new AsyncTask, the TextView will
    // be updated asynchronously when the task has finished.
    updateTextView();
}

private void updateTextView() {
    new AsyncTask<Void, Void, String>() {

        @Override
        /* Runs on a separate thread */
        protected String doInBackground(Void... params) {
            String result = null;
            BufferedReader reader = null;
            try {
                URL url = new URL("http://api.heroesofnewerth.com/player_statistics/ranked/nickname/Hieratic/?token=0CZGH8ZI7UR8J2GN");
                reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
                for (String line; (line = reader.readLine()) != null;) {
                    System.out.println(line);
                    result = line;
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException e) {
                        // Ignore
                    }
                }
            }

            return result;  
        }

        @Override
        /* Runs on the UI/Main thread when doInBackground()
         * has finished */
        protected void onPostExecute(String result) {
            if(result != null) {
                // Update the TextView only if we got a result
                // from the HTTP request
                tv.setText(result);
            }
        }

    }.execute();
}

这篇关于GSON和谷歌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆