在活动之间传递字符串

时间:2015-10-29 08:57:59

标签: java android string android-intent

Helllo Guys。

当我想从ContactView获取字符串到我的MainActivity时,我遇到了问题。

我尝试在ContactView中创建一个Intent,并在MainAcitivty中从此intent中检索数据。

我遇到的问题是,当我在ContactView中执行任何操作时,它会打开MainActivity:

我做的是:

ContactView.java

     //this is where the Activity gets opend right?
      Intent getContact = new Intent(this, MainActivity.class); 
      getContact.putExtra("Contact",phoneNo);
      startActivity(getContact);

这就是我要检索它的方法:

 Bundle extras = getIntent().getExtras();
 if (extras != null) {
     //this is where i should get the contact?
     String readContact= extras.getString("Contact")
 }

我的ContactView中有一个contactPicked方法,它为我提供了联系人姓名和电话号码,这就是我想要传递给我的MainActivity的内容,因为我有一个按钮,应该用来自ContactView的文本和联系人发送一个发送消息。

这是我的contactPicked方法:

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

我是否需要将意图放入我的方法中?虽然在我选择了联系人之后它会打开我的活动。

我错过了一些我无法找到的东西吗?

有人可以帮我吗?

###修改

这是我点击按钮来选择联系人:

public void onClick(View v) {
    Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
            ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
    startActivityForResult(contactPickerIntent, RESULT_PICK_CONTACT);
}

###编辑2

我的Activites的订单是ContactView(我选择联系人并显示它们)的MainActivity(MapView)

我仍然想要选择联系人并在我的ContactView中显示它们但是当我再次进入我的MainActivity时,我有一个按钮,它应该从ContactView获取字符串,并像发送短信一样对它们做些什么。

ContactView.java

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




@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);
    message = (TextView) findViewById(R.id.message);

    //speicher den aktuellen status der activity
    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;
        String msg=message.getText().toString();
        //String ResqMessage = 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 settings = getSharedPreferences("SelectedContact", MODE_PRIVATE);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString("contactName", name);
        editor.putString("contactPhone", phoneNo);
        editor.commit();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

3 个答案:

答案 0 :(得分:2)

其实你收到了错误的方式。查看您的代码,您不会通过MainActivity传递任何捆绑包,因此在通过联系之前无需致电getExtras()。您可以从MainActivity

执行以下操作
//start main
Intent getContact = new Intent(this, MainActivity.class); 
getContact.putExtra("Contact",phoneNo);
startActivity(getContact);
// In MainActivity onCreate
String contact = getIntent().getStringExtra("Contact");

答案 1 :(得分:0)

您是否在MainActivity中使用了startActivityForResult?

通常在第一个活动中调用startActivityForResult(..)并稍后在onActivityResult方法(在MainActivity中)处理结果。 为此,您必须通过setResult(intent i)在第二个Activity中设置结果。

你正在这样做吗?如果没有,搜索它或我可以给你一些代码..

答案 2 :(得分:0)

您应该使用此代码进行解析

  Intent intent = new Intent(this,FirstActivity.class);
    Bundle bundle = new Bundle();
    bundle.putString("data","value");
    intent.putExtras(bundle);
    startActivity(intent);

并且对于在SecondActivity中获取数据,请使用以下代码:

Bundle bundle = getIntent().
bundle.getString("data");