like the title says I\'m getting an error when trying to set a text view text from java in my android project, I can\'t see why.
package com.codeherenow.
You've got a couple issues.
First, you can't do this here
public TextView YT = (TextView) findViewById(R.id.Years);
Because the layout hasn't been inflated yet so you can't look for your View
witht findViewById()
. You can declare it there
public TextView YT;
but you need to initialize it after you call setContentVie()
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sicalculator);
//can't do it before that line ^
YT = (TextView) findViewById(R.id.Years);
}
And you are trying to call setText()
outside of a method. Move that to some method. But you can't do it in onCreate()
because Years
isn't given a value. So you probably want it somewhere else. Maybe in onProgressChanged()
.
Also, to follow Java naming conventions, you should name your variables by starting with lower case (yt or yT and years).
public TextView YT = (TextView) findViewById(R.id.Years);
statement must write onCreate() method.
This YT = (TextView) findViewById(R.id.Years);
and YT.setText(years + " Year(s)");
must be moved into the onCreate()
method
So, leave this
public TextView YT;
And initialize it here:
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.sicalculator);
YT = (TextView) findViewById(R.id.Years);
YT.setText(years + " Year(s)");
}
[EDIT]
If you want a dynamic change with the progress value:
@Override
public void onProgressChanged (SeekBar seekBar,int i, boolean b)
{
//years = i;
YT.setText(i + " Year(s)");
}
Example XML
<TextView
android:id="@+id/myAwesomeTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:text="Escriba el mensaje y luego clickee el canal a ser enviado"
android:textSize="20sp" />
example activity class
//in your OnCreate() method
TextView myAwesomeTextView = (TextView)findViewById(R.id.myAwesomeTextView);
myAwesomeTextView.setText("My Awesome Text");
So you need to add
YT = (TextView) findViewById(R.id.Years);
inside onCreate method