--- description: This guide provides definitive best practices for Android SDK development in Java, focusing on modern architecture, Jetpack libraries, performance, security, and testing. globs: **/*.java --- # android-sdk Best Practices (Java) This guide outlines the essential practices for building robust, performant, and maintainable Android applications using Java, adhering to modern standards and leveraging the AndroidX ecosystem. ## 1. Code Organization and Structure **1.1 Modular Architecture (MVVM)** Adopt a clean, modular architecture, with MVVM (Model-View-ViewModel) as the standard. This promotes separation of concerns, testability, and scalability. ❌ **BAD: Tight Coupling** ```java // Activity directly fetching data and updating UI public class UserProfileActivity extends AppCompatActivity { private TextView userName; // ... other UI elements @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_user_profile); userName = findViewById(R.id.user_name); // Direct network call on UI thread (or poorly managed background thread) new Thread(() -> { String name = fetchUserNameFromNetwork(); // Blocking call runOnUiThread(() -> userName.setText(name)); }).start(); } // ... } ``` ✅ **GOOD: MVVM with Repository Pattern** ```java // ui/UserProfileActivity.java public class UserProfileActivity extends AppCompatActivity { private UserProfileViewModel viewModel; private TextView userName; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_user_profile); userName = findViewById(R.id.user_name); viewModel = new ViewModelProvider(this).get(UserProfileViewModel.class); viewModel.getUserName().observe(this, name -> { userName.setText(name); }); } } // ui/UserProfileViewModel.java public class UserProfileViewModel extends AndroidViewModel { private UserRepository userRepository; private MutableLiveData userName = new MutableLiveData<>(); public UserProfileViewModel(@NonNull Application application) { super(application); this.userRepository = new UserRepository(application); // Injected via Hilt in real app loadUserName(); } public LiveData getUserName() { return userName; } private void loadUserName() { // Use ExecutorService or RxJava for background work Executors.newSingleThreadExecutor().execute(() -> { String name = userRepository.fetchUserName(); userName.postValue(name); // Post value to main thread }); } } // data/UserRepository.java public class UserRepository { // In a real app, this would interact with Room, Retrofit, etc. public String fetchUserName() { // Simulate network call try { Thread.sleep(2000); } catch (InterruptedException e) {} return "John Doe"; } } ``` **1.2 Package Structure** Organize packages by feature or layer, not by Android component type. ❌ **BAD: Component-based** ``` com.example.app ├── activities │ └── UserProfileActivity.java ├── fragments │ └── SettingsFragment.java ├── adapters │ └── UserListAdapter.java └── utils └── NetworkUtils.java ``` ✅ **GOOD: Feature-based (or Layer-based for larger apps)** ``` com.example.app ├── userprofile │ ├── UserProfileActivity.java │ ├── UserProfileViewModel.java │ └── UserProfileFragment.java ├── settings │ ├── SettingsActivity.java │ └── SettingsViewModel.java ├── data │ ├── UserRepository.java │ ├── UserApiService.java │ └── UserDatabase.java └── common ├── adapters │ └── UserListAdapter.java └── utils └── NetworkUtils.java ``` ## 2. Common Patterns and Anti-patterns **2.1 Jetpack Libraries** Always prefer AndroidX Jetpack libraries for modern, backward-compatible, and lifecycle-aware components. * **Room for Persistence:** Use Room for all local database storage. ❌ **BAD: Raw SQLiteOpenHelper** ```java // Manual SQLite table creation and query management public class MyDbHelper extends SQLiteOpenHelper { /* ... */ } ``` ✅ **GOOD: Room Database** ```java @Database(entities = {User.class}, version = 1) public abstract class AppDatabase extends RoomDatabase { public abstract UserDao userDao(); } @Entity public class User { @PrimaryKey public int id; public String name; } @Dao public interface UserDao { @Query("SELECT * FROM user WHERE id = :userId") LiveData getUserById(int userId); @Insert void insert(User user); } ``` * **View Binding (or Data Binding):** Eliminate `findViewById` boilerplate. ❌ **BAD: Manual View Lookup** ```java public class MyActivity extends AppCompatActivity { private Button myButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_my); myButton = findViewById(R.id.my_button); myButton.setOnClickListener(v -> /* ... */); } } ``` ✅ **GOOD: View Binding** ```java public class MyActivity extends AppCompatActivity { private ActivityMyBinding binding; // Generated binding class @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = ActivityMyBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); binding.myButton.setOnClickListener(v -> /* ... */); } } ``` * **Navigation Component:** Manage in-app navigation consistently. ❌ **BAD: Manual Fragment Transactions** ```java getSupportFragmentManager().beginTransaction() .replace(R.id.fragment_container, new DetailFragment()) .addToBackStack(null) .commit(); ``` ✅ **GOOD: Navigation Graph** ```java // In Activity/Fragment NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment); navController.navigate(R.id.action_homeFragment_to_detailFragment); // Define navigation in res/navigation/nav_graph.xml ``` **2.2 Dependency Injection (Hilt)** Use Hilt (built on Dagger) for robust dependency injection, simplifying object creation and improving testability. ❌ **BAD: Manual Dependency Management** ```java public class MyRepository { private MyApiService apiService = new MyApiService(); // Hardcoded dependency // ... } ``` ✅ **GOOD: Hilt** ```java @Module @InstallIn(SingletonComponent.class) public abstract class AppModule { @Provides @Singleton public static MyApiService provideMyApiService() { return new MyApiService(); // Or provide Retrofit instance } } @Singleton public class MyRepository { private final MyApiService apiService; @Inject // Hilt injects MyApiService public MyRepository(MyApiService apiService) { this.apiService = apiService; } // ... } @HiltAndroidApp public class MyApplication extends Application {} ``` ## 3. Performance Considerations **3.1 Layout Optimization** Flatten view hierarchies using `ConstraintLayout` and `ViewStub` to reduce layout inflation time and memory usage. ❌ **BAD: Deeply Nested Layouts** ```xml