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

时间:2015-10-23 09:05:47

标签: java android save load contacts

嘿伙计们,也许有人可以帮助我:

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

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

这是我的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();
    }
}

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

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;
}

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

WITH SHAREDPREFERENCE:

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();
        }
    }

1 个答案:

答案 0 :(得分:1)

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

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

现在在您的onViewin ContactView中检查变量是否包含数据

 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);
 }

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