首页 > 解决方案 > 将联系人姓名输入android应用程序并保存

问题描述

在我的 Android 应用程序中,我想访问设备中的联系人并选择其中一个并将它们存储在应用程序中以通过语音命令发送消息。我已经成功选择了联系人并发送了消息,但我有一个问题,当我退出应用程序时,联系人被清除,我每次去应用程序时都必须选择它......我可以将它存储在应用程序中并保留它总是?我怎样才能做到这一点?

此代码允许访问联系人并选择一个。

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode==PICK_CONTACT){
        if(resultCode== Activity.RESULT_OK){
            Uri contactData=data.getData();
            Cursor cursor=getContentResolver().query(contactData,null,null,null,null);
            if(cursor.moveToFirst()){
                String name=cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
                nameset.setText(name);
                String con_id=cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                int has_phone=Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
                if(has_phone>0){
                    Cursor phoneCursor= getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=?", new String[] {con_id}, null);

                    if(phoneCursor.moveToFirst()){
                        String phone_number=phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        number.setText(phone_number);
                    }
                    phoneCursor.close();
                }
            }


        }
    }
}

标签: android

解决方案


如果需要存储的数据类型不复杂,可以使用 SharedPreferences。

public void SaveData(){
    SharedPreferences preferences = getSharedPreferences("phone_data", MODE_PRIVATE);
    // get the editor
    SharedPreferences.Editor editor = preferences.edit();
    // store the data in different type
    editor.putString("name", userName);
    editor.putString("phone", phoneNumber);
    // save the data
    editor.apply();
}

public void LoadData(){
    SharedPreferences preferences = getSharedPreferences("phone_data", MODE_PRIVATE);
    userName = preferences.getString("name", "");
    userPhone = preferences.getString("phoneNumber", "");
    // do whatever you want with your data now!
}

推荐阅读