简体   繁体   中英

TextView.setText() not working

I have this piece of code...

class IncomingHandler extends Handler
{
    @Override
    public void handleMessage(Message message) 
    {

        String totalReceived = (String) message.obj;
        Log.i("TAG", "total received: " + totalReceived);
        totalTextView.setText("" + totalReceived);

        Log.i("TAG", (Looper.getMainLooper().getThread() == Thread.currentThread()) ? "UI thread" : "NOT UI thread");
        //Toast.makeText(MainActivity.this, "message received.", Toast.LENGTH_LONG).show();

    };
};

I run my app and it works just fine, but if i recreate the activity, for instance by changing the device orientation, the text will not be updated. Note that i do receive the messages and they are successfully printed by LogCat.

Also note that on my last log i try to determine if I am running on the main thread. If that check is correct, I am indeed running on the UI thread...

Any ideas on what i might be doing wrong?

Cheers, Alex

正如皮棉建议处理程序应该是静态的,使处理程序成为静态,并创建对活动的weakReference ,然后通过活动引用访问textview,我认为它应该可以工作

try to save instance add this

@Override
protected void onSaveInstanceState(Bundle outState) {
State s = new State(yourTextView.getText().toString());
outState.putSerializable(State.STATE, s);
super.onSaveInstanceState(outState);
 }
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
State s = (State) savedInstanceState.getSerializable(State.STATE);
yourTextView.setText(s.getYourTextViewText());
 }

Your problem is that totalTextView is still pointing to the TextView of the (now destroyed) previous activity.

If class IncomingHandler is a sub-class of Activity, it should be an easy job to make sure that during onCreate() you make sure to update it with totalTextView = (TextView)findViewById(R.id.__/* something */__);

If the handler is not a sub-class of Activity, well, maybe it should be, or you should look into some more Android-Framework-High-Level stuff to update and call back the Activity (eg Loaders or UI-less fragments with setRetainInstance(true); )

ps.: some users will tell you to just override the destruction of the Activity by putting configChanged in the manifest. Although it might work at first moment, it's a poor quick fix, it's an unadvisable pattern that usually will lead to bigger problems in the future.

from: http://developer.android.com/guide/topics/manifest/activity-element.html#config

Note: Using this attribute should be avoided and used only as a last-resort. Please read Handling Runtime Changes for more information about how to properly handle a restart due to a configuration change.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM