SoFunction
Updated on 2025-04-09

Android: How to write a "universal" activity

Preface

I have been developing my own android for a while. Whenever I think back to the code I wrote when I was a beginner, I feel the urge to swear myself, and the code is too bad. Therefore, I thought about summing up the unreasonable parts of the previous code, hoping to help beginners. I hope this is a series of articles.

Contents of this section

What does a "universal" activity look like, and what are the disadvantages of "universal" activity?

Start writing "universal" activities

As a beginner, there may be many friends who write Activity very "versatile", of course it is not better. Then I will take a login module as an example to illustrate how a "universal" activity was generated. Most of the following codes are pseudo-code.

To write the activity_login.xml file, here is a simple pseudo-code:

 One entered the user account number EditText
 A password entered EditText
 A login button Button

Write LoginActivity. LoginActivity contains the function of initializing the views in activity_login.xml, and also includes the function of adding a listener to the login button. Let's see the key code snippets below

 public LoginActivity extends Activity{
  private EditText mUserNameView, mPasswordView;
  private Button mLoginView;
  //This method will be called by the onCreate method  public void initViews(){
   .......
   VariousfindViewById.....Code
   //Add a listener to the login button   (new () { 
   @Override 
    public void onClick(View v) { 
   }
   });
  }
 }

Is the code in LoginActivity still very refreshing and clean? It only does UI-related work.

LoginActivity with Verification

Then, you need to implement the function of verifying the account and whether the password is valid in the login button listener method, and continue to improve the code

 (new () { 
  @Override 
  public void onClick(View v) {
  String userName = ();
  String password = ();
   //Verify the user name entered by the user and whether the password is legal  if(!validate(userName) || !validate(password)){
   Tell the user that the username or password entered is illegal,And do some other work
   }
  }
 });
 //Verify whether the given string is legal, true is legal, false is illegal private boolean validate(String str){

 }

Now that LoginActivity has business code, it is time for us to implement the login function.

LoginActivity with login function

Add login function to the listener

 (new () { 
  @Override 
  public void onClick(View v) {
  Verify the user name entered by the user,Is the password legal?...
  if(All are legal){
   //Start login   login(userName,password);
  }
  }
 });
 //Login method, use pseudo-code to write down network request private void login(String userName,String password){
  ().login(userName,password,
   new ResponseListener(){
    public void failed(Failed failed){
     Do failure-related processing,For example, give users a prompt
     Clear the password input box,For example, the number of login limits, etc.
    }
    public void success(Response response){
     Analyze the data,Jump toappHome page or other interface
    }
   });
 }

LoginActivity with data parsing and storage functions

After I completed the login function, the product raised new requirements. After the user login successfully, the user-related data needs to be returned and saved. There is no way, you can only do it as required, but luckily the requirement is very simple, you just need to modify the successful login method and it is OK.

 public void success(Response response){ 
  Do successful related processing
  //Currently call the user information class UserInfo, parse the data from json, assuming that () exists  String jsonContent = ();
  JsonObject jsonObject = new JsonObject(jsonContent);
  UserInfo userInfo = new UserInfo();
   = ("name");
   = ("userId");
  Analysis of other fields......
  //Save userInfo information into the data table, assuming that userDatabase already exists  (userInfo);
  Jump toappHome page
 }

At this point, the login function has been developed, and the last code of LoginActivity is like this

 public LoginActivity extends Activity{
  private EditText mUserNameView, mPasswordView;
  private Button mLoginView;
  public void initViews(){
   .......
   VariousfindViewById.....Code
   //Add a listener to the login button   (new () { 
   @Override 
    public void onClick(View v) { 
    String userName = ();
    String password = ();
    //Verify whether the password entered by the user is legal    if(!validate(userName) || !validate(password)){
     Tell the user that the username or password entered is illegal
    } else{
     //Start login     login(userName,password);
    }
   }
   });
  }
  //Login method, use pseudo-code to write down network request  private void login(String userName,String password){
  ().login(userName,password,
   new ResponseListener(){
    public void failed(Failed failed){
     Do failure-related processing,For example, give users a prompt
     Clear the password input box,For example, the number of login limits, etc.
    }
    public void success(Response response){
     Do successful related processing
     //Currently call the user information class UserInfo, parse the data from json, assuming that () exists     String jsonContent = ();
     JsonObject jsonObject = new JsonObject(jsonContent);
     UserInfo userInfo = new UserInfo();
      = ("name");
      = ("userId");
     Analysis of other fields......
     //Save userInfo information into the data table, assuming that userDatabase already exists     (userInfo);

     Jump toappHome page
    }
   });
  }
  //Verify whether the given string is legal, true is legal, false is illegal  private boolean validate(String str){
  }
 }

The login module function has been developed here. LoginActivity has changed from the beginning to the refreshing and clean code that only cares about U, and has become the current "universal" Activity. What has LoginActivity done:

  • Handle UI
  • Process username and password legality verification services
  • Process data analysis, data storage

Of course, you will say that the current LoginActivity code is only about 100 lines, and it is still easy to modify it. However, with the growth of the business, who can guarantee that the LoginActivity code will not increase or contain more business codes. LoginActivity is just a microcosm of the "universal" Activity.

Universal is a good thing, but it depends on how universal is achieved. If it is to disperse many small functions into their respective classes, and then the universal class combines these small classes together, the universal class is the omnipotent of real materials. If you make this class become "universal" by putting many small functions in one class, this "universal" is not good.

Disadvantages of "universal" Activity

I'll summarize the shortcomings of "universal" Activity

  • There are many factors that cause the "universal" activity to change, so you have to modify it at any time, and there is no way to minimize the chance of bugs introduced due to modification.
  • Business functions cannot be reused
  • Such activities have poor maintainability, readability and high coupling.

Therefore, for the long-term consideration in the future, you must boldly refactor it when encountering the "universal" Activity. Although it takes a lot of time to refactor it now, it will be once and forever in the future. Therefore, let the "universal" Activity be no longer universal,Activity only does UI-related workThat's enough.

Summarize

That’s all about the “universal” Activity, please readAndroid: "Universal" Activity Refactoring

The code is refreshing and clean, and it feels so refreshing to read. It is no problem to read 100 lines in one breath!

The above is all the content of this article. I hope that the content of this article will help you study or work. I also hope to support me more!