Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
212 views
in Technique[技术] by (71.8m points)

java - Save and load Contacts when swapping Activities

Hey guys maybe someone of you can help me:

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

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

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

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?

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();
        }
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...