setText doesn't set text

2019-09-17 09:59发布

问题:

I have a class that fetches som data from a website. I've followed TheNewBoston's tutorial (147-149 I think) and copied what he writes exactly, but it doesn't work for me. The problem is the setText. I try to switch tv.setText(returned) to tv.setText("Hello") but it doesn't change. Anyone know what's wrong?

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    TextView tv= (TextView) findViewById(R.id.text1);
    GetMethodEx test = new GetMethodEx();
    String returned;

    try {
        returned = test.getInternetData();
        tv.setText(returned);
    } catch (Exception e) {
        e.printStackTrace();
    }

}

回答1:

replace:

  try {
        returned = test.getInternetData();
        tv.setText(returned);
    } catch (Exception e) {
        e.printStackTrace();
    }

by

  try {
        returned = test.getInternetData();
        tv.setText("returned");
    } catch (Exception e) {
        e.printStackTrace();
        tv.setText(e.getMessage());
    }

setText will then set Text as you requested!



回答2:

Try this:

String returned = "some default string.";
try {
    returned = test.getInternetData();
} catch (Exception e) {
    e.printStackTrace();
}
tv.setText(returned);

This way, you know that setText will be called with data, regardless of if there was an exception.



回答3:

runOnUiThread(new Runnable()
            {

                public void run()
                {

                tv.setText(returned.toString());

                }
            });