Today I'm trying to use a LiveData (MutableLiveData) object to have some dynamics values. (in MVVM pattern)
I used a model object like this:
public class Object {
private String name;
private float internalvalue;
private float in1;
private float out1;
private float out2;
public Object(String name, float internalvalue){
this.name = name;
this.internalvalue = internalvalue;
}
public float getOut1(){
return this.out1;
}
public float getOut2(){
return this.out2;
}
public void setIn1(float in1){
this.in1 = in1;
}
private void performSomething(float internalvalue, float in1){
SubClassSingleton.performSomething(internalvalue, in1, new SubClassSingletonListener() {
#Override
public void onSuccess(float out1, float out2){
this.out1 = out1;
this.out2 = out2;
}
});
}
}
I use a ViewModel like this:
public class MainViewModel {
public MutableLiveData<Object> obj;
public MainViewModel(){
this.obj = new MutableLiveData<>();
this.obj.postValue(new Object("Name", 50.0f);
}
}
In MainFragment:
public class MainFragment extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
MainViewModel viewModel = ViewModelProviders.of(this).get(MainViewModel.class);
MainFragmentBinding binding = MainFragmentBinding.inflate(getLayoutInflater());
binding.setViewModel(viewModel);
binding.setLifecycleOwner(this);
return binding.getRoot();
}
}
And in View:
<layout ...
<data>
<variable
name="viewModel"
type="app.example.MainViewModel"/>
</data>
<LinearLayout
...>
<EditText
android:text="#={viewModel.obj.in1}"
.../>
<TextView
android:text="#{viewModel.obj.out1}"
.../>
<TextView
android:text="#{viewModel.obj.out2}"
.../>
</LinearLayout>
</layout>
I'd like to update my view when the values (out1, out2) of my model are updated (when the calculation is performed).
How can I do this ?
Try this:
You need to make your model class extend BaseObservable.
public class Object extends BaseObservable {
private String name;
private float internalvalue;
private float in1;
private float out1;
private float out2;
public Object(String name, float internalvalue) {
this.name = name;
this.internalvalue = internalvalue;
}
public float getOut1() {
return this.out1;
}
public void setOut1(float out1) {
this.out1 = out1;
notifyChange();
}
public float getOut2() {
return this.out2;
}
public void setOut2(float out2) {
this.out2 = out2;
notifyChange();
}
public void setIn1(float in1) {
this.in1 = in1;
}
private void performSomething(float internalvalue, float in1) {
SubClassSingleton.performSomething(internalvalue, in1, new SubClassSingletonListener() {
#Override
public void onSuccess(float out1, float out2) {
setOut1(out1);
setOut2(out2);
}
});
}
}
And in View, you cannot bind float directly to view. It has to be string, so bind like this:
<layout ...
<data>
<variable
name="viewModel"
type="app.example.MainViewModel"/>
</data>
<LinearLayout
...>
<EditText
android:text='#={""+viewModel.obj.in1}'
.../>
<TextView
android:text='#{""+viewModel.obj.out1}'
.../>
<TextView
android:text='#{""+viewModel.obj.out2}'
.../>
</LinearLayout>
</layout>
Related
Hello I am struggling with this problem. I have a RecyclerView with checkboxes items which is nested in another RecyclerView. My problem is that I want all the checkbox to be unchecked when the user click in a button in the fragment. So how could I access the checkbox view holder from my fragment button? Thank you.
Please be comprehensive with the mistakes in my code I am beginner, self-taught and it is my first app. Any help would be really appreciated.
fragment_index_category_filter.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="4dp"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".Fragments.IndexCategoryFilterFragment">
<!-- TODO: Update blank fragment layout -->
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/appBarLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/white"
android:gravity="center"
app:layout_constraintTop_toTopOf="parent"
android:theme="#style/AppTheme.AppBarOverlay">
<androidx.appcompat.widget.Toolbar
android:id="#+id/home_activity_tb"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:contentInsetLeft="0dp"
app:contentInsetRight="0dp"
app:contentInsetEnd="0dp"
app:contentInsetStart="0dp"
android:gravity="center"
android:layout_gravity="center"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<RelativeLayout
android:id="#+id/toolbar"
android:padding="8dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.button.MaterialButton
android:id="#+id/close_filters"
android:layout_width="32dp"
android:layout_height="32dp"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"
android:insetLeft="0dp"
android:insetTop="0dp"
android:insetRight="0dp"
android:insetBottom="0dp"
android:padding="0dp"
app:fabCustomSize="50dp"
app:icon="#drawable/cancel"
app:iconGravity="textStart"
app:iconPadding="0dp"
app:iconSize="32dp"
app:shapeAppearanceOverlay="#style/ShapeAppearanceOverlay.MyApp.Button.Circle" />
<com.google.android.material.textview.MaterialTextView
android:id="#+id/appBarTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Category list"
android:textAllCaps="false"
android:textColor="#color/black"
android:textSize="24sp" />
<com.google.android.material.button.MaterialButton
android:id="#+id/save_filters"
app:icon="#drawable/ic_check_ok"
app:iconSize="32dp"
app:iconGravity="textStart"
android:layout_width="32dp"
android:layout_height="32dp"
android:padding="0dp"
app:iconPadding="0dp"
android:insetLeft="0dp"
android:insetTop="0dp"
android:insetRight="0dp"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:insetBottom="0dp"
app:shapeAppearanceOverlay="#style/ShapeAppearanceOverlay.MyApp.Button.Circle"
app:fabCustomSize="50dp"
/>
</RelativeLayout>
</androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.AppBarLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="#+id/appBarLayout"
android:id="#+id/shortcuts_filter">
<com.google.android.material.button.MaterialButton
android:id="#+id/clear_filters"
style="#style/Widget.MaterialComponents.Button.OutlinedButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:padding="0dp"
android:text="Clear all"
android:textAllCaps="false"
android:textSize="12sp" />
<com.google.android.material.button.MaterialButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="0dp"
android:id="#+id/select_all_filters"
android:textSize="12sp"
android:text="Select all"
android:layout_alignParentEnd="true"
android:textAllCaps="false"
style="#style/Widget.MaterialComponents.Button.OutlinedButton"/>
</RelativeLayout>
<androidx.recyclerview.widget.RecyclerView
android:layout_margin="8dp"
app:layout_constraintTop_toBottomOf="#+id/shortcuts_filter"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/categorySection_rv"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
android:orientation="vertical"/>
</androidx.constraintlayout.widget.ConstraintLayout>
IndexCategoryFilterFragment.java
public class IndexCategoryFilterFragment extends Fragment {
//Initialize variable
List<String> streamFiltersList;
RecyclerView categorySection_rv;
FirebaseDatabase firebaseDatabase;
DatabaseReference dbCategoryReference;
StreamFilterManager streamFilterManager;
MaterialButton save_filters, clear_filters, close_fragment;
FiltersViewModel filtersListObserver;
private FirebaseAuth mAuth;
FirebaseUser firebaseUser;
String userId;
SectionAdapter sectionAdapter;
List<Letter> letterList;
List<Category> categoryInLetter = new ArrayList<>();
public FilterInterface interfaceListener;
public IndexCategoryFilterFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (container != null) {
container.removeAllViews();
}
// Inflate the layout for this fragment
mAuth = FirebaseAuth.getInstance();
firebaseUser = mAuth.getCurrentUser();
userId = firebaseUser.getUid();
View view = inflater.inflate(R.layout.fragment_index_category_filter, container, false);
save_filters = view.findViewById(R.id.save_filters);
categorySection_rv = view.findViewById(R.id.categorySection_rv);
clear_filters = view.findViewById(R.id.clear_filters);
close_fragment = view.findViewById(R.id.close_filters);
firebaseDatabase = FirebaseDatabase.getInstance();
dbCategoryReference = firebaseDatabase.getReference("CategoryIndexed");
save_filters.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
streamFilterManager.logOutFromUserSession();
streamFilterManager.writeListInPref(getContext(), streamFiltersList, userId);
Log.d("streamFilter", "onClick: " + streamFiltersList);
filtersListObserver = new ViewModelProvider(requireActivity()).get(FiltersViewModel.class);
filtersListObserver.setFiltersList(streamFiltersList);
getParentFragmentManager().beginTransaction().replace(R.id.fragment_container, new Home(), "home").commit();
}
});
close_fragment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getParentFragmentManager().popBackStack();
}
});
letterList = new ArrayList<>();
categoryInLetter = new ArrayList<>();
sectionAdapter = new SectionAdapter(getContext(), letterList);
categorySection_rv.setAdapter(sectionAdapter);
firebaseCategoryIndex();
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onResume() {
super.onResume();
streamFilterManager = new StreamFilterManager(getContext(), userId);
streamFiltersList = streamFilterManager.readFilterList(getContext(), userId);
if (streamFiltersList == null) {
streamFiltersList = new ArrayList<>();
}
clear_filters.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkboxUpdate();
}
});
}
private void firebaseCategoryIndex() {
// First recycler
Query queryLetter = dbCategoryReference.orderByChild("index");
queryLetter.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
letterList.clear();
for (DataSnapshot dsLetter : snapshot.getChildren()) {
Letter letter = dsLetter.getValue(Letter.class);
letterList.add(letter);
}
sectionAdapter.notifyDataSetChanged();
Log.d("letterList", "letterList: " + letterList.size());
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
// solutions testing
public interface FilterInterface {
void clearSelectAllFilters(Button allFilters);
}
private void checkboxUpdate() {
// 1. get ith item of the parent recyclerView
for(int i = 0 ; i< sectionAdapter.getItemCount();i++){
SectionAdapter.ViewHolder viewHolder = (SectionAdapter.ViewHolder) categorySection_rv.findViewHolderForAdapterPosition(i);
RecyclerView recyclerView = viewHolder.section_item_rv;
ItemSectionAdapter itemSectionAdapter = (ItemSectionAdapter) recyclerView.getAdapter();
itemSectionAdapter.update();
}
}
}
SectionAdapter.java
public class SectionAdapter extends RecyclerView.Adapter<SectionAdapter.ViewHolder> implements IndexCategoryFilterFragment.FilterInterface {
Context context ;
List<Letter> letterList;
DatabaseReference categoryListRef;
public SectionAdapter(Context context, List<Letter> letterList) {
this.context = context;
this.letterList = letterList;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.section_category,parent,false);
return new SectionAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
List<Category> letterCategoryList = new ArrayList<>();
Letter letter = letterList.get(position);
holder.section_letter.setText(letter.getIndex());
holder.section_title_ll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int visible = holder.section_item_rv.getVisibility();
if (visible == View.VISIBLE){
holder.section_item_rv.setVisibility(View.GONE);
} else {
holder.section_item_rv.setVisibility(View.VISIBLE);
}
}
});
categoryListRef = FirebaseDatabase.getInstance().getReference("CategoryIndexed").child(letter.getIndex()).child("content");
ItemSectionAdapter itemSectionAdapter = new ItemSectionAdapter(letterCategoryList);
categoryListRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dsLetterContent : snapshot.getChildren()){
Category category = dsLetterContent.getValue(Category.class);
category.setCheckState(true);
Log.d("letterList", "letterList: "+ category.getCategoryName() + " "+ category.isCheckState());
letterCategoryList.add(category);
}
itemSectionAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
holder.section_item_rv.setAdapter(itemSectionAdapter);
}
#Override
public int getItemCount() {
return letterList.size();
}
#Override
public void clearSelectAllFilters(Button allFilters) {
}
public class ViewHolder extends RecyclerView.ViewHolder {
public MaterialTextView section_letter;
public RecyclerView section_item_rv;
public LinearLayout section_title_ll;
public ViewHolder(#NonNull View itemView) {
super(itemView);
section_letter = itemView.findViewById(R.id.section_letter);
section_item_rv = itemView.findViewById(R.id.section_item_rv);
section_title_ll = itemView.findViewById(R.id.section_title_ll);
}
}
}
ItemSectionAdpater.java
public class ItemSectionAdapter extends RecyclerView.Adapter<ItemSectionAdapter.ViewHolder> implements IndexCategoryFilterFragment.FilterInterface {
List<Category> categoryList;
public ItemSectionAdapter(List<Category> categoryList) {
this.categoryList = categoryList;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.index_category_name_item,parent,false);
return new ItemSectionAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
Category category = categoryList.get(position);
holder.indexItemCategory.setText(category.getCategoryName());
holder.cb_categoryItem.setChecked(category.isCheckState());
}
#Override
public int getItemCount() {
return categoryList.size();
}
#Override
public void clearSelectAllFilters(Button allFilters) {
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView indexItemCategory;
public CheckBox cb_categoryItem;
public RelativeLayout category_item_rl;
public ViewHolder(#NonNull View itemView) {
super(itemView);
indexItemCategory = itemView.findViewById(R.id.indexItemCategory);
cb_categoryItem = itemView.findViewById(R.id.cb_categoryItem);
category_item_rl = itemView.findViewById(R.id.category_item_rl);
}
}
public void update() {
categoryList.forEach(category -> category.setCheckState(false));
notifyDataSetChanged();
}
}
Make a public method in adapter and then pass your new data with changed checked values to true, and then notify the adapter like shown below (or update the existing method with the code given below).
public void updateList(ArrayList<Category> categoryList) {
this.categoryList = categoryList;
notifyDataSetChanged();
}
then simply call this method wherever you need with the adapter object in your fragment.
I have been making an app that uses a recycler view in a fragment. how the contents of the recycler view have not been showing up. I am not sure what I have done wrong as the app does not crash when it is run. Please tell me what i need to do.
fragment_home.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"`enter code here`
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".Fragments.Home_Fragment">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/cetagory_recyclerview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorAccent"
android:elevation="3dp" />
</FrameLayout>
Home_Fragment.java
private RecyclerView categoryRecyclerView;
private CategoryAdapter categoryAdapter;
public Home_Fragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
categoryRecyclerView = view.findViewById(R.id.cetagory_recyclerview);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
categoryRecyclerView.setLayoutManager(layoutManager);
List<CategoryModel> categoryModelList = new ArrayList<CategoryModel>();
categoryModelList.add(new CategoryModel("Link","Home"));
categoryModelList.add(new CategoryModel("Link","Electronicse"));
categoryModelList.add(new CategoryModel("Link","Garments"));
categoryModelList.add(new CategoryModel("Link","Fashion"));
categoryModelList.add(new CategoryModel("Link","Toys"));
categoryModelList.add(new CategoryModel("Link","Sporte"));
categoryModelList.add(new CategoryModel("Link","Furniture"));
categoryModelList.add(new CategoryModel("Link","Wall Art"));
categoryModelList.add(new CategoryModel("Link","Appliance"));
categoryAdapter = new CategoryAdapter(categoryModelList);
categoryRecyclerView.setAdapter(categoryAdapter);
categoryAdapter.notifyDataSetChanged();
return view;
}
CategoryModel.java
private String categoryItemIconLink;
private String categoryName;
public CategoryModel(String categoryItemIconLink, String categoryName) {
this.categoryItemIconLink = categoryItemIconLink;
this.categoryName = categoryName;
}
public String getCategoryItemIconLink() {
return categoryItemIconLink;
}
public void setCategoryItemIconLink(String categoryItemIconLink) {
this.categoryItemIconLink = categoryItemIconLink;
}
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
CategoryAdapter.java
Context context;
private List<CategoryModel> categoryModelList = new ArrayList<CategoryModel>();
public CategoryAdapter(List<CategoryModel> categoryModerList) {
this.context = context;
this.categoryModelList = categoryModelList;
}
#NonNull
#Override
public CategoryAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int viewType) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.category_item, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull CategoryAdapter.ViewHolder holder, int position) {
String icon = categoryModelList.get(position).getCategoryItemIconLink();
String name = categoryModelList.get(position).getCategoryName();
holder.setCategoryName(name);
}
#Override
public int getItemCount() {
return categoryModelList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private ImageView categoryIcon;
private TextView categoryName;
public ViewHolder(#NonNull View itemView) {
super(itemView);
categoryIcon = itemView.findViewById(R.id.category_item_icon);
categoryName = itemView.findViewById(R.id.category_item_name);
}
private void setCategoryIcon() {
//Todo: set categoryIcone here
}
private void setCategoryName(String name) {
categoryName.setText(name);
}
}
You have not initialized your variables inside your adapter
Replace this...
public CategoryAdapter(List<CategoryModel> categoryModerList) {
this.context = context;
this.categoryModelList = categoryModelList;
}
With this..
public CategoryAdapter(Context context,List<CategoryModel> categoryModelList) {
this.context = context;
this.categoryModelList = categoryModelList;
}
then inside your fragment where you are calling adapters constructor add change this line.
from..
categoryAdapter = new CategoryAdapter(categoryModelList);
to..
categoryAdapter = new CategoryAdapter(getContext(),categoryModelList);
Today I've some question about mvvm and databinding on android,
I'm trying to bind object properties on view.
I've an Object (Model) with some properties, by example :
public String name;
public String title;
public int value;
I've a ViewModel with livedata like this :
MutableLiveData<Object> _obj = new MutableLiveData<>();
public LiveData<Object> obj = _obj;
And, at last, I've a view like this :
<layout>
<data>
<variable
name="viewModel">
type="com.sample.app.viewmodels.MainViewModel" />
</data>
<LinearLayout
... >
<TextView
android:text:="#{viewModel.obj.name}"
.../>
</LinearLayout>
</layout>
I saw that we can do that in a video from "Android Developers" about "LiveData" : https://youtu.be/OMcDk2_4LSk?t=102
She says that its possible in Android studio on 3.1+ versions.
But this is not working for me.
For this to work, your model class must extend BaseObservable class from databinding library. And you have to call notifyChange() on each setter method like this:
public class Object extends BaseObservable {
public String name;
public String title;
public int value;
public void setName(String name) {
this.name = name;
notifyChange();
}
public void setTitle(String title) {
this.title = title;
notifyChange();
}
public void setValue(int value) {
this.value = value;
notifyChange();
}
}
I want to achieve something like below, my list data is coming from a restful server. Everything is working except that the list is empty.
I used the following;
* Recyclerview Adaptor
* Created a pojo for list items, logs show that that the data is coming through from the server except that the list is not populated
//TransactionsFragment
public class TransactionsFragment extends Fragment {
View rootView;
RecyclerView recyclerView;
String transaction_amount;
String transaction_date_created;
public String authToken;
public TransactionsFragment() {
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_transactions_list, container, false);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
recyclerView = rootView.findViewById(R.id.rv_transactions);
recyclerView.setLayoutManager(linearLayoutManager);
TransactionListAdapter transactionListAdapter = new TransactionListAdapter(getContext(), getTransactions());
recyclerView.setAdapter(transactionListAdapter);
transactionListAdapter.notifyDataSetChanged();
return rootView;
}
private List<Transaction> getTransactions() {
List<Transaction> transactionList = new ArrayList<>();
/........
#Override
public void onNext(List<Transaction> transactions) {
Integer transactionSize = transactions.size();
for (int i =0;i<transactionSize;i++) {
transaction_amount = transactions.get(i).getAmount();
transaction_date_created = transactions.get(i).getDateCreated();
transactionList.add(new Transaction(transactions.get(i).getId(),null,transactions.get(i).getAmount(), transactions.get(i).getDateCreated(), transactions.get(i).getAccount()));
}
/// Data is shown here after running the app so it tells me that we are getting response from the server
Toast.makeText(getActivity(), "Transaction Date Created: " + transaction_date_created + "!", Toast.LENGTH_LONG).show();
}
#Override
public void onError(Throwable e) {
if (e instanceof HttpException) {
HttpException response = (HttpException) e;
int code = response.code();
String msg = response.message();
Toast.makeText(getActivity(), "Transaction Error message: " + msg + "!", Toast.LENGTH_LONG).show();
}
}
#Override
public void onComplete() {
}
});
//...
return transactionList;
}
}
//..TransactionListAdapter
public class TransactionListAdapter extends RecyclerView.Adapter {
private List transactionList;
private Context mContext;
public TransactionListAdapter(Context context, List<Transaction> transactions) {
this.mContext = context;
this.transactionList = transactions;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
RecyclerView.ViewHolder vh;
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_transactions_single, parent, false);
vh = new OriginalViewHolder(view);
return vh;
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int i) {
if (holder instanceof TransactionListAdapter.OriginalViewHolder) {
TransactionListAdapter.OriginalViewHolder view = (TransactionListAdapter.OriginalViewHolder) holder;
Transaction transaction = transactionList.get(i);
view.tvTransactionAmount.setText(transaction.getAmount());
view.tvTransactionDateCreated.setText(transaction.getDateCreated());
}
}
#Override
public int getItemCount() {
return transactionList.size();
}
public class OriginalViewHolder extends RecyclerView.ViewHolder{
ImageView imgTransactionType;
TextView tvTransactionName, tvTransactionAmount, tvTransactionDateCreated, tvDefaultCurrency, getTvTransactionUSD;
public OriginalViewHolder(View itemView) {
super(itemView);
tvTransactionDateCreated = itemView.findViewById(R.id.tv_transaction_date_created);
tvTransactionAmount = itemView.findViewById(R.id.tv_transaction_amount);
}
}
}
//..MainActivity
public class MainActivity extends AppCompatActivity implements
View parent_view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
checkConnection();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
}
setContentView(R.layout.activity_home);
initiateViews();
Fragment transFragment = new TransactionsFragment();
final FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.transactions_frame_container, transFragment);
transaction.addToBackStack(null);
transaction.commit();
}
private void initiateViews() {
parent_view = (CoordinatorLayout)findViewById(R.id.home_container);
home_container_id = R.id.frame_container;
}
private void loadFragment(Fragment fragment, Integer container_id) {
// create a FragmentManager
FragmentManager fm = getSupportFragmentManager();
// create a FragmentTransaction to begin the transaction and replace the Fragment
FragmentTransaction fragmentTransaction = fm.beginTransaction();
// replace the FrameLayout with new Fragment
fragmentTransaction.replace(container_id, fragment);
fragmentTransaction.commit(); // save the changes
}
}
//..fragment_transactions_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/grey_10" />
<View
android:layout_width="0dp"
android:layout_height="#dimen/spacing_middle" />
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/rv_transactions"
android:scrollbars="vertical"
android:scrollingCache="true"/>
</LinearLayout>
I am trying to learn ViewModel in android, in my first phase of learning I am trying to update UI (TextView) by using ViewModel and DataBinding. In ViewModel, I have an AsyncTask callback and it will invoke REST API call. I am getting the response from API call but the value in textview is not getting updated.
my ViewModel class:
public class ViewModelData extends ViewModel {
private MutableLiveData<UserData> users;
public LiveData<UserData> getUsers() {
if (users == null) {
users = new MutableLiveData<UserData>();
loadUsers();
}
return users;
}
public void loadUsers() {
ListTask listTask =new ListTask (taskHandler);
listTask .execute();
}
public Handler taskHandler= new Handler() {
#Override
public void handleMessage(Message msg) {
UserData userData = (UserData) msg.obj;
users.setValue(userData);
}
};
}
and my MainActivity class:
public class MainActivity extends AppCompatActivity implements LifecycleOwner {
private LifecycleRegistry mLifecycleRegistry;
private TextView fName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fName = (TextView)findViewById(R.id.text_name);
mLifecycleRegistry = new LifecycleRegistry(this);
mLifecycleRegistry.markState(Lifecycle.State.CREATED);
ViewModelData model = ViewModelProviders.of(this).get(ViewModelData.class);
model.getUsers().observe(this, new Observer<UserData>() {
#Override
public void onChanged(#Nullable UserData userData) {
Log.d("data"," = - - - - ="+userData.getFirstName());
}
});
}
#Override
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
}
and my data class:
public class UserData extends BaseObservable{
private String firstName ;
#Bindable
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
notifyPropertyChanged(BR.firstName);
}
}
and layout file
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<import type="android.view.View" />
<variable name="data" type="com.cgi.viewmodelexample.UserData"/>
</data>
<RelativeLayout
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.cgi.viewmodelexample.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#{data.firstName}"
android:id="#+id/text_name"/>
</RelativeLayout>
</layout>
I suggest to follow next basic principles:
don't overload data objects by business or presentation logic
only view model required to obtain data in presentation layer
view model should expose only ready to use data to presentation layer
(optional) background task should expose LiveData to deliver data
Implementation notes:
firstName is read only on view
lastName is editable on view
loadUser() is not threadsafe
we have error message when call save() method until data is not loaded
Don't overload data objects by business or presentation logic
Suppose, we have UserData object with first and last name. So, getters it's (usually) all what we need:
public class UserData {
private String firstName;
private String lastName;
public UserData(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
}
Only view model required to obtain data in presentation
To follow this suggestion we should to use only view model in data binding layout:
<?xml version="1.0" encoding="utf-8"?>
<layout 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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.vmtestapplication.MainActivity">
<data>
<import type="android.view.View" />
<!-- Only view model required -->
<variable
name="vm"
type="com.example.vmtestapplication.UserDataViewModel" />
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:animateLayoutChanges="true"
android:orientation="vertical">
<!-- Primitive error message -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#{vm.error}"
android:visibility="#{vm.error == null ? View.GONE : View.VISIBLE}"/>
<!-- Read only field (only `#`) -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#{vm.firstName}" />
<!-- Two-way data binding (`#=`) -->
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#={vm.lastName}" />
</LinearLayout>
</layout>
Note: you can use a few view models in one layout, but not raw data
View model should expose only ready to use data to presentation
This mean, you shouldn't to expose complex data objects (UserData in our case) directly from view model. Preferable to expose privative types which view can use as-is. In example below we don't need to hold UserData object because it used only to loading grouped data. We, probably, need to create UserData to save it but it depends on your repository implementation.
public class UserDataViewModel extends ViewModel {
private ListTask loadTask;
private final MutableLiveData<String> firstName = new MediatorLiveData<>();
private final MutableLiveData<String> lastName = new MediatorLiveData<>();
private final MutableLiveData<String> error = new MutableLiveData<>();
/**
* Expose LiveData if you do not use two-way data binding
*/
public LiveData<String> getFirstName() {
return firstName;
}
/**
* Expose MutableLiveData to use two-way data binding
*/
public MutableLiveData<String> getLastName() {
return lastName;
}
public LiveData<String> getError() {
return error;
}
#MainThread
public void loadUser(String userId) {
// cancel previous running task
cancelLoadTask();
loadTask = new ListTask();
Observer<UserData> observer = new Observer<UserData>() {
#Override
public void onChanged(#Nullable UserData userData) {
// transform and deliver data to observers
firstName.setValue(userData == null? null : userData.getFirstName());
lastName.setValue(userData == null? null : userData.getLastName());
// remove subscription on complete
loadTask.getUserData().removeObserver(this);
}
};
// it can be replaced to observe() if LifeCycleOwner is passed as argument
loadTask.getUserData().observeForever(observer);
// start loading task
loadTask.execute(userId);
}
public void save() {
// clear previous error message
error.setValue(null);
String fName = firstName.getValue(), lName = lastName.getValue();
// validate data (in background)
if (fName == null || lName == null) {
error.setValue("Opps! Data is invalid");
return;
}
// create and save object
UserData newData = new UserData(fName, lName);
// ...
}
#Override
protected void onCleared() {
super.onCleared();
cancelLoadTask();
}
private void cancelLoadTask() {
if (loadTask != null)
loadTask.cancel(true);
loadTask = null;
}
}
Background task should expose LiveData to deliver data
public class ListTask extends AsyncTask<String, Void, UserData> {
private final MutableLiveData<UserData> data= new MediatorLiveData<>();
public LiveData<UserData> getUserData() {
return data;
}
#Override
protected void onPostExecute(UserData userData) {
data.setValue(userData);
}
#Override
protected UserData doInBackground(String[] userId) {
// some id validations
return loadRemoiteUser(userId[0]);
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
private UserDataViewModel viewModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// get view model
viewModel = ViewModelProviders.of(this).get(UserDataViewModel.class);
// create binding
ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
// set view model to data binding
binding.setVm(viewModel);
// don't forget to set LifecycleOwner to data binding
binding.setLifecycleOwner(this);
// start user loading (if necessary)
viewModel.loadUser("user_id");
// ...
}
}
PS: try to use RxJava library instead of AsyncTask to perform background work.
You'll require to notify observer when you set value like this :
public class UserData extends BaseObservable{
private String firstName ;
#Bindable
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
notifyPropertyChanged(BR.firstName) // call like this
}
}
If you want binding layout to work then you have to set your view in binding way. Also set data in binding class.
public class MainActivity extends AppCompatActivity implements LifecycleOwner {
ActivityMainBinding binding;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
...
ViewModelData model = ViewModelProviders.of(this).get(ViewModelData.class);
...
binding.setData(model.getUsers());
}
}