我正在研究架构组件,现在我正在学习LiveData和数据绑定。我可以将LiveData与布局绑定为Integer值,但是找不到用户列表。
这是带有数据绑定的LiveData的有效示例
<?xml version="1.0" encoding="utf-8"?>
<layout>
<data>
<variable
name="viewModel"
type="com.example.tutorial3livedataanddatabinding.viewmodel.CounterViewModel" />
</data>
<android.support.constraint.ConstraintLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{String.valueOf(viewModel.counter)}"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
</layout>
ViewModel类和活动
public class CounterViewModel extends ViewModel {
private MutableLiveData<Integer> counter = new MutableLiveData<>();
public MutableLiveData<Integer> getCounter() {
return counter;
}
public void setCounter(MutableLiveData<Integer> counter) {
this.counter = counter;
}
public void counterValue(int val) {
this.counter.setValue(val);
}
}
public class MainActivity extends AppCompatActivity {
private int mCounter = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
/*
LifeCycleOwner should be set for LiveData changes to be propagated to UI for this binding
*/
binding.setLifecycleOwner(this);
final CounterViewModel counterViewModel = ViewModelProviders.of(this).get(CounterViewModel.class);
binding.setViewModel(counterViewModel);
increaseCounter(counterViewModel);
}
private void increaseCounter(final CounterViewModel counterViewModel) {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
mCounter ++;
counterViewModel.counterValue(mCounter);
handler.postDelayed(this, 1000);
}
}, 1000);
}
}
对于上面的示例,将数据与数据绑定可以正常工作。计数器更新,但与文档说明不同,它不会在应用程序停止或LiveData时停止计数
注意:LiveData对象仅在活动或 LifecycleOwner是活动的。如果导航到其他应用,则日志 消息暂停,直到您返回。 LiveData对象仅考虑 各自的生命周期所有者为 开始或恢复。
我真正的问题是如何使用LiveData<List<User>>
类实现数据绑定。
<?xml version="1.0" encoding="utf-8"?>
<layout>
<data>
<variable
name="viewModel"
type="com.example.tutorial3livedataanddatabinding2.viewmodel.MyViewModel"/>
</data>
<android.support.constraint.ConstraintLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.tutorial3livedataanddatabinding2.MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{viewModel.getUserRecords()}"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.349" />
<Button
android:id="@+id/button_shufle"
android:layout_width="88dp"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="20dp"
android:onClick="@{() -> viewModel.shuffleUsers()}"
android:text="Shuffle"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView" />
<Button
android:id="@+id/button_add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:onClick="@{() -> viewModel.addUser()}"
android:text="Add"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button_shufle" />
</android.support.constraint.ConstraintLayout>
</layout>
android:text =“ @ {viewModel.getUserRecords()]在开始时将用户数据绑定为String,但是除非添加新用户或对列表进行混洗,否则除非设备旋转,否则它不会更新。
public class MyViewModel extends ViewModel {
private MutableLiveData<List<User>> users;
public LiveData<List<User>> getUsers() {
if (users == null) {
users = new MutableLiveData<>();
loadUsers();
}
return users;
}
private void loadUsers() {
// do async operation to fetch users
List<User> userList = new ArrayList<>();
User user = new User();
user.setFirstName("Jack");
user.setLastName("Daniels");
userList.add(user);
user = new User();
user.setFirstName("Johnny");
user.setLastName("Walker");
userList.add(user);
user = new User();
user.setFirstName("James");
user.setLastName("Jameson");
userList.add(user);
user = new User();
user.setFirstName("Arthur");
user.setLastName("Guinness");
userList.add(user);
users.setValue(userList);
}
public void shuffleUsers() {
if (users != null && users.getValue() != null && users.getValue().size() > 0) {
Collections.shuffle(users.getValue());
// Needed to update Live Data observers
users.setValue(users.getValue());
}
}
public void addUser() {
if (users != null && users.getValue() != null) {
User user = new User();
user.setFirstName("Winston");
user.setLastName("Whiskey");
users.getValue().add(user);
// Needed to update Live Data observers
users.setValue(users.getValue());
}
}
public String getUserRecords() {
if (users != null && users.getValue() != null && users.getValue().size() > 0) {
StringBuilder sb = new StringBuilder();
for (User user : users.getValue()) {
sb.append( user.getFirstName() + " " + user.getLastName() + "\n");
}
return sb.toString();
}
return "empty list";
}
}
活动
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyViewModel myViewModel = ViewModelProviders.of(MainActivity.this).get(MyViewModel.class);
myViewModel.getUsers();
ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
binding.setViewModel(myViewModel);
// Required for binding with LiveData
binding.setLifecycleOwner(this);
}
}
编辑:我在Blackbelt回答后编辑了MyViewModel类
现在我得到Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.arch.lifecycle.LiveData.observeForever(android.arch.lifecycle.Observer)' on a null object reference
System.out.println()
内部的apply()
不会被调用,其他2被调用并且不会为users
和users.getValue()
import android.arch.core.util.Function;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.MutableLiveData;
import android.arch.lifecycle.Transformations;
import android.arch.lifecycle.ViewModel;
import com.example.tutorial3livedataanddatabinding2.model.User;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class MyViewModel extends ViewModel {
private MutableLiveData<List<User>> users;
public LiveData<String> userStringLiveData = Transformations.map(users, new Function<List<User>, String>() {
@Override
public String apply(List<User> input) {
System.out.println("userStringLiveData users: " + users);
return getUserRecords();
}
});
public LiveData<List<User>> getUsers() {
if (users == null) {
users = new MutableLiveData<>();
loadUsers();
}
return users;
}
private void loadUsers() {
// do async operation to fetch users
List<User> userList = new ArrayList<>();
User user = new User();
user.setFirstName("Jack");
user.setLastName("Daniels");
userList.add(user);
user = new User();
user.setFirstName("Johnny");
user.setLastName("Walker");
userList.add(user);
user = new User();
user.setFirstName("James");
user.setLastName("Jameson");
userList.add(user);
user = new User();
user.setFirstName("Arthur");
user.setLastName("Guinness");
userList.add(user);
users.setValue(userList);
System.out.println("MyViewModel users " + users);
System.out.println("MyViewModel users List" + users.getValue());
}
public void shuffleUsers() {
if (users != null && users.getValue() != null && users.getValue().size() > 0) {
Collections.shuffle(users.getValue());
// Needed to update Live Data observers
users.setValue(users.getValue());
}
}
public void addUser() {
if (users != null && users.getValue() != null) {
User user = new User();
user.setFirstName("Winston");
user.setLastName("Whiskey");
users.getValue().add(user);
// Needed to update Live Data observers
users.setValue(users.getValue());
}
}
public String getUserRecords() {
if (users != null && users.getValue() != null && users.getValue().size() > 0) {
StringBuilder sb = new StringBuilder();
for (User user : users.getValue()) {
sb.append(user.getFirstName() + " " + user.getLastName() + "\n");
}
return sb.toString();
}
return "empty list";
}
}
答案 0 :(得分:2)
看起来很像在对象创建时(即第一次评估userStringLiveData时)用户将为null。因此,Transformations.map将传递一个null作为其第一个参数,而不是您希望稍后对其进行操作的LiveData。
这是我的建议:
public class r_RealTulipCoin {
private LiveData<List<User>> users;
public LiveData<String> userStringLiveData;
public void onCreate() {
getUsersLiveDataFromRoomOrSomething();
prepareUserStringLiveData();
}
private void prepareUserStringLiveData() {
userStringLiveData = Transformations.map(users, new android.arch.core.util.Function<List<User>, String>() {
@Override
public String apply(List<User> input) {
System.out.println("userStringLiveData users: " + users);
return getUserRecordsAsSingleStringFromThisParticularList(input);
}
});
}
private String getUserRecordsAsSingleStringFromThisParticularList(List<User> a_list_of_users) {
return "i concatenated them or something";
}
private class User {
String a_name_or_something;
}
}
这是一个样机,但我希望它能说明我的观点。您会注意到我已经做了几件事... 在尝试将用户传递到Transformations.map之前,请确保用户实际上不为null。 我使用map提供的输入参数。非常感谢您已经知道它所指的含义,这就是为什么您的代码无法使用users字段的原因,但是考虑它的来源以及Transformations类试图做什么可能会对您有所帮助。
就您而言,我建议您这样做:
public LiveData<List<User>> getUsers() {
if (users == null) {
users = new MutableLiveData<>();
// this is the first time the users pointer is not null
loadUsers();
prepareUserStringLiveData();
}
return users;
}
最后一个选择是,回到您的原始代码,并在初次构建Transform时使用getUsers()代替用户:
public LiveData<String> userStringLiveData = Transformations.map(getUsers(), blah...)
这不是最整洁的解决方案,但再次说明了为什么我一直坚持要求您实际上将null传递给Transformations.map。
答案 1 :(得分:1)
android:text="@{viewModel.getUserRecords()}
getUserRecords()
中的返回String
,而不是LiveData
对象。您应该改为绑定到LiveData<String>
对象。
例如
public LiveData<String> userStringLiveData = Transformations.map(getUsers(), new Function<List<User>, String>() {
@Override
public String apply(List<User> input) {
return getUserRecords();
}
});
并在您的布局android:text="@{viewModel.userStringLiveData}
中。这样,当您在用户上发布新值时,将调用map并更新UI。