在 Android 中使用 Gson

Using Gson in Android

我正在使用 google-gson 从一个 rest 网络服务获取数据,但 LogCat 显示我 android.os.NetWorkOnMainThreadException。对于与 Web 服务的连接,我使用来自 https://code.google.com/p/httpclientandroidlib/.

的 httpclientandroidlib 包

我的代码是:

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import ch.boye.httpclientandroidlib.HttpEntity;
import ch.boye.httpclientandroidlib.HttpResponse;
import ch.boye.httpclientandroidlib.HttpStatus;
import ch.boye.httpclientandroidlib.client.methods.HttpGet;
import ch.boye.httpclientandroidlib.impl.client.DefaultHttpClient;

import com.google.gson.Gson;


public class MainActivity extends Activity {

    String url = "http://localhost:8080/SightsWebService/sights/getFun";

    @Override
    public void onCreate(Bundle savedInstanceState) {

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

        InputStream source = retrieveStream(url);

        Gson gson = new Gson();
        Reader reader = new InputStreamReader(source);
        ListKozanisPlaces sightsList = gson.fromJson(reader, ListKozanisPlaces.class);


        for ( int counter = 0; counter < sightsList.getList().size(); counter++ )
            Toast.makeText(this, sightsList.getList().get( counter ).toString(), Toast.LENGTH_SHORT).show();
    }

    private InputStream retrieveStream(String url) 
    {    
        DefaultHttpClient client = new DefaultHttpClient(); 

        HttpGet getRequest = new HttpGet(url);

        try {      
           HttpResponse getResponse = client.execute(getRequest);
           final int statusCode = getResponse.getStatusLine().getStatusCode();

           if (statusCode != HttpStatus.SC_OK) { 
              Log.w(getClass().getSimpleName(), 
                  "Error " + statusCode + " for URL " + url); 
              return null;
           }

           HttpEntity getResponseEntity = getResponse.getEntity();
           return getResponseEntity.getContent();

        } 
        catch (IOException e) {
           getRequest.abort();
           Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
        }   
        return null;     
    }
}

感谢任何指点。谢谢

顾名思义android does not allow for networking operations on the "main" thread. You need to do these operations on an other thread. The simplest way to go about this is with an Asynctask。快速 google 搜索应该可以找到几个关于 Asynctasks 的教程。

当应用程序试图在其主线程上执行网络操作时抛出此异常。尝试使用 AsyncTask 进行网络操作

演示示例,你可以参考这个http://android-er.blogspot.in/2012/04/androidosnetworkonmainthreadexception.html