试图在片段中显示ListView

时间:2014-04-13 22:52:17

标签: android listview android-fragments

我正在尝试使用片段中的自定义适配器显示ListView,但它不会出现。我使用的是与我在正常活动中使用的相同的代码,但它在这个片段中没有...

代码没有错误,但没有出现任何错误。

enter image description here

public class Amics extends Fragment {
    ListView listView_Amics;
    ArrayAdapter<Usuari> adapter;
    List<Usuari> list = new ArrayList<Usuari>();


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        View rootView = inflater.inflate(R.layout.amics, container, false);


        listView_Amics = (ListView) rootView.findViewById(R.id.listView_amics);
            adapter = new MyAdapter_Amics(getActivity(),list);
            listView_Amics.setAdapter(adapter);

    obtenir_amics1();  // THIS FUNCTION ADD ELEMENTS TO THE LIST AND SETS ADAPTER

        return rootView;
    }

    public boolean obtenir_amics1(){
    String data = null; // THE STRING TO SAVE HTTPOST RESPONSE

        // HTTP POST DATA RECIEVING..
        List<NameValuePair> parametres = new ArrayList<NameValuePair>();
        parametres.add(new BasicNameValuePair("id", id));
        try {
            DefaultHttpClient client = new DefaultHttpClient();
            HttpPost request = new HttpPost("MY_HOST");
            request.setEntity(new UrlEncodedFormEntity(parametres));
            HttpResponse response = client.execute(request);
            HttpEntity entity = response.getEntity();
            data = EntityUtils.toString(entity);
            Log.e("DADES OBTINGUDES", data);

            try {

                JSONArray json = new JSONArray(data);
                int limit = 50;
                if(json.length()<limit){limit=json.length();}
                for (int i = 0; i < limit; i++) {
                    JSONObject obj = json.getJSONObject(i);
                    String nombre = obj.getString("usuario_two");
                    boolean selected = false;
                    Log.e("amic:", nombre);

                list.add(new Usuari(nombre,selected));


                listView_Amics.setAdapter(adapter);

                }
                return true;
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        } catch (ClientProtocolException e) {
            Log.d("HTTPCLIENT", e.getLocalizedMessage());
        } catch (IOException e) {
            Log.d("HTTPCLIENT", e.getLocalizedMessage());
        }
        return false;
    }

1 个答案:

答案 0 :(得分:0)

覆盖onResume()方法并将adapter = new MyAdapter_Amics(getActivity(),list); listView_Amics.setAdapter(adapter); obtenir_amics1();转为onResume()