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.sicalculator;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.SeekBar;
public class SICalculatorActivity extends Activity implements SeekBar.OnSeekBarChangeListener{
public double years;
public TextView YT = (TextView) findViewById(R.id.Years);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sicalculator);
}
@Override
public void onProgressChanged (SeekBar seekBar,int i, boolean b){
years = i;
}
@Override
public void onStartTrackingTouch (SeekBar seekBar){
}
@Override
public void onStopTrackingTouch (SeekBar seekBar){
}
YT.setText(years + " Year(s)");
}
You've got a couple issues.
First, you can't do this here
Because the layout hasn't been inflated yet so you can't look for your
View
withtfindViewById()
. You can declare it therebut you need to initialize it after you call
setContentVie()
And you are trying to call
setText()
outside of a method. Move that to some method. But you can't do it inonCreate()
becauseYears
isn't given a value. So you probably want it somewhere else. Maybe inonProgressChanged()
.Also, to follow Java naming conventions, you should name your variables by starting with lower case (yt or yT and years).
Example XML
example activity class
So you need to add
inside onCreate method
statement must write onCreate() method.
This
YT = (TextView) findViewById(R.id.Years);
andYT.setText(years + " Year(s)");
must be moved into theonCreate()
methodSo, leave this
And initialize it here:
[EDIT]
If you want a dynamic change with the progress value: