简体   繁体   中英

Change value of global variable crash android

i have the class MainActivity

    public class MainActivity extends Activity {
    int mVariable= ((Constant)getApplicationContext()).variable;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    Button count= (Button)findViewById(R.id.button1);
    final TextView tx = (TextView)findViewById(R.id.text);


     count.setOnClickListener(new View.OnClickListener(){    
        public void onClick(View v) {    
            mVariable ++;
            tx.setText(" "+mVariable);

               ....

and the Constant class

        public class Constant extends Application {
        public int variable=0;

           }

and this doesn't work ..i declare Constant in Manifest.

         <application
                      ...
          android:name=".Constant"/>

I want to set value by onClick like this code and change the value of a global variable.. thanks

You can make this variable as Static and access it in every other classes in your project like Constant.variable :

public class Constant extends Application {
        public static int variable = 0;

}

And

public class MainActivity extends Activity {
    ......
     tx.setText(" " + Constant.variable);
    .......

} 

And now the variable is available throughout the whole project by Constant.variable and when you change the variable 's value, it will be applied to all classes.

I don't now what actually happened inyour project but above is just a suggestion to your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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