1

你好我有这个代码(粘贴在下面),它读取并显示电话联系人ListView。除此之外,它还应该具有更多功能,即它应该能够在将联系人读取到 xml 文件时将其写入。我想将该 xml 存储在我的 SD 卡中。请检查下面的代码。

public class ContactsListActivity extends Activity implements
OnItemClickListener
{
    private ListView listView;
    private List<ContactBean> list = new ArrayList<ContactBean>();
    XmlSerializer serializer = Xml.newSerializer();

    File newxmlfile = new File(Environment.getExternalStorageDirectory()+"/new.xml");




    @SuppressWarnings("deprecation")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contacts);

        listView = (ListView) findViewById(R.id.list);
        listView.setOnItemClickListener(this);

        try{
            newxmlfile.createNewFile();
        }catch(IOException e){
            Log.e("IOException", "exception in createNewFile() method");
        }
    //we have to bind the new file with a FileOutputStream
    FileOutputStream fileos = null;         
    try{
        fileos = new FileOutputStream(newxmlfile);
    }catch(FileNotFoundException e){
        Log.e("FileNotFoundException", "can't create FileOutputStream");
    }




        Cursor phones = getContentResolver().query(
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
                null, null);
        //we set the FileOutputStream as output for the serializer, using UTF-8 encoding
        try {
            serializer.setOutput(fileos, "UTF-8");
            //Write <?xml declaration with encoding (if encoding not null) and standalone flag (if standalone not null) 
            serializer.startDocument(null, Boolean.valueOf(true));
        } catch (IllegalArgumentException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IllegalStateException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } 
        while (phones.moveToNext()) {

            String name = phones
                    .getString(phones
                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));

            String phoneNumber = phones
                    .getString(phones
                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

            ContactBean objContact = new ContactBean();
            objContact.setName(name);
            objContact.setPhoneNo(phoneNumber);
            list.add(objContact);




            //create a new file called "new.xml" in the SD card

            //we create a XmlSerializer in order to write xml data

            try {

                //set indentation option
            //  serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true); 
                //start a tag called "root"
                serializer.startTag(null, name); 
                //i indent code just to have a view similar to xml-tree
                    serializer.startTag(null, "name");
                    serializer.text(name);
                    serializer.endTag(null, "name");

                    serializer.startTag(null, "phonenumber");
                    serializer.text(phoneNumber);
                    serializer.endTag(null, "phonenumber");

                serializer.endTag(null, name);

                //write xml data into the FileOutputStream
                serializer.flush();
            //finally we close the file stream
                fileos.close();





            } catch (Exception e) {
                Log.e("Exception","error occurred while creating xml file");



        }
            try {
                //write xml data into the FileOutputStream
            //  serializer.flush();
            //finally we close the file stream
            //  fileos.close();
                serializer.endDocument();
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        phones.close();

        ContactAdapter objAdapter = new ContactAdapter(
                ContactsListActivity.this, R.layout.alluser_row, list);
        listView.setAdapter(objAdapter);

        if (null != list && list.size() != 0) {
            Collections.sort(list, new Comparator<ContactBean>() {

                @Override
                public int compare(ContactBean lhs, ContactBean rhs) {
                    return lhs.getName().compareTo(rhs.getName());
                }
            });
            AlertDialog alert = new AlertDialog.Builder(
                    ContactsListActivity.this).create();
            alert.setTitle("");

            alert.setMessage(list.size() + " Contact Found!!!");

            alert.setButton("OK", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            alert.show();

        } else {
            showToast("No Contact Found!!!");
        }


    }

    private void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onItemClick(AdapterView<?> listview, View v, int position,
            long id) {
        ContactBean bean = (ContactBean) listview.getItemAtPosition(position);
        showCallDialog(bean.getName(), bean.getPhoneNo());
    }

    @SuppressWarnings("deprecation")
    private void showCallDialog(String name, final String phoneNo) {
        AlertDialog alert = new AlertDialog.Builder(ContactsListActivity.this)
                .create();
        alert.setTitle("Call?");

        alert.setMessage("Are you sure want to call " + name + " ?");

        alert.setButton("No", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        alert.setButton2("Yes", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                String phoneNumber = "tel:" + phoneNo;
                Intent intent = new Intent(Intent.ACTION_CALL, Uri
                        .parse(phoneNumber));
                startActivity(intent);
            }
        });
        alert.show();
    }
}

我从互联网上得到了这段代码,它有一个缺陷。只有最后一个读取的联系人被添加到我的 sd 卡上的 xml 文件中。当我调试代码时,它显示正确遍历代码和所有联系人。

我想将所有读取的联系人添加到正在存储的 xml 文件中。非常感谢此代码中的任何帮助或更正。提前致谢。

4

0 回答 0