-2
我试图通过使用setText()来更改我的TextView中的文本。Android更改TextView中的文本
当我尝试这样做,我得到以下错误:
E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{<bla bla bla>}: java.lang.NullPointerException
Caused by: java.lang.NullPointerException
at com.training.mytraining.test.MainActivity.display(MainActivity.java:35)
MainActivity.java
public class MainActivity extends AppCompatActivity {
TextView tvCountry;
private Server theServer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvCountry = (TextView) findViewById(R.id.countryTextView);
theServer = new Server(this);
theServer.weatherFromYahoo();
}
public void display() {
tvCountry.setText("USA");
}
}
Server.java
public class Server extends AppCompatActivity {
MainActivity theMainActivity;
//Constructor
public Server (Context context){
this.theMainActivity = new MainActivity();
}
public void weatherFromYahoo() {
theMainActivity.display();
}
}
activity_main.xml中
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
<TextView
android:id="@+id/countryTextView"
android:text="@string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
这仅仅是我真正的代码的例子。我并不想把所有的代码放在一起,所以我只是为了解决这个问题而编写了一个新的代码。我必须通过从另一个类中调用我的MainActivity来设置文本。
请帮助我,我一直呆在这里几个小时。
切勿通过其构造函数创建活动(例如'new MainActivity()')。 – CommonsWare
在这个例子中没有'MainActivity.java:35'。 –
可能的重复:http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it –