Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I pass data via Intent?

I am trying to get the entered data from an activity. From my main screen, I kick off the activity like this:

Intent myIntent = new Intent(this, ContactInfo.class);
startActivityForResult(myIntent, AppState.ACTIVITY_CONTACT_INFO);

In the activity, upon the user tapping the Save button, I fire off the following:

Intent intent = new Intent();
TextView tvName = (TextView) findViewById(R.id.txtContactName);
intent.putExtra("Name", tvName.getText());

if (getParent() == null) {
    setResult(Activity.RESULT_OK, intent);
} else {
    getParent().setResult(Activity.RESULT_OK, intent);
}
finish();

In the original activity, I catch the onActivityResult event like this:

String contactName = (String) data.getExtras().get("Name");

However, this line blows up with java.lang.ClassCastException: android.text.SpannableString cannot be cast to java.lang.String. I've also tried getStringExtra with same results.

What am I missing?

like image 339
AngryHacker Avatar asked Dec 03 '22 03:12

AngryHacker


2 Answers

TextView.getText() doesn't return a string, but rather the SpannableString you see. Use getText().toString() instead.

like image 73
zmbq Avatar answered Dec 05 '22 17:12

zmbq


Had a similar problem, where the error appear, android.text.SpannableString cannot be cast to java.lang.String

It was because getText() needs to have a 'toString()' at the end. Without this 'toString()', it will crash on Android 4.x, but will work on Android 2.x.

ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
TextView viewTxt;  // Continue and complete this yourself.

String tmpStr = (String) viewTxt.getText().toString();
like image 20
Britc Avatar answered Dec 05 '22 16:12

Britc