简体   繁体   English

为什么此静态字段为null?

[英]Why is this static field null?

on android. 在android上。 my activity is like this. 我的活动就是这样。

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);

//other method,startservice()and so on. //其他方法,startservice()等。

and there is BroadcastReceiver to receive a flag from service. 并且存在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);

like this, in onReceiver, textview is null. 这样,在onReceiver中,textview为null。 as test, int aaa is'nt null. 作为测试,int aaa不为null。

why textview is null? 为什么textview为null?

EDIT Texttiew xml is 编辑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" />

And method in Activity using same textview.settext isnt null. 并且在Activity中使用相同textview.settext的方法不为null。 Thanks. 谢谢。

EDIT2 I can know i should save this variable. EDIT2我知道我应该保存此变量。 So, whats the best way to save VIEW variable? 那么,保存VIEW变量的最佳方法是什么? SharedPreferences seem not able to save VIEW variable. SharedPreferences似乎无法保存VIEW变量。

This thread indicates that having static fields might be a problem. 该线程指示具有静态字段可能是个问题。 In general, android kills your app.. and on return static variables may not be set. 通常,android会杀死您的应用程序。返回时可能不会设置静态变量。

static variable null when returning to the app 返回应用程序时,静态变量为null

This is likely that you are not referencing the correct textview element. 这很可能是您未引用正确的textview元素。 Double check your IDs in your layout file. 在布局文件中仔细检查您的ID。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM