0

我的问题是:在我的代码中,我试图从 HTTP 客户端获取 JSON 对象并在 LogCat 中打印它们。但是什么也没发生。所以为了测试,我添加了 Log("sdf","1") 行。现在我可以看到在 Log("sdf","2") 行之后,没有代码正在运行。没有错误,没有例外或没有类似的东西。我已添加 Internet 权限。我错过了什么还是我的 Eclipse 有问题?谢谢您的帮助。

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
    HttpGet httpget = new HttpGet("http://tusyad2014.org/akb_api/hastalarimiza_ozel.json");
    httpget.setHeader("Content-type", "application/json;charset=utf-8");

    Log.e("sdf","1");
    try {
        Log.e("sdf","2");
        HttpResponse response = httpclient.execute(httpget);
        Log.e("sdf","3");
        String result = EntityUtils.toString(response.getEntity(), "UTF-8");
        Log.e("sdf","4");
        JSONArray ja = new JSONArray(result);

        Log.e("sdf","5");

        int n = ja.length();

        for (int i = 0; i < n; i++) {

          JSONObject jo = ja.getJSONObject(i);

          Log.d("sdf","Json : " + jo.getString("id") + " - "+ jo.getString("name"));

        }

    } catch (Exception e) {

      Log.e("sdf","");
    }      
}   
}

日志

08-15 05:14:40.609: E/sdf(1656): 1
08-15 05:14:40.609: E/sdf(1656): 2
08-15 05:14:41.167: D/gralloc_goldfish(1656): Emulator without GPU emulation detected.
4

3 回答 3

1

You are running network related operation on the ui thread which is not possible. Use a Thread or Asynctask.

Post Honeycomb you will get NetworkOnMainThreadException

This is only thrown for applications targeting the Honeycomb SDK or higher. Applications targeting earlier SDK versions are allowed to do networking on their main event loop threads, but it's heavily discouraged. See the document Designing for Responsiveness.

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

AsyncTask docs

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

Edit

 new TheTask().execute();

Then

public void  getJson()
  {
        HttpClient httpclient = new DefaultHttpClient();
        httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        HttpGet request = new HttpGet("http://tusyad2014.org/akb_api/hastalarimiza_ozel.json");     
        try
        {
        HttpResponse response = httpclient.execute(request);
        HttpEntity resEntity = response.getEntity();
        String _response=EntityUtils.toString(resEntity);
        Log.e("sdf",_response);

        } catch (Exception e) {

          Log.e("sdf","");
        }      
    }   
    class TheTask extends AsyncTask <String,Void,Void>
  { 
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }
    @Override
    protected void onPostExecute(Void result) {

    super.onPostExecute(result);

    }
    @Override
    protected Void doInBackground(String... params) {
        getJson();
        return null;
    }
    }   
  }

Log

08-15 15:05:26.745: E/sdf(21197): [{"id":"1","name":"Ayakta Åekil BozukluÄu- Kemik Ãıkıntısı- Halluks Valgus - Halluks Rijitus"},{"id":"2","name":"Ãekiç Parmak"},{"id":"3","name":"DoÄumsal El, Ayak, Ãst Ekstremite Anamolileri, Eksiklikleri, Åekil Bozuklukları"},{"id":"4","name":"DoÄum Felci- DoÄum sonrası Beyin Felci, Spastisite"},{"id":"5","name":"Kapalı omuz, dirsek, el bileÄi ameliyatları- ARTROSKOPÄ°K cerrahi giriÅimler"},{"id":"6","name":"Ortopedi de PRP ( trombositten zengin plazma) uygulamaları"},{"id":"7","name":"Kırık kaynama gecikmesi, kaynamamaları ve ultrason tedavisi"},{"id":"8","name":"El bileÄi kırıkları, radius ve ulna alt uç kırıkları, skafoid kırıkları"},{"id":"9","name":"Humerus kırıkları, radial sinir sorunları, kaynamamaları"},{"id":"10","name":"Eldeki kistler,Ganglion kistleri"},{"id":"11","name":"Dirsek aÄrısı,Tenisçi dirseÄi, Golfçü dirseÄi"},{"id":"12","name":"Elde uyuÅma, karıncalanma, iÄnelenme, aÄrı"},{"id":"13","name":"Pleksus ve sinir yaralanmaları"},{"id":"14","name":"Ãnkol Kemik (Radius ve Ulna) Kaynamamaları"},{"id":"15","name":"Femur BaÅı Avasküler Nekrozu"},{"id":"16","name":"Tetik Parmak"},{"id":"17","name":"BaÅparmak Tendonlarının SıkıÅması (De Quervain HastalıÄı)"},{"id":"18","name":"Omuz AÄrısı ve Hareket KısıtlılıÄı"},{"id":"19","name":"DoÄumsal Tibia Kaynamaması (Konjenital Tibia Psödoartrozu)"}]
于 2013-08-15T09:19:33.843 回答
1

As Raghunandan suggest you need to use Asynctask or Background Thread for this operations.

For Example :

    new AsyncTask<Void, Void, Void>() {


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


@Override
protected Void doInBackground(Void... params) {

DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
    HttpGet httpget = new HttpGet("http://tusyad2014.org/akb_api/hastalarimiza_ozel.json");
    httpget.setHeader("Content-type", "application/json;charset=utf-8");

    Log.e("sdf","1");
    try {
        Log.e("sdf","2");
        HttpResponse response = httpclient.execute(httpget);
        Log.e("sdf","3");
        String result = EntityUtils.toString(response.getEntity(), "UTF-8");
        Log.e("sdf","4");
        JSONArray ja = new JSONArray(result);

        Log.e("sdf","5");

        int n = ja.length();

        for (int i = 0; i < n; i++) {

          JSONObject jo = ja.getJSONObject(i);

          Log.d("sdf","Json : " + jo.getString("id") + " - "+ jo.getString("name"));

        }

    } catch (Exception e) {

      Log.e("sdf","");
    }      


}       
    }.execute();

EDIT :

And also see this answer.

于 2013-08-15T09:20:42.107 回答
0

The problem might be that your network is slow...... it takes a while to get response in slow connection....

further it would be giving exception in new android apis as you are doing network related work on main thread

于 2013-08-15T09:19:59.530 回答