标签: android-architecture-components

如何为 ViewPager 中的每个页面创建一个 ViewModel?

我有一个ViewPager,我在其中显示了PetFragment. 要创建 a 的新实例PetFragment,我调用PetFragment.newInstance(petId).

我想要一个单独的ViewModel实例petId。但ViewModelProvider.Factory#create()只将 aClass<T>作为参数。我如何实现这一目标?

android android-architecture-lifecycle android-architecture-components

2
推荐指数
1
解决办法
2077
查看次数

我可以为不同的对象类型使用一个 TypeConverter 吗?

到目前为止,为了存储在Room 数据库中,我一直在为每个类使用类型转换器。像这样:

@SerializedName("sidebar")
@Expose
@TypeConverters(SidebarConverter.class)
private Sidebar sidebar;
@SerializedName("splash")
@Expose
@TypeConverters(SplashConverter.class)
private Splash splash;
@SerializedName("overview")
@Expose
@TypeConverters(OverviewConverter.class)
private Overview overview;
@SerializedName("home")
@Expose
@TypeConverters(HomeConverter.class)
private Home home;
@SerializedName("portfolio")
@Expose
@TypeConverters(PortfolioConverter.class)
private Portfolio portfolio;
@SerializedName("team")
@Expose
@TypeConverters(TeamConverter.class)
private Team team;
Run Code Online (Sandbox Code Playgroud)

我想知道是否有一种更方便的方法可以TypeConverter在数据库中单独使用。

database android android-room android-architecture-components

2
推荐指数
1
解决办法
5010
查看次数

使用存储库在本地数据库/位置和网络之间同步

我正在实施一个天气应用程序,它通过 Retrofit 从 DarkSky 获取预报,并从 GoogleFusedLocationClient 获取位置。我的目标是通过应用程序关闭和配置更改来保存 UI 数据。我使用 Room+ViewModel+LiveData 和 Repository 模型实现了它。但是我在片段中而不是在存储库中获取我的位置和预测,目标是将其移动到存储库。
以便存储库查看数据库,如果它是空的,则从网络中获取数据。
我当前的存储库:

public class UIRepository {

    private UIDao mUIDao;
    private LiveData<List<UIData>> mAllUIData;

    UIRepository(Application application) {
        PhotoDatabase db = PhotoDatabase.getDatabase(application);
        mUIDao = db.uiDao();
        mAllUIData = mUIDao.getAllUIData();
    }

    LiveData<List<UIData>> getAllUIData() {
        return mAllUIData;
    }

    public void insert(UIData uiData) {
        new insertAsyncTask(mUIDao).execute(uiData);
    }

    private static class insertAsyncTask extends AsyncTask<UIData, Void, Void> {

        private UIDao mAsyncDao;

        insertAsyncTask(UIDao uiDao) {
            mAsyncDao = uiDao;
        }

        @Override
        protected Void doInBackground(UIData... uiData) {
            mAsyncDao.insert(uiData[0]);
            return …
Run Code Online (Sandbox Code Playgroud)

java android android-fragments android-room android-architecture-components

2
推荐指数
1
解决办法
2393
查看次数

无法实例化片段 androidx.navigation.fragment.NavHostFragment

错误

无法实例化片段 androidx.navigation.fragment.NavHostFragment:确保类名存在,是公共的,并且有一个公共的空构造函数。

活动布局

 <fragment
        android:id="@+id/my_nav_host_fragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:name="androidx.navigation.fragment.NavHostFragment"
        app:defaultNavHost="true"
        app:navGraph="@navigation/app_nav" />
Run Code Online (Sandbox Code Playgroud)

活动

class HomeActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_home)
    }
}
Run Code Online (Sandbox Code Playgroud)

分段

class MovieListFragment : Fragment() {
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_movie_list, container, false)
    }
}
Run Code Online (Sandbox Code Playgroud)

使用的依赖:

implementation('android.arch.navigation:navigation-fragment-ktx:1.0.0-alpha07') {
    exclude group: "com.android.support"
}
implementation('android.arch.navigation:navigation-ui-ktx:1.0.0-alpha07') {
    exclude group: "com.android.support"
}
Run Code Online (Sandbox Code Playgroud)

android android-architecture-components android-jetpack android-architecture-navigation

2
推荐指数
2
解决办法
3019
查看次数

Transformations.map 和 MediatorLiveData 使用空对象引用崩溃的应用程序

不知道发生了什么。我正在运行两个查询,然后使用 MediatorLiveData 和 Transformations.map 合并和转换这些查询。我将这个几乎完全相同的代码用于其他两个查询,没有问题。但是当我将它用于这些特定查询时,应用程序一开始就会崩溃,并出现以下错误。

请注意:我已经尝试观察 MediatorLiveData,并且可以毫无错误地获得两个查询的结果。只有当我尝试通过 Transformations.map 运行它们时,才会出现错误和应用程序崩溃。

这是我用来测试运行良好的 MediatorLiveData 的观察:

    viewModel.getAllValidEventsLiveDataMerger().observe(this, new Observer<AllValidEventsSnapshot>() {
            @Override
            public void onChanged(@Nullable AllValidEventsSnapshot allValidEventsSnapshot) {
                if (allValidEventsSnapshot.isComplete()) {
                    List<Event> nonRepeatEventList;
                    List<Event> repeatEventList;
                    List<Event> eventList = new ArrayList<>();
                    nonRepeatEventList = allValidEventsSnapshot.getValidNonRepeatableEventsSnapshot().toObjects(Event.class);
                    repeatEventList = allValidEventsSnapshot.getValidRepeatableEventsSnapshot().toObjects(Event.class);
                    eventList.addAll(nonRepeatEventList);
                    eventList.addAll(repeatEventList);
                    Log.d(TAG, "EVENTLIST: " + eventList.toString());
                }
            }
        }); 
Run Code Online (Sandbox Code Playgroud)

这是通过 Transformations.map 的观察:

    viewModel.getAllValidEventsLiveData().observe(this, new Observer<List<Event>>() {
            @Override
            public void onChanged(@Nullable List<Event> eventList) {
                if (eventList != null) {
                    Log.d(TAG, "EventList: " + eventList.toString());
                }
            }
        }); 
Run Code Online (Sandbox Code Playgroud)

这是代码:

视图模型.java …

android android-architecture-components google-cloud-firestore

2
推荐指数
1
解决办法
2067
查看次数

无法解决:添加导航后的片段

当我尝试添加依赖项时出现此错误 Navigation

无法解决:片段

我添加了这些行:

implementation "android.arch.navigation:navigation-fragment-ktx:$navigationVersion"
implementation "android.arch.navigation:navigation-ui-ktx:$navigationVersion"
Run Code Online (Sandbox Code Playgroud)

在项目 gradle 这是我添加的内容:

ext{
    navigationVersion = '1.0.0-alpha09'
}
repositories {
    google()
    jcenter()
}
Run Code Online (Sandbox Code Playgroud)

我试图使缓存无效并重新启动,但没有奏效。

旁注我已经迁移到androidx没有问题,但在我尝试添加Navigation库后,出现此错误

android android-architecture-components android-architecture-navigation

2
推荐指数
1
解决办法
1938
查看次数

为什么在导航控制器中实现包含时出现 StackOverflowError?

我的项目文件:https : //drive.google.com/file/d/11llz7ylWe7ACyLMBbqp6YzugUL8hhImt/view?usp=sharing

所以我有 2 个导航图。称为主导航图和身份验证图。

我将主图包含在身份验证图中,反之亦然,身份验证图包含在主图中。

我想实现登录系统,所以当用户成功登录时,用户将转到主活动(具有底部导航视图和工具栏),身份验证活动没有底部导航视图或片段。这是图表

  1. 主导航图:

在此处输入图片说明

<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            xmlns:tools="http://schemas.android.com/tools"
            android:id="@+id/navigation_graph"
            app:startDestination="@id/destination_home">

    <include app:graph="@navigation/auth_graph" />

    <fragment android:id="@+id/destination_home" android:name="com.muchammadagunglaksana.navcontroller.HomeFragment"
              android:label="Home Judul" tools:layout="@layout/fragment_home">
        <action android:id="@+id/action_toAuthActivity" app:destination="@id/auth_graph"/>
    </fragment>


    <fragment android:id="@+id/destination_camera" android:name="com.muchammadagunglaksana.navcontroller.CameraFragment"
              android:label="Camera Judul" tools:layout="@layout/fragment_camera">
        <action android:id="@+id/toPhotosDestination" app:destination="@id/destination_photos"/>
    </fragment>


    <fragment android:id="@+id/destination_photos" android:name="com.muchammadagunglaksana.navcontroller.PhotosFragment"
              android:label="Foto Judul" tools:layout="@layout/fragment_photos">
        <action android:id="@+id/toHomeDestination" app:destination="@id/destination_home"/>
        <argument android:name="numberOfPhotos" app:argType="integer" android:defaultValue="0"/>
    </fragment>


    <fragment android:id="@+id/destination_settings"
              android:name="com.muchammadagunglaksana.navcontroller.SettingsFragment"
              android:label="Setting Judul" tools:layout="@layout/fragment_settings"/>
</navigation>
Run Code Online (Sandbox Code Playgroud)
  1. 验证图: 在此处输入图片说明

    <include app:graph="@navigation/navigation_graph" />
    
    <fragment android:id="@+id/loginFragment" android:name="com.muchammadagunglaksana.navcontroller.LoginFragment"
              android:label="fragment_login" tools:layout="@layout/fragment_login">
        <action android:id="@+id/action_toMainActivity" app:destination="@id/navigation_graph"/>
    </fragment>
    
    Run Code Online (Sandbox Code Playgroud)

当单击 LoginFragment 中的登录按钮时,我使用以下代码:

       login_button.setOnClickListener …
Run Code Online (Sandbox Code Playgroud)

android android-architecture-components android-jetpack

2
推荐指数
1
解决办法
827
查看次数

如何通过 ViewModel 从 Fragment 观察 Repository LiveData

我很难弄清楚如何在请求的情况下连接我的RepositoryViewModel的实时数据@GET并在片段中观察它们。

当请求类型是@POST因为我可以Transformation.switchMap在主体上使用时,我没有这个问题,并且每当主体更改存储库的函数被调用并向响应实时数据发出值时,就像这样

val matchSetsDetail: LiveData<Resource<MatchDetailBean>> = Transformations.switchMap(matchIdLiveData) { matchId ->
        val body = MatchSetRequest(matchId)
        repository.getMatchSet(body)
    }
Run Code Online (Sandbox Code Playgroud)

但是在@GET请求的情况下,我的视图提供了几个查询参数

我在存储库类中有这个改造 API 调用,代码看起来像这样

class Repository {
    fun checkInCheckOutUser(apiKey: String, userId: Int, status: String, latitude: Double, longitude: Double, checkedOn: Long): LiveData<Resource<BaseResponse>> = liveData {
            emit(Resource.Loading())
            try {
                val response: Response<BaseResponse> = ApiClient.coachApi.checkInCheckOutUser(apiKey, userId, status, latitude, longitude, checkedOn)
                if (response.isSuccessful && response.body() != null) {
                    if (response.body()!!.isValidKey && response.body()!!.success) {
                        emit(Resource.Success(response.body()!!))
                    } else …
Run Code Online (Sandbox Code Playgroud)

android kotlin android-livedata android-architecture-components kotlin-coroutines

2
推荐指数
1
解决办法
2073
查看次数

LifecycleService 是否与生命周期扩展工件一起被弃用?

似乎过去存在于lifecycle-extensions工件中的 LifecycleService 类在当前推荐的任何工件中都不可用。我希望它是lifecycle-runtime,这是没有的ViewModel andLiveData的一个,但LifecycleService不是lifecycle-viewmodellifecycle-livedata

LifecycleService 是否已被弃用?

当前生命周期工件的来源

android deprecated android-architecture-lifecycle android-architecture-components androidx

2
推荐指数
1
解决办法
574
查看次数

使用导航架构组件时,Activity 和 Fragment 之间的通信

我想让宿主 Activity 知道 Fragment 中发生的事情。传统上,我会有一个带有 Fragment 可以调用的回调的接口,但现在我们使用导航架构组件。

有没有办法将主机活动的引用传递给片段,或者我将如何解决“活动和片段之间的通信”情况?

谢谢!

android android-architecture-components androidx navigation-architecture

2
推荐指数
1
解决办法
1442
查看次数