android - 将联系人姓名输入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();
}
}
}
}
}
解决方案
如果需要存储的数据类型不复杂,可以使用 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!
}
推荐阅读
- ruby-on-rails - 在 API 中呈现资源
- excel - Excel VBA:搜索文本并将其设为粗体并更改单元格颜色
- java - 有没有办法在没有 web.xml 的情况下创建自定义 404 页面?
- kubernetes - 设置 authentication-token-webhook-config-file
- python - 属于同一类别的多个列上的 OneHotEncoder
- c - 当我做这个任务时到底发生了什么
- excel - 将 MEDIAN 等函数应用于数组公式中的单个元素 - Excel
- c - GLib/GTK2 中的字符串列表
- uitableview - Xamarin Form:通过Button选择ViewCell数据
- groovy - 如何在 bonita 7.5 中将演员分配到车道?