2015-10-14 74 views
-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來設置文本。

請幫助我,我一直呆在這裏幾個小時。

+3

切勿通過其構造函數創建活動(例如'new MainActivity()')。 – CommonsWare

+0

在這個例子中沒有'MainActivity.java:35'。 –

+0

可能的重複:http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it –

回答

0

更改此:

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

要這樣:

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

從而使的onCreate被稱爲仍然正確。如果您正在進行一項活動,則無法正確設置視圖並遵循正確的生命週期。正如@CommonsWare所說,你不應該通過它的構造函數創建一個活動。