2013-02-09 54 views
1

在android上。 我的活動是這樣的。爲什麼這個靜態字段爲空?

public class MainActivity extends Activity { 

    static TextView textview; 
    static int aaa = 1; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    this.getWindow().setSoftInputMode(LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); 
    setContentView(R.layout.activity_main); 

      textview = (TextView)findViewById(R.id.textView6); 

//其他方法,startservice()等等。

並且有BroadcastReceiver從服務接收標誌。

 public static class Receiver extends BroadcastReceiver{ 

    @Override 
    public void onReceive(Context context, Intent intents) { 
     intents.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
     textview.setText("set")//throw null point 
        Log.d("aaa","aaa is" + aaa); 

像這樣,在onReceiver中,textview爲null。 as test,int aaa is'nt null。

爲什麼textview爲空?

EDIT Texttiew 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" 
    tools:context=".MainActivity" > 
<TextView 
     android:id="@+id/textView6" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_above="@+id/adview" 
     android:layout_alignParentLeft="true" 
     android:text="Large Text" 
     android:textAppearance="?android:attr/textAppearanceLarge" /> 

並且在活性的方法使用相同textview.settext心不是空。 謝謝。

EDIT2 我知道我應該保存這個變量。 那麼,什麼是保存VIEW變量的最佳方式? SharedPreferences似乎無法保存VIEW變量。

+0

您的佈局XML是什麼樣的? – 2013-02-09 01:51:08

回答

0

這很可能是因爲您沒有引用正確的textview元素。仔細檢查你的佈局文件中的ID。

1

此線程表示有靜態字段可能是一個問題。 一般來說,android殺死你的應用程序..並在返回靜態變量可能不會被設置。

static variable null when returning to the app

+0

我很想知道這個問題很快發生了嗎?也許在10秒內。 – user2027811 2013-02-09 02:35:49

+0

哦,,,我忘了即時通訊與VIEW.GONE使用webview。 – user2027811 2013-02-09 04:25:20