Home  >  Article  >  Java  >  Global variables and local variables in Android

Global variables and local variables in Android

伊谢尔伦
伊谢尔伦Original
2017-01-23 13:16:171394browse

Global variables, as the name implies, are variables that can be called in the entire class or in multiple functions. Also called external variables. Local variables are variables that can be accessed within a specific procedure or function. It is very easy to declare a variable, but when it comes to using it, it is not as simple as imagined. As for me, I often define global variables for use, but just because of this, I define global variables. It also spared a lot of twists and turns.

Global variables and local variables in Android

When using Adapter, usually the adapter is always used with listView, because a listView basically has a layout of listView's Items. The following scenario is: There will be an ImageView in each Item. When I click on an item, I need to change the background color of the ImageView of the Item or change it to another background image. A situation that may occur at this time is something you clearly pointed out. In the first article, you will find that the pictures in the third or second article have also changed. This is because you define a global variable. The code part is as follows:

public class  Adapter extends BaseAdapter {
private ImageView img;

  public View getView(int position, View convertView, ViewGroup parent) {
  convertView = mInflater.inflate(R.layout.group_listview_item,null);
  img = (ImageView) convertView.findViewById(R.id.logo);

  return convertView;

  }
}

In the above part, ImageView is a global variable. At this time, we need to define ImageView as a local variable,

 public class  Adapter extends BaseAdapter {
 public View getView(int position, View convertView, ViewGroup parent) {
     convertView = mInflater.inflate(R.layout.group_listview_item,null);
     ImageView  img = (ImageView) convertView.findViewById(R.id.logo);
    return convertView;
  } 
}

At this time, it represents the ImageView in each Item. Another situation is that when making a shopping cart, you can click the plus or minus icon to change the number of items in the shopping cart. When you define the quantity num, it must also be defined as a local variable. It would be better if you can use ViewHolder.

Static modified static variables are very convenient to use. They can be used in different classes and packages and occupy separate memory in the virtual machine. Yes, these are their advantages, but after the project is launched , only to find that static has some disadvantages.

When checking the crash information of the project, I found that there were inexplicable null pointer exception errors in many places. After investigation, I found that it may be a static problem. In the project, we saved the user's information, that is, the User object, into a static variable, and in the places where errors were reported, we found that this variable was used. Therefore, we can roughly infer that there is a certain relationship with this way of saving. contact. At the same time, many users have reported that when the application is opened, after answering a phone call or waiting for a long time, the application will crash when they return to the application. These crashes are related to the null pointer of static variables.

In this case, is static modification very dangerous in Android development? Perhaps we can say that if it is defined as static User u = new User();, then there should not be much of a problem, but if it is defined as static User u;, then NULL is likely to occur. Of course, the properties in the previous method may also be empty, but this can be encapsulated to avoid null pointers. In addition, static constants are still very useful.

So how should we save login or global information? According to the official recommendations of Google and the recommendations of experts from Baidu, we should try to use custom classes inherited from Application, define variables that need to be used globally in the classes we inherit, and obtain and save relevant variables through getApplicationContext() Just variables.

 /** 
     * 自定义的MyApplication继承Application 
     *  
     * @author way 
     *  
     */  
    public class MyApplication extends Application {  
        /** 
         * 引发异常:在一些不规范的代码中经常看到Activity或者是Service当中定义许多静态成员属性。这样做可能会造成许多莫名其妙的 null 
         * pointer异常。 
         */  
      
        /** 
         * 异常分析:Java虚拟机的垃圾回收机制会主动回收没有被引用的对象或属性。在内存不足时,虚拟机会主动回收处于后台的Activity或 
         * Service所占用的内存。当应用再次去调用静态属性或对象的时候,就会造成null pointer异常 
         */  
      
        /** 
         * 解决异常:Application在整个应用中,只要进程存在,Application的静态成员变量就不会被回收,不会造成null pointer异常 
         */  
        private int number;  
      
        @Override  
        public void onCreate() {  
            // TODO Auto-generated method stub  
            super.onCreate();  
        }  
      
        public int getNumber() {  
            return number;  
        }  
      
        public void setNumber(int number) {  
            this.number = number;  
        }  
    }

However, in order for our MyApplication to replace android.app.Application and take effect in our code, we need to modify AndroidManifest.xml:

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

Below we can Or flexibly used in Service:

MyApplication application = (MyApplication) this.getApplicationContext();   
    //保存变量  
    application.setNumber(5);  
    //取出变量  
    application.getNumber();

Application exists at the same time as the application, that is, the application is there and will not be inexplicably recycled by the GC. Therefore, it is safer to use this method.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn