Search code examples
javaandroidsettext

Android setText() Syntax Error On Tokens


Okay, I've got the makings of a really simple Android program here. I decided to start out with something simple but also relatively useful. Eventually, I hope to have an application that stores and displays study cards. I feel like not being able to get past a TextView is a bad omen. I've looked at several dozen examples and researched common problems new users have with setText(), but to no avail. Here are the relevant lines of code:

From my .java file:

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {

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

TextView tv1 = (TextView) findViewById(R.id.TextView1);
tv1.setText("New text");

.... and so on

Eclipse is marking the line containing "setText" and giving me the following syntactical errors:

Syntax error on token(s), misplaced construct(s) //underlining the period after tv1

Syntax error on token ""New text"", delete this token


Solution

  • Move the initialization of textview to onCreate.

    TextView tv1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    tv1 = (TextView) findViewById(R.id.TextView1); 
    // initialize after settting layout to activtiy
    tv1.setText("New text");
    // the above statement must be within a method 
    }
    

    Your initialization of textview is outside any method. You should initialize your textview only after setting the layout to the activity. So textview is initialized in onCreate. This tv1.setText("New text") statement must be within a method.

    Initializing your textview inside activity onCreate is better.