从网络线程android中检索数据

时间:2016-07-10 12:48:29

标签: java android json multithreading network-programming

我正在尝试从一个URL到一个Android应用程序获得一个JSON ARRAY,我已经在一个特殊的线程中创建了网络连接。我的连接工作正常,但我无法将接收数据解析为字符串变量my connection class,如下所示

public class Connection {

    String data="no data";

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }

    Context mContext;
    public Connection(Context context){
        this.mContext=context;
    }


  public void runNetwork(String url) {
        final String urlString = url;

        final Thread thread = new Thread(new Runnable()  {
            @Override
            public void run() {
                try {
                    URL url = new URL(urlString);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setReadTimeout(10000 /* milliseconds */);
                    conn.setConnectTimeout(15000 /* milliseconds */);
                    conn.setRequestMethod("GET");
                    conn.setDoInput(true);
                    // Starts the query
                    conn.connect();
                    InputStream stream = conn.getInputStream();
                    String NetworkData = convertStreamToString(stream);
                   System.out.println(NetworkData);
                    setData(NetworkData);
                    stream.close();

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        thread.start();



    }
    static String convertStreamToString(java.io.InputStream is) {
        java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
        return s.hasNext() ? s.next() : "";
    }

}

当我打印networkData变量时,它打印从url检索的数据。但它没有在线程外解析。这段代码出了什么问题?

0 个答案:

没有答案