为什么这个静态字段为空?

时间:2013-02-09 01:47:57

标签: java android nullpointerexception broadcastreceiver

在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。 作为测试,int aaa是'无效。

为什么textview为null?

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的Activity中的方法不为null。 感谢。

EDIT2 我知道我应该保存这个变量。 那么,什么是保存VIEW变量的最佳方法? SharedPreferences似乎无法保存VIEW变量。

2 个答案:

答案 0 :(得分:1)

此线程表示拥有静态字段可能是个问题。 通常,android会杀死你的应用..并且在返回静态变量时可能无法设置。

static variable null when returning to the app

答案 1 :(得分:0)

这可能是您没有引用正确的textview元素。仔细检查布局文件中的ID。

相关问题