Building an Android App with Spring Boot for CRUD Operations

Here’s an end-to-end guide to building a complete CRUD application using Android as the front end and Spring Boot as the backend.

We’ll cover the following steps:

  1. Backend with Spring Boot

    • Setting up the Spring Boot project
    • Creating the REST API
    • Implementing CRUD operations
    • Testing the backend
  2. Frontend with Android

    • Setting up the Android project
    • Connecting to the Spring Boot API
    • Performing CRUD operations
    • Displaying data in RecyclerView
  3. Testing and Deployment


Step 1: Backend with Spring Boot

1.1 Setting up Spring Boot Project

  1. Use Spring Initializr to generate a new project with the following dependencies:

    • Spring Web
    • Spring Data JPA
    • H2 Database (or MySQL for production)
    • Lombok (optional, for reducing boilerplate code)
  2. Configure the application.properties file:

    spring.datasource.url=jdbc:h2:mem:testdb
    spring.datasource.driver-class-name=org.h2.Driver
    spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
    spring.h2.console.enabled=true

1.2 Creating the REST API

  1. Model Class:

    @Entity
    public class User {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Long id;
        private String name;
        private String email;
        private String phone;
    
        // Getters and setters
    }
    
  2. Repository:

    @Repository
    public interface UserRepository extends JpaRepository<User, Long> {}
  3. Service:

    @Service
    public class UserService {
        private final UserRepository userRepository;
    
        public UserService(UserRepository userRepository) {
            this.userRepository = userRepository;
        }
    
        public List<User> getAllUsers() {
            return userRepository.findAll();
        }
    
        public User getUserById(Long id) {
            return userRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("User not found"));
        }
    
        public User createUser(User user) {
            return userRepository.save(user);
        }
    
        public User updateUser(Long id, User userDetails) {
            User user = getUserById(id);
            user.setName(userDetails.getName());
            user.setEmail(userDetails.getEmail());
            user.setPhone(userDetails.getPhone());
            return userRepository.save(user);
        }
    
        public void deleteUser(Long id) {
            userRepository.deleteById(id);
        }
    }
  4. Controller:

    @RestController
    @RequestMapping("/api/users")
    public class UserController {
        private final UserService userService;
    
        public UserController(UserService userService) {
            this.userService = userService;
        }
    
        @GetMapping
        public List<User> getAllUsers() {
            return userService.getAllUsers();
        }
    
        @GetMapping("/{id}")
        public User getUserById(@PathVariable Long id) {
            return userService.getUserById(id);
        }
    
        @PostMapping
        public User createUser(@RequestBody User user) {
            return userService.createUser(user);
        }
    
        @PutMapping("/{id}")
        public User updateUser(@PathVariable Long id, @RequestBody User userDetails) {
            return userService.updateUser(id, userDetails);
        }
    
        @DeleteMapping("/{id}")
        public void deleteUser(@PathVariable Long id) {
            userService.deleteUser(id);
        }
    }

1.3 Testing the Backend

  • Run the application and use Postman or cURL to test the endpoints:
    • GET /api/users
    • GET /api/users/{id}
    • POST /api/users
    • PUT /api/users/{id}
    • DELETE /api/users/{id}

Step 2: Frontend with Android

2.1 Setting up Android Project

  1. Create a new Android project in Android Studio.
  2. Add the following dependency in build.gradle for network operations:
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
    implementation 'androidx.recyclerview:recyclerview:1.3.1'

2.2 Connecting to the Spring Boot API

  1. Retrofit API Interface:

    public interface ApiService {
        @GET("users")
        Call<List<User>> getUsers();
    
        @GET("users/{id}")
        Call<User> getUser(@Path("id") Long id);
    
        @POST("users")
        Call<User> createUser(@Body User user);
    
        @PUT("users/{id}")
        Call<User> updateUser(@Path("id") Long id, @Body User user);
    
        @DELETE("users/{id}")
        Call<Void> deleteUser(@Path("id") Long id);
    }
    
  2. Retrofit Client:

    public class RetrofitClient {
        private static final String BASE_URL = "http://<your-ip>:8080/api/";
        private static Retrofit retrofit;
    
        public static Retrofit getInstance() {
            if (retrofit == null) {
                retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
            }
            return retrofit;
        }
    }

2.3 Performing CRUD Operations

  1. Model Class:

    public class User {
        private Long id;
        private String name;
        private String email;
        private String phone;
    
        // Getters and setters
    }
  2. RecyclerView Adapter: Create an adapter for displaying users in a RecyclerView.


2.4 Displaying Data in RecyclerView

  1. Fetch the list of users using the getUsers() API.
  2. Populate the RecyclerView with the data.

Step 3: Testing and Deployment

  1. Testing:

    • Test the Android app against the Spring Boot backend.
    • Test on physical/emulated Android devices.
  2. Deployment:

    • Deploy the Spring Boot application on a cloud server (e.g., AWS, Heroku).
    • Update the Android app’s BASE_URL to point to the deployed backend.

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete