android - 访问函数外部的全局值

标签 android function global-variables oncreate

我正在尝试在函数中设置一个值(全局)并在android中的“On create()”函数外部访问它 我尝试将全局变量设为静态,甚至尝试将其写入“编辑文本”并在“on create()”中解析它。但它一直初始化为0.0(变量是double类型) 当我尝试在“on create()”中访问时,

哦,我无法返回该值,因为该函数太嵌套,因此所有层次结构都太复杂。 :(

谁能帮我解决这个问题;

    public class TryActivity extends Activity
    {
        double BAT;\\ global value
     public void onCreate(Bundle savedInstanceState)
            {      
        disp(); // calling the function disp to set the value to BAT                
        String To_string=Double.toString(BAT);    
            System.out.println("Current Battery level  ==="+To_string); \\ prints 0.0 the wrong value
        super.onCreate(savedInstanceState);
            setContentView(R.layout.main); 
           }


     public void disp(){            
        this.registerReceiver(this.batteryInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));               
        }



        private BroadcastReceiver batteryInfoReceiver = new BroadcastReceiver(){                
        public void onReceive(Context context, Intent intent){                  
        double  level= intent.getIntExtra(BatteryManager.EXTRA_LEVEL,0);
        BAT=level;
            Textview1 = (EditText) findViewById(R.id.Textview1);
            Textview1.setText(Double.toString(BAT));      // sets the correct value
            System.out.println("bbbattererrerey 1 "+Double.toString(BAT));   //prints the correct value
        }        
    };
}

最佳答案

只需在类中将变量全局初始化为 public static 即可。您将能够从任何地方访问它。

关于android - 访问函数外部的全局值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21487815/

相关文章:

c - 功能参数差异

function - 当前类方法名称为字符串

javascript - javascript中获取内部函数的返回值

python - 如何定义通过另一个函数内的 for 循环创建的全局变量?

python - Python:变量似乎没有在while循环中重新分配+分配前引用的局部变量

android - 在 Android Studio 项目上运行 gifImageView

java - 安卓,http : How to upload a file to a site hosted by a shared server?

安卓 :How can i check whether GPS is working in my android device or not?

php - 为什么 WordPress 仍然使用 addlashes()、register_globals() 和 magic_quotes?

android - Android Studio src/res/layout子文件夹错误