我已经从我的应用访问了联系人,但我知道如何将两个textview保存到共享的首选项。代码运行正常,但我无法将其存储到共享的首选项。
contact.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
pickContact(null);
String a = tvCname.getText().toString();
String b = tvCnum.getText().toString();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = prefs.edit();
editor.putString("Name",a);
editor.putString("Phone Number",b);
editor.commit();
Toast.makeText(MainActivity.this,"added",Toast.LENGTH_LONG).show();
}
});
这是访问手机中联系人的代码。
public void pickContact(View v)
{
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(contactPickerIntent, RESULT_PICK_CONTACT);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// check whether the result is ok
if (resultCode == RESULT_OK) {
// Check for the request code, we might be usign multiple startActivityForResult
switch (requestCode) {
case RESULT_PICK_CONTACT:
contactPicked(data);
//test
break;
case 99:
Intent intentReceived = data;
String strName = intentReceived.getStringExtra("name");
String strBT = intentReceived.getStringExtra("bloodType");
String strNum = intentReceived.getStringExtra("number");
String strAddress = intentReceived.getStringExtra("address");
String strOther = intentReceived.getStringExtra("other");
tvName.setText(strName);
tvBg.setText(strBT);
tvNum.setText(strNum);
tvAddress.setText(strAddress);
tvOther.setText(strOther);
Toast.makeText(this,"Profile added",Toast.LENGTH_LONG).show();
break;
}
} else {
Log.e("MainActivity", "Failed to pick contact");
}
}
/**
* Query the Uri and read contact details. Handle the picked contact data.
* @param data
*/
private void contactPicked(Intent data) {
Cursor cursor = null;
try {
String phoneNo = null ;
String cName = null;
// getData() method will have the Content Uri of the selected contact
Uri uri = data.getData();
//Query the content uri
cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
// column index of the phone number
int phoneIndex =cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
// column index of the contact name
int nameIndex =cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
phoneNo = cursor.getString(phoneIndex);
cName = cursor.getString(nameIndex);
// Set the value to the textviews
tvCname.setText(phoneNo);
tvCnum.setText(cName);
} catch (Exception e) {
e.printStackTrace();
}
}
答案 0 :(得分:0)
将值保存到SharedPreferences
b'\x14'
要获得此值
SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE); //MyPREFERENCES is a string for find your SharedPreferences
Editor editor = sharedpreferences.edit();
editor.putString("key1", "value1");
editor.putString("key1", "value1");
editor.commit();