I know there's a couple of questions about this out there but I still don't get it. I have an activity
package test.example.om;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import test.example.om.Texter;
public class TextActivity extends Activity {
/** Called when the activity is first created. */
public String text="Helloo";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Texter myTexter = new Texter();
myTexter.textTexter();
}
public void textSet(){
TextView tv = (TextView) findViewById(R.id.myTextViewInXml);
tv.setText(text);
}
}
And a class Texter
package test.example.om;
import android.widget.TextView;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class Texter extends Activity{
String string="Helloo";
public void textTexter(){
TextView tv = (TextView) findViewById(R.id.myTextViewInXml);
tv.setText(string);
}
}
The LogCat is showing a NullPointerException and the app crashes. What am I doing wrong and how can I setText to the TextView from another class th开发者_开发百科an the main activity class?
You are instantiating an activity subclass and you're not supposed to do that... Also, you are trying to findViewById (in the Texter class) while your context is null, since you haven't gone through the correct Activity lifecycle.
In order to change the text of the text view, simply move the textTexter method from Texter to TextActivity and call it. Remove the Texter activity as it's unused.
package test.example.om;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import test.example.om.Texter;
public class TextActivity extends Activity {
/** Called when the activity is first created. */
public String text="Helloo";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = (TextView) findViewById(R.id.myTextViewInXml);
tv.setText(text);
}
}
EDIT: Just noticed you want to do it from another class. To do that, simply give a reference to the text view you want to change and setText on it
精彩评论