交换活动时保存和加载联系人 [英] Save and load Contacts when swapping Activities

查看:45
本文介绍了交换活动时保存和加载联系人的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,也许你们中有人可以帮助我:

Hey guys maybe someone of you can help me:

我正在做什么:我的ContactView中有一个按钮,可让我选择一个电话联系人并将姓名和电话号码插入到textviews中.

What im doing: I have a button in my ContactView that lets me select a phonecontact and inserts name and phonenumber into textviews.

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

The Problem I have is that when i swap between MainActivity and ContactActivity the Contact is deleted and i need to select again a contact

这是我的ContactView代码

Here is my ContactView code

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:

This is the code within my MainAcitivty for the ContactButton that lets me go to 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;
}

是否可以检查我的意图数据是否为空?还是以某种方式保存字符串,只要它们不为空?

is there a way to check if my intent data is empty? or somehow save the strings as long they are not null?

具有共享偏好:

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

推荐答案

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

If you want to save the state of an activity use SharedPreferences

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

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

now in your onCreate of ContactView check if that variables contains data

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

希望这对您有所帮助.告诉我这是否可行!

I hope this helps you. Tell me if this works!

这篇关于交换活动时保存和加载联系人的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆