Domanda

So I know that this question has come up before, but I cannot find what is going wrong with my code. I have a TextView that I want to update and a Button that I want to make invisible just so I can see that it is working. In my onCreate I have:

setMessage("Welcome, " + pref.getString("fName", "User"));

which calls to the method I created:

private void setMessage(final String input)
{
    this.input = input;
    runOnUiThread(new Runnable()
    {
    @Override
    public void run() {
            message.setText(input);
            create.setVisibility(4);
        }
    });
    Toast.makeText(this, input, Toast.LENGTH_LONG).show();
}

The toast is just so that I can see that the string comes out correctly, and it does. I get no crashes, no errors in the log, nothing. The Textview is set to a string in my Strings.xml that says "Hello World!" and after the activity starts it reads that message, but the button is still visible and the message that comes up for toast doesn't come up. What am I doing wrong? Input is a String by the way.

My variables:

private TextView message;
private Button create;
private SharedPreferences pref;
private int norecurs = 0;
private Bundle state;
private Handler handler;
private String input;

All my code in onCreate() that wasn't there before:

pref = getSharedPreferences("login", 0);
    message = (TextView) findViewById(R.id.message);
    create = (Button) findViewById(R.id.button1);
    input = "Welcome, " + pref.getString("fName", "User");
    setMessage("Welcome, " + pref.getString("fName", "User"));
È stato utile?

Soluzione

This doesn't really seem like you need to create a new thread to be honest. Instead of:

pref = getSharedPreferences("login", 0);
message = (TextView) findViewById(R.id.message);
create = (Button) findViewById(R.id.button1);
input = "Welcome, " + pref.getString("fName", "User");
setMessage("Welcome, " + pref.getString("fName", "User"));

You should write:

pref = getSharedPreferences("login", 0);
message = (TextView) findViewById(R.id.message);
create = (Button) findViewById(R.id.button1);
input = "Welcome, " + pref.getString("fName", "User");

// Just set the text in your onCreate
message.setText("Welcome, " + pref.getString("fName", "User"));

If, however, you really want to keep the setMessage method, just change it to this:

private void setMessage(String input)
{
    this.input = input;

    message.setText(input);
    create.setVisibility(4);

    Toast.makeText(this, input, Toast.LENGTH_LONG).show();
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top