zanazaar zanazaar - 1 month ago 11
Android Question

TextView disappearing after updating using setText()

I have 3 classes: main, Sublist and editcrap.

For now i have 2 textviews separated by a Button in the Sublist xml file; and an EditText and a Button in my editcrap xml file.

What i wanted to do was take text input from the EditText in the editcrap activity, click the Button and return it to the Sublist activity and display it in the 1st textview of the Sublist xml file. I've done this using Intents and startActivityForResult() from the Sublist actvity.

The problem:

But after receiving data bak in the Sublist activity; after the "subject1.setText(newText);" code is executed...all i see in the Sublist activity in the emulator is the Button (that was supposed to be in between the 2 TextViews) and the TextView on the right. The left TextView vanishes. No error on emulator or nothin...just the TextView vanishes. I've been tryin to get around this but no luck. Could someone tell me wat i'm overlooking? :)

my code:

protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode)
{
case 1: if(resultCode==Activity.RESULT_OK)
{
String newText = data.getStringExtra("thetext");
subject1.setText(newText);
// this is where the textview supposed to update but
// instead vanishes entirely
}
break;
}
}

//second activity's code:

sub1 = (EditText) findViewById(R.id.peditText1);
final String theText = sub1.getText().toString();
parambutton1 = (Button) findViewById(R.id.parambutton1);

parambutton1.setOnClickListener(new View.OnClickListener() {

public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(editcrap.this, Sublist.class);

i.putExtra("thetext", theText);
setResult(Activity.RESULT_OK, i);
finish();

}
});
}


this is how the second activity returns the input text from the EditText.

Answer

Per the documentation, always use extra names prefixed with your package's name.

Ex: "com.example.thetext"

Example set result:

data.putExtra("com.example.thetext", yourstring);
setResult(Activity.RESULT_OK, data);

Example get result:

String newText = data.getStringExtra("com.example.thetext");
subject1.setText(newText); 

To avoid mistyping the extra field name, I use string resources so I can do getString(R.string.extra_thetext) which stores "com.example.thetext" for me so I don't mistype it later (isn't compile-time checking great?). But you can similarly use a constant :

static final String THE_TEXT = "com.example.thetext";