Populate recyclerview with firebase through databinding - firebase

Can anyone help me!
i am a new developer getting this error. I am trying to populate a recyclerview with firebase through databinding in a fragment.
ProductListFragment.java
public class ProductListFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
RecyclerView recyclerView = (RecyclerView) inflater.inflate(R.layout.recycler_view, container, false);
FirebaseRecyclerAdapter adapter;
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
Firebase mFirebaseRef = new Firebase(Constants.FIREBASE_URL).child("subcategories").child("abc");
adapter = new FirebaseRecyclerAdapter<Product, ViewHolder>(
Product.class, R.layout.fragment_list_product, ViewHolder.class, mFirebaseRef) {
#Override
protected void populateViewHolder(ViewHolder viewHolder, Product product, int i) {
FragmentProductListBinding binding = viewHolder.getBinding();
binding.setProduct(product);
}
};
recyclerView.setAdapter(adapter);
return recyclerView;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
FragmentProductListBinding binding;
public ViewHolder (View rootView) {
super(rootView);
binding = DataBindingUtil.bind(rootView);
}
public FragmentProductListBinding getBinding() {
return binding;
}
}
}
Product.java contains the POJO
public class Product extends BaseObservable {
public String productTitle;
public String productUnit;
public String productMRP;
public String productSellingPrice;
public String productDescription;
public Product() {
}
#Bindable
public String getProductUnit() {
return productUnit;
}
public void setProductUnit(String productUnit) {
this.productUnit = productUnit;
}
#Bindable
public String getProductMRP() {
return productMRP;
}
public void setProductMRP(String productMRP) {
this.productMRP = productMRP;
}
#Bindable
public String getProductSellingPrice() {
return productSellingPrice;
}
public void setProductSellingPrice(String productSellingPrice) {
this.productSellingPrice = productSellingPrice;
}
#Bindable
public String getProductDescription() {
return productDescription;
}
public void setProductDescription(String productDescription) {
this.productDescription = productDescription;
}
#Bindable
public String getProductTitle() {
return productTitle;
}
public void setProductTitle(String productTitle) {
this.productTitle = productTitle;
}
}
fragment_list_product.xml
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable name="Product" type="com.abc.www.abc.model.Product"/>
</data>
<RelativeLayout
android:padding="#dimen/activity_horizontal_margin"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/product_image"
android:layout_width="40dp"
android:layout_height="40dp"
android:scaleType="centerCrop"
android:src="#drawable/ic_twitter"
android:contentDescription="#string/product_list_image_content_description"/>
<TextView
android:id="#+id/product_mrp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/colorPrimary"
android:ellipsize="end"
android:singleLine="true"
android:text="#{Product.productMRP}"
android:textAppearance="?attr/textAppearanceListItem"
android:textSize="14sp"
android:layout_gravity="center"
android:layout_below="#+id/product_title"
android:layout_toRightOf="#+id/product_image"
android:layout_toEndOf="#+id/product_image" />
<TextView
android:id="#+id/product_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginStart="16dp"
android:layout_toRightOf="#+id/product_image"
android:layout_toEndOf="#+id/product_image"
android:layout_marginEnd="16dp"
android:text="#{Product.productTitle}"
android:textAppearance="?attr/textAppearanceListItem"
android:textSize="16sp"
android:layout_gravity="top" />
<TextView
android:id="#+id/product_selling_price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/colorPrimary"
android:ellipsize="end"
android:singleLine="true"
android:text="#{Product.productSellingPrice}"
android:textAppearance="?attr/textAppearanceListItem"
android:textSize="14sp"
android:layout_gravity="center"
android:layout_below="#+id/product_title"
android:layout_toRightOf="#+id/product_mrp"
android:layout_toEndOf="#+id/product_mrp" />
</RelativeLayout>
here is the error which i am getting.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.abc.www.abc, PID: 1894
com.firebase.client.FirebaseException: Failed to bounce to type
at com.firebase.client.DataSnapshot.getValue(DataSnapshot.java:183)
at com.firebase.ui.FirebaseRecyclerAdapter.parseSnapshot(FirebaseRecyclerAdapter.java:161)
at com.firebase.ui.FirebaseRecyclerAdapter.getItem(FirebaseRecyclerAdapter.java:150)
at com.firebase.ui.FirebaseRecyclerAdapter.onBindViewHolder(FirebaseRecyclerAdapter.java:190)
at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:5453)
at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:5486)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4723)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4599)
at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:1988)
at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1384)
at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1347)
at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:574)
at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3003)
at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:2881)
at android.support.v7.widget.RecyclerView.consumePendingUpdateOperations(RecyclerView.java:1457)
at android.support.v7.widget.RecyclerView.access$400(RecyclerView.java:147)
at android.support.v7.widget.RecyclerView$1.run(RecyclerView.java:285)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
at android.view.Choreographer.doCallbacks(Choreographer.java:670)
at android.view.Choreographer.doFrame(Choreographer.java:603)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5422)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: com.fasterxml.jackson.databind.JsonMappingException: Can not instantiate value of type [simple type, class com.abc.www.abc.model.Product] from String value; no single-String constructor/factory method
at com.fasterxml.jackson.databind.deser.std.StdValueInstantiator._createFromStringFallbacks(StdValueInstantiator.java:428)
at com.fasterxml.jackson.databind.deser.std.StdValueInstantiator.createFromString(StdValueInstantiator.java:299)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromString(BeanDeserializerBase.java:1056)
at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:136)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:123)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:2888)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2034)
at com.firebase.client.DataSnapshot.getValue(DataSnapshot.java:181)
at com.firebase.ui.FirebaseRecyclerAdapter.parseSnapshot(FirebaseRecyclerAdapter.java:161) 
at com.firebase.ui.FirebaseRecyclerAdapter.getItem(FirebaseRecyclerAdapter.java:150) 
at com.firebase.ui.FirebaseRecyclerAdapter.onBindViewHolder(FirebaseRecyclerAdapter.java:190) 
at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:5453) 
at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:5486) 
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4723) 
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4599) 
at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:1988) 
at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1384) 
at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1347) 
at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:574) 
at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3003) 
at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:2881) 
at android.support.v7.widget.RecyclerView.consumePendingUpdateOperations(RecyclerView.java:1457) 
at android.support.v7.widget.RecyclerView.access$400(RecyclerView.java:147) 
at android.support.v7.widget.RecyclerView$1.run(RecyclerView.java:285) 
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858) 
at android.view.Choreographer.doCallbacks(Choreographer.java:670) 
at android.view.Choreographer.doFrame(Choreographer.java:603) 
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844) 
at android.os.Handler.handleCallback(Handler.java:739) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5422) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
it is the database which i am try to fetch from firebase.
subcategories{
abc{
product-description:"xxadasccdcnsdcnsdc"
product-mrp: 100
product-selling-price: 80
product-title:"Name"
product-unit: "100 meter"}
}
 

Use #JsonProperty("product-description") on top of your variables to match it with your db.
#JsonProperty("product-title")
public String productTitle;
#JsonProperty("product-unit")
public String productUnit;
The problem here is that the Jackson library used by Firebase Android client to serialize/deserialize JSON is not matching property names in the POJO and the DB

Use the #JsonIgnoreProperties(ignoreUnknown = true) on the top of your BaseObservable.class
#JsonIgnoreProperties(ignoreUnknown = true)
public class Product extends BaseObservable {
public Product() {
}
Refer this link for reference

Related

NullPointerException while populating views inside populateView using FirebaseListAdapter even when everything's right

The populateView method of FirebaseListAdapter is throwing null pointer exceptions while trying to set text of individual text views even though the layout id, view ids are correct. Here's the main activity
public class MainActivity extends AppCompatActivity {
private String dbUrlString = "MY_DB_URL_HERE";
private ListView listView;
private DatabaseReference databaseReference;
private FirebaseListAdapter<Video> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toast.makeText(getApplicationContext(),"Fetching",Toast.LENGTH_SHORT).show();
databaseReference = FirebaseDatabase.getInstance().getReferenceFromUrl(dbUrlString);
listView = (ListView) findViewById(R.id.list_view);
FirebaseListOptions<Video> options = new FirebaseListOptions.Builder<Video>()
.setQuery(databaseReference,Video.class)
.setLayout(R.layout.custom_item_layout)
.build();
adapter = new FirebaseListAdapter<Video>(options) {
#Override
protected void populateView(#NonNull View v, #NonNull final Video video, int position) {
TextView vname = (TextView) findViewById(R.id.video_name);
TextView vId = (TextView) findViewById(R.id.video_list_id);
vname.setText(video.getName());
vId.setText(video.getVideoId());
}
};
listView.setAdapter(adapter);
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
}
This is the main layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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">
<ListView
android:id="#+id/list_view"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
</LinearLayout>
These are the views in the custom_item_layout file with the respective ids:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:layout_height="wrap_content"
android:layout_width="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:weightSum="10"
android:layout_margin="10dp">
<ImageView
android:id="#+id/play_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_play_video_24dp"
android:layout_marginRight="10dp"
android:layout_centerInParent="true"
android:layout_alignParentLeft="true"/>
<TextView
android:id="#+id/video_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/play_icon"
android:text="Video title"
android:textSize="20sp"
android:layout_centerInParent="true"
android:textColor="#android:color/black"/>
<TextView
android:id="#+id/video_list_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="."
android:layout_alignParentRight="true"
android:layout_centerInParent="true"/>
</RelativeLayout>
This is the Video class:
package com.example.util;
public class Video {
private String name, videoId;
public Video(){
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVideoId() {
return videoId;
}
public void setVideoId(String videoId) {
this.videoId = videoId;
}
public Video(String name, String videoId) {
this.name = name;
this.videoId = videoId;
}
}
And this is the error I'm getting:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.example.gifapplication.MainActivity$1.populateView(MainActivity.java:44)
at com.example.gifapplication.MainActivity$1.populateView(MainActivity.java:39)
at com.firebase.ui.database.FirebaseListAdapter.getView(FirebaseListAdapter.java:121)
at android.widget.AbsListView.obtainView(AbsListView.java:2365)
at android.widget.ListView.measureHeightOfChildren(ListView.java:1408)
at android.widget.ListView.onMeasure(ListView.java:1315)
at android.view.View.measure(View.java:22759)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6788)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1514)
at android.widget.LinearLayout.measureHorizontal(LinearLayout.java:1167)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:687)
at android.view.View.measure(View.java:22759)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6788)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at androidx.appcompat.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:143)
at android.view.View.measure(View.java:22759)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6788)
at androidx.appcompat.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:403)
at android.view.View.measure(View.java:22759)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6788)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at android.view.View.measure(View.java:22759)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6788)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1514)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:806)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:685)
at android.view.View.measure(View.java:22759)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6788)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
at com.android.internal.policy.DecorView.onMeasure(DecorView.java:754)
at android.view.View.measure(View.java:22759)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2538)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1565)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1833)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1453)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7039)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:924)
at android.view.Choreographer.doCallbacks(Choreographer.java:732)
at android.view.Choreographer.doFrame(Choreographer.java:664)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:910)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6524)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:888)
Any help is appreciated. I've been going crazy trying to fix this. Tried a couple of fixes suggested online but nothing works. I don't even get why the views are null even when they're being instantiated with the right ids.

MVVM Cross Exception: Cannot Create Fragment. Use the MvxAppCompatViewPresenter when using Android Support Fragments

Im having trouble getting my fragments to run, and im getting the following exception. MVVM Cross Exception: Cannot Create Fragment. Use the MvxAppCompatViewPresenter when using Android Support Fragments.
Here is the MainViewModel, where it should navigate to the first fragment/ViewModel (ActionViewModel).
public class MainViewModel : BaseViewModel
{
public IMvxCommand<string> BottomNavigationItemSelectedCommand { get; private set; }
List<TabViewModel> _tabs;
public List<TabViewModel> Tabs
{
get => _tabs;
set => SetProperty(ref _tabs, value);
}
private readonly IMvxNavigationService _navigationService;
public MainViewModel(IMvxNavigationService navigationService)
{
_navigationService = navigationService;
BottomNavigationItemSelectedCommand = new MvxCommand<string>(BottomNavigationItemSelected);
var tabs = new List<TabViewModel>
{
Mvx.IoCProvider.IoCConstruct<ActionViewModel>(),
Mvx.IoCProvider.IoCConstruct<TaskViewModel>(),
Mvx.IoCProvider.IoCConstruct<KpiViewModel>(),
Mvx.IoCProvider.IoCConstruct<EisViewModel>(),
Mvx.IoCProvider.IoCConstruct<MenuViewModel>()
};
Tabs = tabs;
}
public override Task Initialize()
{
return base.Initialize();
}
// Android-only, not used on iOS
private void BottomNavigationItemSelected(string tabId)
{
if (tabId == null)
{
return;
}
foreach (var item in Tabs)
{
if (tabId == item.TabId)
{
_navigationService.Navigate(item);
break;
}
}
}
}
}
And this is the ActionFragment:
[MvxFragmentPresentation(typeof(MainViewModel), Resource.Id.fragment_content, true)]
[Register(nameof(ActionFragment))]
public class ActionFragment : BaseFragment<ActionViewModel>
{
//public static ActionFragment NewInstance() => new ActionFragment();
public override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
}
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
var view = inflater.Inflate(Resource.Layout.activity_actions, container, false);
return view;
}
}
This is the main activity layout:
<androidx.coordinatorlayout.widget.CoordinatorLayout
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"
xmlns:local="http://schemas.android.com/apk/res-auto"
android:id="#+id/parentView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="?android:attr/colorBackground">
<androidx.appcompat.widget.LinearLayoutCompat
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.appcompat.widget.ContentFrameLayout
android:id="#+id/fragment_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"/>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:labelVisibilityMode="labeled"
app:menu="#menu/bottom_nav_menu"
local:MvxBind="BottomNavigationSelectedBindingKey BottomNavigationItemSelectedCommand"/>
</androidx.appcompat.widget.LinearLayoutCompat>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
Could someone please let me know what I should do to solve this problem? I am new to this!
I found out that my problem was that I had to change the MainApplication.cs and Setup.cs classes.
from :
public class Setup : MvxAndroidSetup
to
public class Setup : MvxAppCompatSetup<App>
and from :
public class MainApplication : MvxAndroidApplication<MvxAndroidSetup<App>, App>
to
public class MainApplication : MvxAppCompatApplication<Setup, App>

Recyler view is not displaying anything

I set a recycler view for displaying data from firestore. I almost did everything right.but when I run my app it is not showing any data. Someone please help me. I attached my code here. I added setLinearlayoutmanager and set visibility to visible for recyclerview. I tried to get a data from user and use that data to retrieve content from the database.
display_data.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
android:background="#drawable/loginbg"
tools:context=".displayData">
<EditText
android:id="#+id/deptName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="41dp"
android:layout_marginTop="41dp"
android:ems="10"
android:hint="Enter dept eg:IT"
android:inputType="textPersonName"
android:textColorHint="#android:color/white"
android:textColorLink="#android:color/black"
tools:textColor="#android:color/background_light" />
<Button
android:id="#+id/getData"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/deptName"
android:layout_toEndOf="#+id/deptName"
android:background="#drawable/buttonshape"
android:text="Get" />
<android.support.v7.widget.RecyclerView
android:id="#+id/mainlist"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginTop="120dp"
android:visibility="visible" />
</RelativeLayout>
my java code display.java:
public class displayData extends AppCompatActivity implements View.OnClickListener {
RecyclerView mlist;
EditText deptName;
FirebaseFirestore db3;
public List<Users> usersList;
UsersListAdaptor usersListAdaptor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_data);
findViewById(R.id.getData).setOnClickListener(this);
deptName=findViewById(R.id.deptName);
mlist=(RecyclerView) findViewById(R.id.mainlist);
mlist.setHasFixedSize(true);
mlist.setLayoutManager(new LinearLayoutManager(this));
mlist.setAdapter(usersListAdaptor);
db3=FirebaseFirestore.getInstance();
usersList=new ArrayList<>();
usersListAdaptor=new UsersListAdaptor(usersList);
}
public void onClick(View view) {
switch (view.getId()){
case R.id.getData:
getdata();
break;
}
}
private void getdata() {
String deptname=deptName.getText().toString().trim().toLowerCase();
CollectionReference cref=db3.collection("bookingdetails");
Query q2=cref.whereEqualTo("dept",deptname);
q2.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot queryDocumentSnapshots, #Nullable FirebaseFirestoreException e) {
if(e!=null){
Toast.makeText(getApplicationContext(),"Something went wrong",Toast.LENGTH_SHORT).show();
}
for(DocumentChange doc:queryDocumentSnapshots.getDocumentChanges()){
Users users = doc.getDocument().toObject(Users.class);
usersList.add(users);
usersListAdaptor.notifyDataSetChanged();
}
}
});
}
}
users.class
package com.example.sarukesi.seminarbook;
public class Users {
String name;
String dept;
String time;
String date;
public Users() {
}
public Users(String name, String dept, String time, String date) {
this.name = name;
this.dept = dept;
this.time = time;
this.date = date;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDept() {
return dept;
}
public void setDept(String dept) {
this.dept = dept;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
UsersListAdapter:
public class UsersListAdaptor extends RecyclerView.Adapter<UsersListAdaptor.ViewHolder> {
List<Users> usersList;
public UsersListAdaptor(List<Users> usersList) {
this.usersList = usersList;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view=LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_item,viewGroup,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder viewHolder, int i) {
viewHolder.tname.setText(usersList.get(i).getName());
viewHolder.tdept.setText(usersList.get(i).getDept());
viewHolder.ttime.setText(usersList.get(i).getTime());
viewHolder.tdate.setText(usersList.get(i).getDate());
}
#Override
public int getItemCount() {
return usersList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
View mview;
public TextView tname,tdept,ttime,tdate;
public ViewHolder(#NonNull View itemView) {
super(itemView);
mview=itemView;
tname=itemView.findViewById(R.id.nametxt);
tdept=itemView.findViewById(R.id.depttxt);
ttime=itemView.findViewById(R.id.timetxt);
tdate=itemView.findViewById(R.id.datetxt);
}
}
}
list_item.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"
android:padding="20dp">
<TextView
android:id="#+id/nametxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="monospace"
android:padding="15dp"
android:text="Name"
android:textSize="16sp" />
<TextView
android:id="#+id/depttxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="serif-monospace"
android:padding="15dp"
android:text="Dept"
android:textSize="16sp" />
<TextView
android:id="#+id/timetxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="cursive"
android:padding="15dp"
android:text="Time"
android:textSize="16sp" />
<TextView
android:id="#+id/datetxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="serif-monospace"
android:padding="15dp"
android:text="Date"
android:textSize="16sp" />
</LinearLayout>
mlist.setAdapter(usersListAdaptor);
db3=FirebaseFirestore.getInstance();
usersList=new ArrayList<>();
usersListAdaptor=new UsersListAdaptor(usersList);
You create a new adapter after assigning the old one. Move the first line to the end of this block

Firebase ui 3.1.0 (Firebaselistadapter) No setter/field for mc_name found on class

I've tried my code in normal activity both images and text show. in fragment only image showing but the text is not showing (in both normal and fragment activity I've used same xml layout). I'm using firebaselistadpter for gridview and it works fine. I also tried using it with listview in fragment still images only showing but no text showing. (there is no Error message).
1- my java activity:
public class R_MainCat extends Fragment {
private GridView gridView;
private DatabaseReference myRef;
private FirebaseListAdapter<Sub_Category_Data> adapter;
private TextView mc_name;
private ImageView url;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_gridview, container, false);
rootView.setBackgroundColor(Color.WHITE);
myRef= FirebaseDatabase.getInstance().getReference("Main_Category");
Firebase.getDefaultConfig().setPersistenceEnabled(true);
gridView = (GridView) rootView.findViewById(R.id.gridview);
FirebaseListOptions<Sub_Category_Data> options = new FirebaseListOptions.Builder<Sub_Category_Data>()
.setQuery(myRef, Sub_Category_Data.class).setLayout(R.layout.gridview_icon).build();
adapter = new FirebaseListAdapter<Sub_Category_Data>(options) {
#Override
protected void populateView(View v, Sub_Category_Data model, int position) {
mc_name = v.findViewById(R.id.cat_name);
url = v.findViewById(R.id.img);
mc_name.setText(model.getName());
Picasso.with(getActivity()).load(model.getUrl()).into(url);
}
};
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
switch(i)
{
case 0:
R_DairyProds f1 = new R_DairyProds();
FragmentTransaction fragTransaction1 = getFragmentManager().beginTransaction();
fragTransaction1.replace(R.id.container_view,f1 );
fragTransaction1.addToBackStack(null);
fragTransaction1.commit();
break;
case 1:
R_Bakery f2 = new R_Bakery();
FragmentTransaction fragTransaction2 = getFragmentManager().beginTransaction();
fragTransaction2.replace(R.id.container_view,f2 );
fragTransaction2.addToBackStack(null);
fragTransaction2.commit();
break;
case 2:
R_Grocery f3 = new R_Grocery();
FragmentTransaction fT3 = getFragmentManager().beginTransaction();
fT3.replace(R.id.container_view,f3);
fT3.addToBackStack(null);
fT3.commit();
break;
case 3:
R_FruitsNVegs f4 = new R_FruitsNVegs();
FragmentTransaction fT4 = getFragmentManager().beginTransaction();
fT4.replace(R.id.container_view,f4);
fT4.addToBackStack(null);
fT4.commit();
break;
case 4:
R_CleanNWash f5 = new R_CleanNWash();
FragmentTransaction fT5 = getFragmentManager().beginTransaction();
fT5.replace(R.id.container_view,f5);
fT5.addToBackStack(null);
fT5.commit();
break;
}
}
});
return rootView;
}
#Override
public void onStart() {
super.onStart();
adapter.startListening();
}
#Override
public void onStop() {
super.onStop();
adapter.stopListening();
}
}
2-my xml layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/card_view"
android:focusable="false"
android:focusableInTouchMode="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
card_view:cardUseCompatPadding="true"
card_view:cardCornerRadius="4dp">
<RelativeLayout
android:descendantFocusability="blocksDescendants"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/img"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"/>
<me.grantland.widget.AutofitLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/img"
>
<TextView
android:id="#+id/cat_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="hello_world"
android:textColor="#000"
android:textSize="20sp"
android:gravity="center"
/>
</me.grantland.widget.AutofitLayout>
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
3- my Data model java:
public class Sub_Category_Data {
private String mc_name;
private String url;
public Sub_Category_Data() {
}
public void setName(String mc_name) {
this.mc_name = mc_name;
}
public String getName() {
return mc_name;
}
public void setUrl(String url) {
this.url = url;
}
public String getUrl() {
return url;
}
}
4- snapshot of the output:
text suppose to be showing under the image.
Output in fragment
I want my fragment to show the text data same as what is showing in this image
Output I've tested in normal Activity
5- database snapshot:
Database Image
does anyone have any clue? or have faced this issue before? because I'm lost since there is no error showing besides the fact it works fine in normal activity but text is not showing in the fragment. thank you in advance.
after looking over and over I noticed this in logcat
"No setter/field for mc_name found on class"
I've fixed the problem. It was in the model class getName() and SetName() methods I changed them to same name as the child key name in my firebase you can see picture of the database in the question above. so the new methods are getMc_name() and setMc_name().
public class Sub_Category_Data {
private String mc_name;
private String url;
public Sub_Category_Data() {
}
public String getMc_name() {
return mc_name;
}
public void setMc_name(String mc_name) {
this.mc_name = mc_name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
the output screen shot

Using a progressBar in a listview item

I have this listview and it's coded in a fragment class. When selecting a listview item it goes to another fragment and displays the details . But it takes several seconds to load the data because the data i display is using AsyncTask,so it takes some time to get data from the JSON and display . So i need to use a progressBar when an item is clicked in the listview and it should close when the data is ready to display. How can i do this? I referred several tutorials and tried many of them. But i couldn't accomplish what i'm looking for.Hope some of you can help me.
NewsFragment class
private ListView listView;
private ArrayList<BaseElement> News;
private LazyAdapter adapter;
private Activity activity;
private CommonVariable commonVariable;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.news_fragment, container,
false);
activity = this.getActivity();
commonVariable = (CommonVariable) activity.getApplication();
listView = (ListView) view.findViewById(R.id.list);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id){
android.support.v4.app.Fragment detail = new NewsDetailFragment();
android.support.v4.app.FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().add(R.id.content_frame, detail).addToBackStack("back").commit();
}
});
new BackGround().execute();
return view;
}
public class BackGround extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
News = JSONServices.getNewsDescription();
return null;
}
#Override
/* check again */
protected void onPostExecute(Void result) {
commonVariable.setNewsDescription(News);
adapter = new LazyAdapter(News, activity,Element.NEWS_LIST.getType());
listView.setAdapter(adapter);
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
}
}
NewsDetailFragment
public class NewsDetailFragment extends Fragment {
private View view1;
private ArrayList<BaseElement> newsdetail;
private LazyAdapter adapter;
private Activity activity;
private CommonVariable commonVariable;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.newsdetail_fragment, container,
false);
activity = this.getActivity();
commonVariable = (CommonVariable) activity.getApplication();
view1 = (View) view.findViewById(R.id.list);
new BackGround().execute();
return view;
}
public class BackGround extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
newsdetail = JSONServices.getNewsDescription();
return null;
}
#SuppressWarnings("unchecked")
#Override
/* check again */
protected void onPostExecute(Void result) {
commonVariable.setTheater(newsdetail);
adapter = new LazyAdapter(newsdetail, activity,Element.NEWS_DETAIL.getType());
((AdapterView<ListAdapter>) view1).setAdapter(adapter);
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
}
}
NewsList layout
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#color/grey"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:background="#drawable/listview" >
<ImageView
android:id="#+id/thumb_image"
android:layout_width="150dp"
android:layout_height="120dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="1dp"
android:layout_marginBottom="1dp"
/>
<TextView
android:id="#+id/news_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#ffffff"
android:layout_toRightOf="#+id/thumb_image"
android:layout_marginTop="10dp"
android:layout_marginLeft="7dp"
android:textStyle="bold"
android:textSize="20dp" />
<!-- <TextView
android:id="#+id/news_description"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#000000"
android:textStyle="bold"
android:layout_below="#+id/news_title"
android:textSize="15dp" /> -->
</LinearLayout>
</RelativeLayout>
NewsFragment layout
<?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="match_parent"
android:orientation="vertical"
android:background="#color/grey" >
<!-- <GridView
android:id="#+id/gridView2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:numColumns="2"
android:stretchMode="columnWidth"
android:layout_margin="5dp"
android:columnWidth="100dp"/> -->
<ListView
android:id="#+id/list"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:dividerHeight="10dp"
android:layout_margin="6dp">
</ListView>
</LinearLayout>
Add ProgressBar to your NewsFragment layout:
<ProgressBar
android:id="#+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:indeterminate="true"
android:visibility="gone" />
Then in onItemClick method change it's visibility to true progressBar.setVisibility(View.VISIBLE) to show it and change it's visibility to false to hide it progressBar.setVisibility(View.GONE) in onPostExecute of AsyncTask.
Ok i got it now. I modified my 2nd fragment like this. When an item in the listview is clicked it goes to my second class.So i added a progressBar to my second class and it worked!
public class NewsDetailFragment extends Fragment {
private View view1;
private ArrayList<BaseElement> newsdetail;
private LazyAdapter adapter;
private Activity activity;
private CommonVariable commonVariable;
private ProgressDialog dialog;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.newsdetail_fragment, container,
false);
activity = this.getActivity();
commonVariable = (CommonVariable) activity.getApplication();
view1 = (View) view.findViewById(R.id.list);
dialog = new ProgressDialog(NewsDetailFragment.this.getActivity());
dialog.setMessage("Loading News");
dialog.setCancelable(true);
new BackGround().execute();
return view;
}
public class BackGround extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
newsdetail = JSONServices.getNewsDescription();
return null;
}
#SuppressWarnings("unchecked")
#Override
/* check again */
protected void onPostExecute(Void result) {
commonVariable.setTheater(newsdetail);
adapter = new LazyAdapter(newsdetail, activity,Element.NEWS_DETAIL.getType());
((AdapterView<ListAdapter>) view1).setAdapter(adapter);
dialog.dismiss();
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
dialog.show();
super.onPreExecute();
}
}
}

Resources