0

我有从 android 中的服务器获取电话联系的代码,我使用菜单项来制作它,这是我的代码

Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
            int row = cursor.getCount();
            friend_item = new MenuItem [row];
            //int i=0;

            while(cursor.moveToNext()){
                nama = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                phone = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            //  friend_item[i] = new MenuItem(nama,phone);
                //i++;
            }   

            cursor.moveToFirst(); 
            while(!cursor.isAfterLast()){
                Log.d("", "" + cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
                phone = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                phoneList.add(phone);
                cursor.moveToNext();
            }

            cursor.close();             

            String [] phonearray = (String[]) phoneList.toArray(new String[phoneList.size()]);          

        //  friendarray();
            String friends=phonearray[0]+"";   
            for(int a=1; a<phonearray.length; a++){
                friends = friends + ","+ phonearray[a];

            }

            Log.d("" , "" + friends);        
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("phone", mPhoneNumber));
                params.add(new BasicNameValuePair("friend", friends));

                // getting JSON string from URL
                JSONObject json = jParser.makeHttpRequest(Constants.url_phone_contact, "POST", params);

                // Check your log cat for JSON reponse
                Log.d("All Friend: ", json.toString());

                try {
                    friend = json.getJSONArray("friend");
                    friend_item = new MenuItem[friend.length()]; 
                     // looping through All Products
                    for (int a = 0; a < friend.length(); a++) {
                    JSONObject  c = friend.getJSONObject(a);  

                    //Storing each json item in variable

                    phone_friend= c.getString("phone"); 
                    id_friend = c.getString("id_ref");

                    Log.e("id_user", id_friend);  


                   namaFriend = getName(phone_friend);                                    

                   if(phone_friend == null){
                       Toast.makeText(getApplicationContext(), "contact not found", Toast.LENGTH_LONG).show();
                   }else{
                      friend_item[a] = new MenuItem(namaFriend, phone_friend);

                    // creating new HashMap   
                    HashMap<String, String> map1 = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    //map1.put("phone", mPhoneNumber);  
                    map1.put("id_ref", id_friend); 
                    map1.put("nama_friend", namaFriend);

                   // adding HashList to ArrayList
                    friendList.add(map1);

                   }
                    }

              } catch (JSONException e) {

              e.printStackTrace();

              }  
              //i++;*/    

             return null;               
        }       

     /**
         * After completing background task Dismiss the progress dialog
         * **/
     protected void onPostExecute(String file_url) {
            pDialog.dismiss();    
            if(friend_item != null && friend_item.length > 0){            

                mainlist.setAdapter(new ListMenuAdapter(friend_item));

            } else 
                Toast.makeText(getApplicationContext(), "You don't have friend using Shoop! yet, please invite them :)", Toast.LENGTH_LONG).show();
        }
    }

要从 android 设备获取名称,我使用此代码

private String getName(String number) {
        // define the columns I want the query to return
        String[] projection = new String[] {
                ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
                ContactsContract.CommonDataKinds.Phone.NUMBER};

        // encode the phone number and build the filter URI
        Uri contactUri = Uri.withAppendedPath(ContactsContract.CommonDataKinds.Phone.CONTENT_FILTER_URI, Uri.encode(number));

        // query time
        Cursor c = getContentResolver().query(contactUri, projection, null,
                null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME +" ASC");

        // if the query returns 1 or more results
        // return the first result
        if (c.moveToFirst()) {
            String name = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            return name;
        }

        // return the original number if no match was found
        return number;
    }

此列表菜单适配器

private class ListMenuAdapter extends BaseAdapter{

        private MenuItem [] item;

        protected ListMenuAdapter(MenuItem... item){
            this.item = item;
        }   

        public int getCount() {
            return item.length;
        } 

        public Object getItem(int pos) {
            return item[pos];
        }

        public long getItemId(int position) {
            return position;
        }

        public ViewGroup getViewGroup(int position, View view, ViewGroup parent){
            if(view instanceof ViewGroup){
                return (ViewGroup) view;
            }

            Context context = parent.getContext();
            LayoutInflater inflater = LayoutInflater.from(context);
            ViewGroup viewgroup = (ViewGroup)inflater.inflate(R.layout.custom_content_friend, null);

            return viewgroup;           
        }



        public View getView(int position, View convertView, ViewGroup parent) {

            ViewGroup group = getViewGroup(position, convertView, parent);
            MenuItem menu = item[position];

            TextView name = (TextView) group.findViewById(R.id.content_friend_myname);
            TextView phone  = (TextView) group.findViewById(R.id.content_friend_desc);

            if(menu.my_name == null || menu.phone == null){
                Toast.makeText(getApplicationContext(), "Contact not found", Toast.LENGTH_LONG).show();
            }else{      
            name.setText(menu.my_name);
            phone.setText(menu.phone);
            }

            return group;     
        }       
    }  

    private class MenuItem{

        private String my_name, phone;

        protected MenuItem(String my_name, String phone){
            this.my_name = my_name;
            this.phone= phone;
        }       

    }

现在,我想获得包含姓名和电话的列表视图,并按姓名升序排序,该怎么做?谢谢你的建议

4

2 回答 2

0

在你的活动课上写下:

public class MyActivity extends Activity {

    ....
    private ListView listView01;
    private ArrayList<MenuItem> list;

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

  //       ...
        listView01 = (ListView)findViewById(R.id.listView1);

        list=new ArrayList<MyActivity.MenuItem>();

  //    code to fill your ArrayList

        Collections.sort(list, myComparator);

        listView01.setAdapter(new ListMenuAdapter());
    }
       Comparator<MenuItem> myComparator = new Comparator<MenuItem>()
    {
            public int compare(MenuItem arg0,MenuItem arg1) 
            { 
                return arg0.my_name.compareTo(arg1.my_name);
            }

};
}
于 2012-11-26T09:14:36.960 回答
0

-首先使用一个ArrayList代替Array来存储将被适配器进一步使用的数据。

-用于根据姓名对姓名和电话(即联系人)java.util.Comparator<T>进行排序。

-用于Collections.sort(List<?> l , Comparator c)调用排序。

-notifyDataSetChanged()在使用适配器设置 ListView 后调用适配器。

例如:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

class Car {

    private String name;
    private String brand;
    private double cost;

    public Car(String name, String brand, double cost) {

        this.name = name;
        this.brand = brand;
        this.cost = cost;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public double getCost() {
        return cost;
    }

    public void setCost(double cost) {
        this.cost = cost;
    }

    public String toString() {

        return getName();
    }

}

public class Hog {

    ArrayList<Car> cars = new ArrayList<Car>();

    public void setIt() {

        cars.add(new Car("Padmini", "Fiat", 100008.00));
        cars.add(new Car("XYlo", "Mahindra", 100000.00));
        cars.add(new Car("Swift", "Maruti", 200000.00));
    }

    public void sortIt() {

        Collections.sort(cars, new NameComparator());
        System.out.println(cars);
        Collections.sort(cars, new BrandComparator());
        System.out.println(cars);
        Collections.sort(cars, new CostComparator());
        System.out.println(cars);
    }

    class NameComparator implements Comparator<Car> {

        public int compare(Car c1, Car c2) {

            return c1.getName().compareTo(c2.getName());
        }
    }

    class BrandComparator implements Comparator<Car> {

        public int compare(Car c1, Car c2) {

            return c1.getBrand().compareTo(c2.getBrand());
        }
    }

    class CostComparator implements Comparator<Car> {

        public int compare(Car c1, Car c2) {

            return new Double(c1.getCost()).compareTo(new Double(c2.getCost()));
        }
    }

    public static void main(String[] args) {

        Hog h = new Hog();

        h.setIt();
        h.sortIt();
    }

}
于 2012-11-26T09:15:04.197 回答