2021.1.27 update

Have updated the new version of blog, the update content is a lot, so a new blog, poke here.

1 overview

Spring Boot is used as the back-end framework for basic interaction with Android terminal and mysql, including the most basic function of adding, deleting, checking and changing.

2 Development Environment

  • Win
  • The IDEA of 2019.2
  • Tomcat 9.0.27
  • MySQL 8.0.17
  • Spring Boot 2.2.1
  • JDK 8

3 the back-end

3.1 Creating a Spring Boot project

See here.

3.2 entity class

Create a User class as an entity class:

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;
    private String name;

    public Integer getId(a) {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName(a) {
        return name;
    }

    public void setName(String name) {
        this.name = name; }}Copy the code

In fact, I use the code in 3.1 link, which has a detailed explanation.

3.3 the persistence layer

Create a UserRepository to add, delete, and delete

@Repository
public interface UserRepository extends CrudRepository<User.Integer>
{
    @Query(value = "select * from user where name = ? 1",nativeQuery = true)
    public List<User> findByName(String name);

    @Modifying
    @Query(value = "delete from user where name = ? 1",nativeQuery = true)
    public int deleteByName(String name);
}
Copy the code

Since CrudRepository already contains “add” and “modify “, you can implement your own” search “and” delete “as needed. The CrudRepository API is very simple and the official documentation is here.

  • “Increase” usesaveThe parameter is an entity class
  • DeletedeleteByIdIf you do not want to delete by primary key, you can write your own SQL, as above
  • “Check” usefindAllorfindByIdTo customize the search, you need to write your own SQL
  • “Change” can also be usedsave, notice that the primary key needs to be set

@query is used to set SQL statements, and nativeQuery means using native SQL.

3.4 the business layer

Create a new mainservice.java:

@Transactional
@Service
public class MainService {
    @Autowired
    private UserRepository userRepository;

    public Iterable<User> getAllUsers(a)
    {
        return userRepository.findAll();
    }

    public List<User> findByName(String name)
    {
        return userRepository.findByName(name);
    }

    public boolean add(String name)
    {
        User user = new User();
        user.setName(name);
        userRepository.save(user);
		return true;
    }

    public boolean modify(Integer id,String name)
    {
        User user = new User();
        user.setName(name);
        user.setId(id);
        userRepository.save(user);
        return true;
    }

    public boolean deleteByName(String name)
    {
        returnuserRepository.deleteByName(name) ! =0; }}Copy the code
  • getAllUsers(): returns all rows,Iterable<E>type
  • findByName(): Returns all rows with the same name according to name
  • addDirectly usedsaveBecause ofsaveThe entity class is returned, and the original code looks like this:
returnuserRepository.save(user) ! =null;
Copy the code

But the documentation says it won’t be null, so it’s forced to return true.

  • modifyUsing id and name as arguments, create a new user, pass it to the setter as an argument, and pass it to save
  • deleteByNameUse a custom delete function that returns an int. In UserRepository this int represents the number of rows affected by the SQL. The number of rows is not zero if the delete was successful, the delete failed, or the number of rows is zero if there is no row. So the return value is compared to 0

3.5 control layer

@Controller
@RequestMapping(path = "/demo")
public class MainController {
    @Autowired
    private MainService mainService;

    @GetMapping(path = "/getAll")
    public @ResponseBody Iterable<User> getAllUsers(a)
    {
        return mainService.getAllUsers();
    }

    @PostMapping(path = "/get")
    public @ResponseBody List<User> findByName(String name)
    {
        return mainService.findByName(name);
    }

    @PostMapping(path = "/add")
    public @ResponseBody boolean add(@RequestParam String name)
    {
        return mainService.add(name);
    }

    @PostMapping(path = "/modify")
    public @ResponseBody boolean modify(@RequestParam Integer id,@RequestParam String name)
    {
        return mainService.modify(id,name);
    }

    @PostMapping(path = "/delete")
    public @ResponseBody boolean deleteByName(@RequestParam String name)
    {
        returnmainService.deleteByName(name); }}Copy the code

Controller is basically just a couple of annotations, except getAllUsers uses Get, and everything else uses Post. The other is the path setting, directly in the path can be set. The backend is basically complete here, the rest of the package deployment operation is not said, you can refer to here.

4 the Android end

Forget about the new construction. Post part of MainActivity, see the complete code at the end of the article:

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        register.setOnClickListener(v ->{new Thread(()-> {
            OkHttpClient okHttpClient = new OkHttpClient();
            String name = ((EditText) findViewById(R.id.name)).getText().toString();
            FormBody formBody = new FormBody.Builder().add("name", name).build();
            Request request = new Request.Builder()
                    .url(Constant.ADD)
                    .post(formBody)
                    .build();
            try (Response response = okHttpClient.newCall(request).execute()) {
                Looper.prepare();
                if (Boolean.parseBoolean(response.body().string()))
                {
                    Toast.makeText(this."Registration successful", Toast.LENGTH_SHORT).show();
                }
                else
                {
                    Toast.makeText(this."Registration failed", Toast.LENGTH_SHORT).show();
                }
                Looper.loop();
            }
            / /...}).start(); }); login.setOnClickListener(v ->{new Thread(()-> {
            OkHttpClient okHttpClient = new OkHttpClient();
            String name = ((EditText) findViewById(R.id.name)).getText().toString();
            FormBody formBody = new FormBody.Builder().add("name", name).build();
            Request request = new Request.Builder()
                    .url(Constant.GET)
                    .post(formBody)
                    .build();
            try (Response response = okHttpClient.newCall(request).execute()) {
                List<User> users = JSONArray.parseArray(response.body().string(),User.class);
                Looper.prepare();
                if(users.size() == 0)
                {
                    Toast.makeText(this."Login failed",Toast.LENGTH_SHORT).show();
                }
                else
                {
                    Toast.makeText(this."Login successful",Toast.LENGTH_SHORT).show();
                }
                Looper.loop();
            }
            / /...}).start(); }); delete.setOnClickListener(v ->{new Thread(()-> {
            OkHttpClient okHttpClient = new OkHttpClient();
            String name = ((EditText) findViewById(R.id.name)).getText().toString();
            FormBody formBody = new FormBody.Builder().add("name", name).build();
            Request request = new Request.Builder()
                    .url(Constant.DELETE)
                    .post(formBody)
                    .build();
            try (Response response = okHttpClient.newCall(request).execute()) {
                Looper.prepare();
                if (Boolean.parseBoolean(response.body().string()))
                {
                    Toast.makeText(this."Deleted successfully", Toast.LENGTH_SHORT).show();
                }
                else
                {
                    Toast.makeText(this."Delete failed", Toast.LENGTH_SHORT).show();
                }
                Looper.loop();
            }
            / /...}).start(); }); modify.setOnClickListener(v ->{new Thread(()-> {
            OkHttpClient okHttpClient = new OkHttpClient();
            String name = ((EditText) findViewById(R.id.name)).getText().toString();
            String id = ((EditText)findViewById(R.id.id)).getText().toString();
            FormBody formBody = new FormBody.Builder()
                    .add("name", name)
                    .add("id",id)
                    .build();
            Request request = new Request.Builder()
                    .url(Constant.MODIFY)
                    .post(formBody)
                    .build();
            try (Response response = okHttpClient.newCall(request).execute()) {
                Looper.prepare();
                if (Boolean.parseBoolean(response.body().string()))
                {
                    Toast.makeText(this."Modified successfully", Toast.LENGTH_SHORT).show();
                }
                else
                {
                    Toast.makeText(this."Modification failed", Toast.LENGTH_SHORT).show();
                }
                Looper.loop();
            }
            / /...
		}).start();});
    }
}
Copy the code

The CRUD operations are performed separately.

4.1 to add

OkHttpClient okHttpClient = new OkHttpClient();
String name = ((EditText) findViewById(R.id.name)).getText().toString();
FormBody formBody = new FormBody.Builder().add("name", name).build();
Request request = new Request.Builder()
        .url(Constant.ADD)
        .post(formBody)
        .build();
try (Response response = okHttpClient.newCall(request).execute()) {
    Looper.prepare();
    if (Boolean.parseBoolean(response.body().string()))
    {
        Toast.makeText(this."Registration successful", Toast.LENGTH_SHORT).show();
    }
    else
    {
        Toast.makeText(this."Registration failed", Toast.LENGTH_SHORT).show();
    }
    Looper.loop();
} catch (IOException e) {
    e.printStackTrace();
}
Copy the code

Using OkHttp, set the parameters through FormBody, and then create a Request to send through OkHttpClient. Since the “increment” method on the back end returns true, we convert response.body().string() to Boolean to determine whether the operation succeeded. By the way,

Looper.prepare();
Looper.loop();
Copy the code

These two lines can use Toast in non-UI threads.

4.2 delete

OkHttpClient okHttpClient = new OkHttpClient();
String name = ((EditText) findViewById(R.id.name)).getText().toString();
FormBody formBody = new FormBody.Builder().add("name", name).build();
Request request = new Request.Builder()
        .url(Constant.DELETE)
        .post(formBody)
        .build();
try (Response response = okHttpClient.newCall(request).execute()) {
    Looper.prepare();
    if (Boolean.parseBoolean(response.body().string()))
    {
        Toast.makeText(this."Deleted successfully", Toast.LENGTH_SHORT).show();
    }
    else
    {
        Toast.makeText(this."Delete failed", Toast.LENGTH_SHORT).show();
    }
    Looper.loop();
} catch (IOException e) {
    e.printStackTrace();
}
Copy the code

Delete this section is similar, just change the URL, then…. Then there is no…. Like it’s easy? 2333333

4.3 check

OkHttpClient okHttpClient = new OkHttpClient();
String name = ((EditText) findViewById(R.id.name)).getText().toString();
FormBody formBody = new FormBody.Builder().add("name", name).build();
Request request = new Request.Builder()
        .url(Constant.GET)
        .post(formBody)
        .build();
try (Response response = okHttpClient.newCall(request).execute()) {
    List<User> users = JSONArray.parseArray(response.body().string(),User.class);
    Looper.prepare();
    if(users.size() == 0)
    {
        Toast.makeText(this."Login failed",Toast.LENGTH_SHORT).show();
    }
    else
    {
        Toast.makeText(this."Login successful",Toast.LENGTH_SHORT).show();
    }
    Looper.loop();
} catch (IOException e) {
    e.printStackTrace();
}
Copy the code

Look up here and notice that the back end returns a List, which is converted to a List using Ali’s Fastjson.

List<User> users = JSONArray.parseArray(response.body().string(),User.class);
Copy the code

And then if you have it, you just have to figure out if the length is 0.

4.4 change

OkHttpClient okHttpClient = new OkHttpClient();
String name = ((EditText) findViewById(R.id.name)).getText().toString();
String id = ((EditText)findViewById(R.id.id)).getText().toString();
FormBody formBody = new FormBody.Builder()
        .add("name", name)
        .add("id",id)
        .build();
Request request = new Request.Builder()
        .url(Constant.MODIFY)
        .post(formBody)
        .build();
try (Response response = okHttpClient.newCall(request).execute()) {
    Looper.prepare();
    if (Boolean.parseBoolean(response.body().string()))
    {
        Toast.makeText(this."Modified successfully", Toast.LENGTH_SHORT).show();
    }
    else
    {
        Toast.makeText(this."Modification failed", Toast.LENGTH_SHORT).show();
    }
    Looper.loop();
} catch (IOException e) {
    e.printStackTrace();
}
Copy the code

To change that, you just need an extra ID parameter, so add one in the FormBody.

4.5 the UI

I won’t go into details on the UI, just a few simple buttons, you can see the XML file in the code.

4.6 Dependencies and Others

Pay attention to dependencies, and set up Java8.

compileOptions{
	sourceCompatibility=1.8
	targetCompatibility=1.8
}

dependencies{
	implementation 'com.squareup.okhttp3:okhttp:x.x.x'
	implementation 'com.alibaba:fastjson:x.x.x'
}
Copy the code
  • OkHttp latest version of the stamp here to view
  • The latest version of Fastjson can be seen here

4.7 Network Rights

As mentioned in my previous article, this is mainly the permission setting in androidmanifest.xml, see here.

5 test

Original database:Sign up for one:Look at the database:Test Login:Try logging in to a non-existent:Modification: Finally, delete: Deleting a nonexistent file will fail.

6 source

  • Github
  • Yards cloud
  • CODE.CHINA

If you think the article looks good, please like it.

At the same time, welcome to pay attention to wechat public number: Lingzhi Road.