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

Posted

技术标签:

【中文标题】交换活动时保存和加载联系人【英文标题】:Save and load Contacts when swapping Activities 【发布时间】:2015-10-23 09:05:47 【问题描述】:

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

我在做什么:我的 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;

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

共享参考:

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

【问题讨论】:

使用Sharedpreference 存储您当前的活动状态,使用onResume 从那里获取数据.. 【参考方案1】:

如果您想保存活动的状态,请使用 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);
 

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

【讨论】:

这应该在 MainActivity 中吗?因为我的 MainActivity 不知道名字和电话号码是什么: Intent ContactIntent = new Intent(this, ContactView.class); intent.putExtra("contactName", name); intent.putExtra("contactPhone", phoneNo); startActivity(ContactIntent);

以上是关于交换活动时保存和加载联系人的主要内容,如果未能解决你的问题,请参考以下文章

UITableView - 延迟加载联系人图片

像whatsapp一样加载联系人

按下指定的输入字段时打开联系人活动

在不启动接收活动的情况下将数据传递给活动 (Android)

在联系人活动打开时进入后台时退出应用程序

本地保存数据(IOS)