Android Jetpack's best development posture

On the basis of Android architecture components, it integrates Kotlin process +retrofit, simulates the network, and develops comprehensively and rapidly.

Navigation

NavController manages the application navigation objects in NavHost, navigates to a specific target along a specific path in the navigation diagram, or directly navigates to a specific target.

First, define layout / activity main.xml

 <fragment
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:layout_constraintBottom_toTopOf="@id/nav_view"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:navGraph="@navigation/mobile_navigation" />

Second, define navigation/mobile_navigation.xml

To add an Activity, you need to first create the corresponding Activity in Project, and then process it in the layout designer.
 <navigation  
 <fragment
     android:id="@+id/navigation_home"
     android:name="com.android.myapplication.ui.home.HomeFragment"
     android:label="@string/title_home"
     tools:layout="@layout/fragment_home">

        <action
         android:id="@+id/action_navigation_home_to_detail_activity"
         app:destination="@id/detail_activity" />
 </fragment>
   ...
 <activity
     android:id="@+id/detail_activity"
     android:name="com.android.myapplication.ui.detail.DetailActivity"
     android:label="DetailActivity">
     <argument
         android:name="detailId"
         app:argType="string" />
 </activity>
</navigation>

Finally, page Jump, parameter passing

    val direction =  HomeFragmentDirections.actionNavigationHomeToDetailActivity(plantId)
    view.findNavController().navigate(direction)

Parameter receiving:

    private val args: DetailActivityArgs by navArgs()

Databinding

If you directly use the control in onCreateView(), a null pointer exception will be reported. This gesture binding.tvNavigation is OK.

val binding = FragmentHomeBinding.inflate(inflater, container, false)
binding.tvNavigation.setOnClickListener {
            navigateToDetailPage("1", it)
        }

In layout files, string splicing, such as using with ViewModel:

   android:text='@{"Data From Network-> "+viewModel.response}'

ViewModel

Store and manage interface related data in a lifecycle way.
Kotlin collaboration viewModelScope. If ViewModel has been cleared, the collaboration started in this scope will be automatically cancelled.

private val homeViewModel: HomeViewModel by viewModels {
        InjectorUtils.provideHomeViewModelFactory(requireContext())
    }

viewModelScope.launch {
           ...
        }

LiveData

An observable data storage class with life cycle awareness, which means it follows the life cycle of other application components (such as Activity, Fragment or Service).

   var plantName = gardenPlantings.map {
        ...
    }

map to realize the transformation of LiveData

Room

To create the cache of application data, SQLite provides an abstract layer based on SQLite, making full use of SQLite's powerful functions and a more robust database access mechanism.

Using Room to reference complex data provides the ability to convert between basic types and wrapper types, but object references between entities are not allowed.

To add such support for custom types, you need to provide a TypeConverter that converts back and forth between custom classes and known types that Room can keep.

class Converters {//TypeConverters
    ...
}

Add the @ TypeConverters annotation to the AppDatabase class so that Room can use the converters you defined for each entity and DAO in the AppDatabase:

@Database(entities = table, version = 1, exportSchema = false)
@TypeConverters(Converters::class)
abstract class AppDatabase : RoomDatabase() {
   ...
}
@Insert
suspend fun insertPlant(plant: Plant): Long

Think it's a process suspend

WorkManager

Using the WorkManager API, you can easily schedule deferred asynchronous tasks that should run even when the application exits or the device restarts.

val workManagerConfiguration = Configuration.Builder()
            .setWorkerFactory(RefreshDataWork.Factory())
            .build()

 WorkManager.initialize(appContext, workManagerConfiguration)
        val constraints = Constraints.Builder()
            .setRequiresCharging(true)
            .setRequiredNetworkType(NetworkType.CONNECTED)
            .build()

val work = PeriodicWorkRequestBuilder<RefreshDataWork>(2, TimeUnit.HOURS)
            .setConstraints(constraints)
            .build()

WorkManager.getInstance(appContext)
            .enqueueUniquePeriodicWork(RefreshDataWork::class.java.name, KEEP, work)

PeriodicWorkRequest is used for repeated or repeated work, with a minimum interval of 15 minutes.

OneTimeWorkRequest is a one-time request and does not duplicate work.

WorkManager is executed in sequence, in single instance mode, once when app is started.

Download address of Github:

https://github.com/AlbertShen0211/Android-architecture-components

For a better understanding of the code, the following figure is attached

Tags: Android Fragment SQLite network

Posted on Mon, 09 Mar 2020 19:41:02 -0700 by mrfritz379