2014-09-04 2 views
0

Я получаю данные json и помещаю его в hashmap и hashmap в arraylist. Все, что происходит в осколок ListFragmentОтображение данных из Arraylist of Hashmap

protected String doInBackground(String... urls) { 
     JSONObject jsonObject = new JSONObject(); 

     try { 

      jsonObject.put("full_name", etUserSearch.getText().toString()); 
      responseReceive = JsonPostClient.SendHttpPost(urls[0], 
        jsonObject); 

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

     try { 
      Success = responseReceive.getJSONArray("Success"); 

      for (int i = 0; i < Success.length(); i++) { 
       JSONObject c = Success.getJSONObject(i); 

       String full_name = c.getString(TAG_FULL_NAME); 
       String user_name = c.getString(TAG_USER_NAME); 
       String user_id = c.getString(TAG_USER_ID); 

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

       // adding each child node to HashMap key => value 
       friends.put(TAG_FULL_NAME, full_name); 
       friends.put(TAG_USER_NAME, user_name); 
       friends.put(TAG_USER_ID, user_id); 

       // adding contact to contact list 
       FriendSearchList.add(friends); 

      } 
     } catch (JSONException e) { 
      // TODO Auto-generated catch block 
      Log.d("hello", ""); 
      e.printStackTrace(); 
     } 

     return null; 
    } 

    protected void onPostExecute(String result) { 
     super.onPostExecute(result); 
     if (pDialog.isShowing()) 
      pDialog.dismiss(); 
     printFriends(); 
    }; 

Я проверяю, что данные достоверны по printFriends() и хочу показать только данные «TAG_FULL_NAME» в виде списка. Моя инициализация ListView

View rootView = inflater.inflate(R.layout.tab_add_friends, container, 
      false); 
    lv = (ListView) rootView.findViewById(R.id.listView); 

Метод проверки данных и загрузки в ListView

public void printFriends() { 
    int len = FriendSearchList.size(); 

    for (int i = 0; i < len; i++) { 
     String f_name = FriendSearchList.get(i).get(TAG_FULL_NAME); 
     String u_name = FriendSearchList.get(i).get(TAG_USER_NAME); 
     String u_id = FriendSearchList.get(i).get(TAG_USER_ID); 

     Log.d("full_name", f_name); 
     Log.d("user_name", u_name); 
     Log.d("user_id", u_id); 
    } 


    ListAdapter adapter = new SimpleAdapter(getActivity(), 
      FriendSearchList, R.layout.tab_addfriend_list, 
      new String[] { TAG_FULL_NAME }, new int[] { R.id.full_name }); 

    setListAdapter(adapter); 

} 

tab_add_friends компоновки XML

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" > 

    <ListView 
     android:id="@android:id/list" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content"/> 

</LinearLayout> 

tab_addfriend_list XML макет

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:orientation="vertical" 
    android:padding="10dp" 
    android:paddingLeft="10dp" 
    android:paddingRight="10dp" > 

<!-- Name Label --> 

    <TextView 
     android:id="@+id/full_name" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:paddingBottom="2dip" 
     android:paddingTop="6dip" 
     android:textColor="#43bd00" 
     android:textSize="16sp" 
     android:textStyle="bold" /> 


</LinearLayout> 

Существует нет ошибка, показывающая, что ничего не отображается в списке. Требуется предложение или подсказка, чтобы избавиться от этой проблемы.

+0

Проверьте это: http://stackoverflow.com/questions/25375831/customarrayadapter-implementationunable-to-get-the-resource-id/25376257#25376257 и использовать HashMap вместо Класс пользователя. –

+0

Почему вы не используете пользовательский адаптер? или сделать класс MyUser и переопределить метод toString(), просто добавив «TAG_FULL_NAME» и добавив этот класс в arraylist – thegiga

+0

@GiGa thnx для предложения. Я думал, что он должен работать, но я также пытаюсь использовать другие способы. –

ответ

0

Проблема в том, что вы передаете Arraylist из HashMap, где SimpleAdapter не имеет понятия, какие данные должны помещать в макет элементов ListView.

Вы можете использовать это, чтобы реализовать элементы в вашем ListView

образец:

ListAdapter adapter = new SimpleAdapter(getActivity(), 
              FriendSearchList, R.layout.tab_addfriend_list, 
              new String[] { TAG_FULL_NAME }, new int[] { R.id.full_name }){ 
     @Override 
     public int getCount() { 
      return FriendSearchList.size(); 
     } 
     @Override 
     public View getView(int position,View convertView,ViewGroup parent) { 
      View v; 
      if(convertView == null) 
      { 
       v = getActivity().getLayoutInflater().inflate(R.layout.tab_addfriend_list, parent); 
       TextView tx = (TextView) v.findViewById(R.id.full_name); 
       tx.setText(FriendSearchList.get(i).get(TAG_FULL_NAME)); 
      } else 
       v = convertView; 

      return v; 
     } 
    }; 
0

У меня есть та же самая проблема когда проблема это вы подаете данные, используя простой адаптер, но вы можете раздувать rowView вне нити ui и кормить из выполнения post. thtas почему ваш взгляд не получает данные. на самом деле вам не нужно раздувать обзор строк, это код дыр для вас. Другое дело, что метод print friend также бесполезен, просто инициализируйте простой адаптер в методе onPostExecute().

`общественный класс MainActivity расширяет ListActivity {

private ProgressDialog pDialog; 


// URL to get contacts JSON 
private static String url = "http://api.androidhive.info/contacts/"; 

// JSON Node names 
private static final String TAG_CONTACTS = "contacts"; 
private static final String TAG_ID = "id"; 
private static final String TAG_NAME = "name"; 
private static final String TAG_EMAIL = "email"; 
private static final String TAG_ADDRESS = "address"; 
private static final String TAG_GENDER = "gender"; 
private static final String TAG_PHONE = "phone"; 
private static final String TAG_PHONE_MOBILE = "mobile"; 
private static final String TAG_PHONE_HOME = "home"; 
private static final String TAG_PHONE_OFFICE = "office"; 


private boolean isConnection = false; 

// contacts JSONArray 
JSONArray contacts = null; 

// Hashmap for ListView 
ArrayList<HashMap<String, String>> contactList; 

ArrayList<HashMap<String, String>> oflineContactList; 

private MyContactDataSource dataSource; 

List<Contatcs> oflineContatcs; 

// частная ListAdapter adapter1;

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



    dataSource = new MyContactDataSource(MainActivity.this); 
    dataSource.open(); 




    contactList = new ArrayList<HashMap<String,String>>(); 



    oflineContactList = dataSource.getContatcs(); 


    Log.i("data", oflineContactList.toString()); 
     ListView lv = getListView(); 

     ListAdapter adapter = new SimpleAdapter(
       MainActivity.this, oflineContactList, 
       R.layout.list_item, new String[] { TAG_NAME, TAG_EMAIL, 
         TAG_PHONE_MOBILE }, new int[] { R.id.email, 
         R.id.name, R.id.mobile }); 

     setListAdapter(adapter); 




    lv.setOnItemClickListener(new OnItemClickListener() { 



     @Override 
     public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, 
       long arg3) { 
      // getting values from selected ListItem 
      String name = ((TextView) arg1.findViewById(R.id.name)) 
        .getText().toString(); 
      String cost = ((TextView) arg1.findViewById(R.id.email)) 
        .getText().toString(); 
      String description = ((TextView) arg1.findViewById(R.id.mobile)) 
        .getText().toString(); 

      // Starting single contact activity 
      Intent intent = new Intent(MainActivity.this, SingleListItemActivity.class); 
      intent.putExtra(TAG_NAME, name); 
      intent.putExtra(TAG_EMAIL, cost); 
      intent.putExtra(TAG_PHONE_MOBILE, description); 

      startActivity(intent); 

     } 
    }); 

    new GetContacts().execute(); 


} 



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

    @Override 
    protected void onPreExecute() { 

     super.onPreExecute(); 
     pDialog = new ProgressDialog(MainActivity.this); 
     pDialog.setMessage("Data is loading...please wait..."); 
     pDialog.setCancelable(false); 
     pDialog.show(); 
    } 


    @Override 
    protected Void doInBackground(Void... params) { 
     // Creating service handler class instance 
     ServiceHandler mHandler = new ServiceHandler(); 


     // Making a request to url and getting response 
     String jsonStr = mHandler.makeServiceCall(url, ServiceHandler.GET); 

     Log.d("Response: ", "> " + jsonStr); 

     if(jsonStr != null){ 
      try { 
       JSONObject jsonObject = new JSONObject(jsonStr); 

       //Getting JSON Array node 
       contacts = jsonObject.getJSONArray(TAG_CONTACTS); 

       // looping through All Contacts 
       for (int i = 0; i < contacts.length(); i++) { 
        JSONObject c = contacts.getJSONObject(i); 

        String id = c.getString(TAG_ID); 
        String name = c.getString(TAG_NAME); 
        String email = c.getString(TAG_EMAIL); 
        String address = c.getString(TAG_ADDRESS); 
        String gender = c.getString(TAG_GENDER); 

       // Phone node is JSON Object 
        JSONObject phone = c.getJSONObject(TAG_PHONE); 
        String mobile = phone.getString(TAG_PHONE_MOBILE); 
        String home = phone.getString(TAG_PHONE_HOME); 
        String office = phone.getString(TAG_PHONE_OFFICE); 


       // tmp hashmap for single contact 
        HashMap<String, String> contact = new HashMap<String, String>(); 

       // adding each child node to HashMap key => value 
        contact.put(TAG_ID, id); 
        contact.put(TAG_NAME, name); 
        contact.put(TAG_EMAIL, email); 
        contact.put(TAG_PHONE_MOBILE, mobile); 

       // adding contact to contact list 
        contactList.add(contact); 

       } 
       dataSource.creareContacts(contactList); 
       dataSource.close(); 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 


     } 
     else { 
      Log.e("ServiceHandler", "Couldn't get any data from the url"); 
     } 
     return null; 
    } 


    @Override 
    protected void onPostExecute(Void result) { 

     super.onPostExecute(result); 

     // Dismiss the progress dialog 
     if(pDialog.isShowing()){ 
      pDialog.dismiss(); 
     } 

     /** 
     * Updating parsed JSON data into ListView 
     * */ 
     ListAdapter adapter = new SimpleAdapter(
       MainActivity.this, contactList, 
        R.layout.list_item, new String[] { TAG_NAME, TAG_EMAIL, 
          TAG_PHONE_MOBILE }, new int[] { R.id.name, 
          R.id.email, R.id.mobile }); 

     setListAdapter(adapter); 
    } 
} 

} `

+0

Спасибо, ваш код мне помог !. – Opriday

Смежные вопросы