Android 更改 TextView 中的文本

Android Change text in TextView

我正在尝试使用 setText() 更改我的 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" />

这只是我真实代码的一个例子。我不想把所有的代码都放在一起,所以我用我遇到的那个问题制作了一个新代码。我必须通过从另一个 class.

调用我的 MainActivity 来设置文本

请帮助我,我被困在这里好几个小时了。

改变这个:

public Server (Context context){
    this.theMainActivity = new MainActivity();
}

为此:

public Server (Context context){
    this.theMainActivity = (MainActivity)context;
}

这样 onCreate 仍然可以正常调用。如果您正在新建 activity,它将无法正确设置视图并遵循正确的生命周期。正如@CommonsWare 所说,您不应该通过其构造函数创建 activity。