json数据显示空白页

时间:2015-09-12 12:38:04

标签: android json apache

  

我正在尝试获取数据并将其设置为listview ....我已经看过教程并构建了自己的逻辑但是没有错误在logcat ....但应用程序显示空白页

     

我试图重复删除程序,以便在调试第二个tryCatch块后自动跳过它.......

 package com.example.altaf;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;




import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.os.Build;

public class MainActivity extends ActionBarActivity {

    String id,name,email,address,gender,phone,mobile,home,office,contacts,line;
    String CONTACT="contact";
    InputStream is;
    String response;
    ListView lv;
    SimpleAdapter sadp;
    ArrayList<HashMap<String, String>>list=new ArrayList<HashMap<String,String>>();

    String url="http://api.androidhive.info/contacts/";

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

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
        .permitAll().build();StrictMode.setThreadPolicy(policy);


        lv=(ListView)findViewById(R.id.listView1);

        ArrayList<NameValuePair> namevalue = new ArrayList<NameValuePair>();
        list=new ArrayList<HashMap<String,String>>();


        try {
            HttpClient hpclient = new DefaultHttpClient();
            HttpGet httpGet=new HttpGet(url);
            HttpPost httppost = new HttpPost(url);
            httppost.setEntity(new UrlEncodedFormEntity(namevalue));
            HttpResponse response = hpclient.execute(httppost);
            HttpEntity entity = response.getEntity();

            is = entity.getContent();
            Log.e("pass1", "Connection sucess");
        } catch (Exception e) {
            Log.e("fail", e.toString());
        }
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            response = sb.toString();
            Log.e("pass2", "sucess");
        } catch (Exception e) {
            Log.e("fail", e.toString());

        }

        try {

            JSONObject objsnrry = new JSONObject(response);

            JSONArray arr = objsnrry.getJSONArray(CONTACT);

            String nm = " ";
            for (int i = 0; i < arr.length(); i++) 
            {
                JSONObject obj = arr.getJSONObject(i);
                String id = obj.getString("id");
                String name = obj.getString("name");
                String email = obj.getString("email");
                String address = obj.getString("address");
                String gender = obj.getString("gender");

                JSONObject phone1 = obj.getJSONObject("phone");
                String mobile1 = phone1.getString("mobile");
                String home1 = phone1.getString("home");
                String office1 = phone1.getString("office");

                HashMap<String, String> map = new HashMap<String, String>();

                map.put("id", id);
                map.put("name", name);
                map.put("email", email);
                map.put("address", address);
                map.put("mobile",mobile1);

                list.add(map);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            sadp = new SimpleAdapter(this, list,
                    R.layout.altaf, new String[] { "name",
                            "email", "mobile" }, new int[] { R.id.name,
                            R.id.emai, R.id.mobile });
            lv.setAdapter(sadp);

        } 
    }

1 个答案:

答案 0 :(得分:1)

您正在获取UI线程上的网络操作的例外,因为您正在捕获异常,这就是您无法看到它的原因。 使用AsyncTask ...

private class CopyAsync extends AsyncTask<Void, Void, Void>{

        ProgressDialog pd = null;
        @Override
        protected void onPreExecute() 
        {
            // TODO Auto-generated method stub
            super.onPreExecute();
            pd = ProgressDialog.show(MainActivity.this, "Loading data ...", "Please wait..."); 

        }

    @Override
    protected  void doInBackground(Void... arg0) 
    {

try {
        HttpClient hpclient = new DefaultHttpClient();
        HttpGet httpGet=new HttpGet(url);
        HttpPost httppost = new HttpPost(url);
        httppost.setEntity(new UrlEncodedFormEntity(namevalue));
        HttpResponse response = hpclient.execute(httppost);
        HttpEntity entity = response.getEntity();

        is = entity.getContent();
        Log.e("pass1", "Connection sucess");
    } catch (Exception e) {
        Log.e("fail", e.toString());
    }
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        response = sb.toString();
        Log.e("pass2", "sucess");
    } catch (Exception e) {
        Log.e("fail", e.toString());

    }

    try {

        JSONObject objsnrry = new JSONObject(response);

        JSONArray arr = objsnrry.getJSONArray(CONTACT);

        String nm = " ";
        for (int i = 0; i < arr.length(); i++) 
        {
            JSONObject obj = arr.getJSONObject(i);
            String id = obj.getString("id");
            String name = obj.getString("name");
            String email = obj.getString("email");
            String address = obj.getString("address");
            String gender = obj.getString("gender");

            JSONObject phone1 = obj.getJSONObject("phone");
            String mobile1 = phone1.getString("mobile");
            String home1 = phone1.getString("home");
            String office1 = phone1.getString("office");

            HashMap<String, String> map = new HashMap<String, String>();

            map.put("id", id);
            map.put("name", name);
            map.put("email", email);
            map.put("address", address);
            map.put("mobile",mobile1);

            list.add(map);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }


    @Override
    protected void onPostExecute(LinkedList<String> spinList) 
    {
        // TODO Auto-generated method stub
        super.onPostExecute(spinList);

        if(pd!=null) pd.dismiss();

         sadp = new SimpleAdapter(this, list,
                R.layout.altaf, new String[] { "name",
                        "email", "mobile" }, new int[] { R.id.name,
                        R.id.emai, R.id.mobile });
        lv.setAdapter(sadp);

    }

}       

并从OnCreate中调用它;

new CopyAsync ().execute();

并且不要忘记将Internet权限放入清单中。

我建议的另一件事,总是以适当的方式关闭(流,读者,游标等)。 喜欢:

BufferedReader reader=null;
try {
            reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            response = sb.toString();
            Log.e("pass2", "sucess");
        } catch (Exception e) {
            Log.e("fail", e.toString());

        }finally{
      try{
      is.close()
      reader.close()
     }catch(Exception e){ //like my Ex gf.. i don't care }
}