search
HomeJavajavaTutorialGlobal variables and local variables in Android

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
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools