交换活动时保存和加载联系人

Save and load Contacts when swapping Activities

大家好,也许你们中有人可以帮助我:

我在做什么:我的 ContactView 中有一个按钮,可以让我 select 电话联系人并将姓名和电话号码插入文本视图。

我遇到的问题是,当我在 MainActivity 和 ContactActivity 之间切换时,联系人被删除,我需要再次 select 一个联系人

这是我的 ContactView 代码

public class ContactView extends AppCompatActivity {
    private static final int RESULT_PICK_CONTACT = 85;
    private TextView textView1;
    private TextView textView2;
    private EditText editText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contact_view);
        textView1 = (TextView) findViewById(R.id.TxtName);
        textView2 = (TextView) findViewById(R.id.TxtNumber);
        editText = (EditText) findViewById(R.id.editText);
    }

    public void onClick(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 startActivityForReslut
            switch (requestCode) {
                case RESULT_PICK_CONTACT:
                    contactPicked(data);
                    break;
            }
        } else {
        Log.e("ContactView", "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 name = 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);
        name = cursor.getString(nameIndex);
        // Set the value to the textviews
        textView1.setText(name);
        textView2.setText(phoneNo);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

这是让我转到 ContactView 的 ContactButton 的 MainAcitivty 中的代码:

public boolean onOptionsItemSelected(MenuItem item){
    int id = item.getItemId();
    if(id == R.id.action_contactView)
    {
        Intent ContactIntent = new Intent(this, ContactView.class);
        startActivity(ContactIntent);

    }
    return true;
}

有没有办法检查我的意图数据是否为空?或者只要它们不为空就以某种方式保存字符串?

具有共享偏好:

public class ContactView extends AppCompatActivity {
    private static final int RESULT_PICK_CONTACT = 85;
    private TextView textView1;
    private TextView textView2;
    private EditText editText;
    public SharedPreferences settings = getSharedPreferences("SelectedContact", MODE_PRIVATE);


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contact_view);
        textView1 = (TextView) findViewById(R.id.TxtName);
        textView2 = (TextView) findViewById(R.id.TxtNumber);
        editText = (EditText) findViewById(R.id.editText);

        SharedPreferences settings = getSharedPreferences("SelectedContact", MODE_PRIVATE);
        String name = settings.getString("contactName", "");//the second parameter set a default data if “contactName” is empty
        if (!name.isEmpty()){
            textView1.setText(name);
        }
        String phoneNo = settings.getString("contactPhone", "");//the second parameter set a default data if “contactName” is empty
        if (!phoneNo.isEmpty()){
            textView2.setText(phoneNo);
        }
    }

    public void onClick(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 startActivityForReslut
            switch (requestCode) {
                case RESULT_PICK_CONTACT:
                    contactPicked(data);
                    break;
            }
        } else {
            Log.e("ContactView", "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 name = 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);
            name = cursor.getString(nameIndex);
            // Set the value to the textviews
            textView1.setText(name);
            textView2.setText(phoneNo);
            SharedPreferences.Editor editor = settings.edit();
            editor.putString("contactName",name );
            editor.putString("contactPhone", phoneNo);
            editor.commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

如果要保存 activity 的状态,请使用 SharedPreferences

SharedPreferences settings = getSharedPreferences("SelectedContact", MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString(“contactName”,name );
editor.putString(“contactPhone”,phoneNo);
editor.commit();

现在在 ContactView 的 onCreate 中检查该变量是否包含数据

 SharedPreferences settings = getSharedPreferences(“SelectedContact”, MODE_PRIVATE);
 String name = settings.getString(“contactName”, “”);//the second parameter set a default data if “contactName” is empty
 if (!name.isEmpty()){
    yourEditText.setText(name);
 }

希望对您有所帮助。 告诉我这是否有效!