Please help Me,
I am trying to create a specific type of recycler view which can have always 3 items in all kind of mobile phone. Whether that mobile is having 4 inch display or 6.5 inch display.
Please tell me if that is possible or not.
my code of xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="100dp"
android:id="#+id/recomended"
android:layout_margin="6dp"
android:background="#drawable/graycurverdbtn"
android:layout_height="170dp">
<ImageView
android:id="#+id/image"
android:layout_width="match_parent"
android:layout_height="85dp"
android:scaleType="fitCenter"
android:src="#drawable/mountain">
</ImageView>
<LinearLayout
android:layout_width="match_parent"
android:layout_margin="10dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="15dp"
android:gravity="center"
>
<TextView
android:id="#+id/pinkbtn"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:background="#drawable/pinkcurvedbtn"
android:gravity="center"
android:padding="3dp"
android:text="Recomended"
android:textColor="#color/white"
android:textSize="9dp">
</TextView>
</LinearLayout>
<LinearLayout
android:layout_below="#id/image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_margin="8dp"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_gravity="center"
android:gravity="center"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="normal"
android:layout_margin="6dp"
android:layout_gravity="center"
android:textSize="10sp"
android:textColor="#color/black"
android:text="Pest control">
</TextView>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/grey"></View>
<TextView
android:layout_margin="8dp"
android:id="#+id/shopname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="10dp"
android:textStyle="bold"
android:textColor="#color/black"
android:text="K02BgbhdAf">
</TextView>
<TextView
android:visibility="gone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableLeft="#drawable/graylocation"
android:text="Airport Road"
android:id="#+id/address"
android:textSize="18sp"
android:textStyle="normal">
</TextView>
</LinearLayout>
</LinearLayout>
</RelativeLayout>
This is my Adapter code
public class OurrecomendedAdapter extends RecyclerView.Adapter<OurrecomendedAdapter.MyViewHolder> {
private List<HomeResponse.Recommend> ourrecomendedlist = new ArrayList<>();
private Context context;
public static int recomendedid=0;
public OurrecomendedAdapter(List<HomeResponse.Recommend> list, Context context) {
this.ourrecomendedlist = list;
this.context = context;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.recomemdedservices_item, parent, false);
// itemView.setLayoutParams(new ViewGroup.LayoutParams((int) (parent.getWidth() * 0.3),ViewGroup.LayoutParams.MATCH_PARENT));
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, #SuppressLint("RecyclerView") int position) {
holder.title.setText(ourrecomendedlist.get(position).getCategory().getSlug());
holder.shopname.setText(ourrecomendedlist.get(position).getCategory().getName());
Picasso.get().load(ourrecomendedlist.get(position).getImage()).into(holder.image, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError(Exception e) {
}
});
holder.recomended.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(ourrecomendedlist.get(position).getCategory().getName().toString().equalsIgnoreCase("salon for women") || ourrecomendedlist.get(position).getCategory().getName().toString().equalsIgnoreCase("salon for men")){
AppCompatActivity activity = (AppCompatActivity) context;
WomensalonlistFragment subc = new WomensalonlistFragment();
Bundle args = new Bundle();
args.putString("id", ourrecomendedlist.get(position).getProductcategoryId().toString());
args.putString("title", ourrecomendedlist.get(position).getName());
subc.setArguments(args);
activity.getSupportFragmentManager().beginTransaction().addToBackStack(null).
replace(R.id.nav_host_fragment, subc).commit();
}
else
{
typeListid= ourrecomendedlist.get(position).getId().toString();
Intent intent= new Intent(context, ProductdetailsActivity.class);
intent.putExtra("productId",typeListid);
context.startActivity(intent);
HomeFragment.vendormainid=ourrecomendedlist.get(position).getId().toString();
}
}
});
}
#Override
public int getItemCount() {
return this.ourrecomendedlist.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView name,title,shopname,address,pinkbtn;
Button addtocart;
ImageView image;
RelativeLayout recomended;
MyViewHolder(View itemView) {
super(itemView);
addtocart=itemView.findViewById(R.id.addtocart);
image=itemView.findViewById(R.id.image);
title=itemView.findViewById(R.id.title);
shopname=itemView.findViewById(R.id.shopname);
address=itemView.findViewById(R.id.address);
recomended=itemView.findViewById(R.id.recomended);
name=itemView.findViewById(R.id.name);
pinkbtn=itemView.findViewById(R.id.pinkbtn);
}
}
}
in this i need to display our output as 3 items in each aspect-ratio mobile.
but I'm unable to achieve that. If I'm opening in big screen mobile then it's showing 3.5 items and in small device some times it's showing 2.75 items.
Kindly help me in that how to achieve that exact output.
When I use a recycler view and adapter, the adapter doesn't let the app to install and it causes a crash. I commented out the adapter in my main activity and it started successfully but with adapter it doesn't work.
My adapter class is here:
public class AdapterFree extends RecyclerView.Adapter<AdapterFree.ViewHolder> {
Context context;
List<ModelFree> modelFrees;
public AdapterFree(Context context, List<ModelFree> modelFrees) {
this.context = context;
this.modelFrees = modelFrees;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_free, parent, false);
return new AdapterFree.ViewHolder(view);
//return new ViewHolder(view);
//return new AdapterFree(context, modelFrees).new ViewHolder(view);
/*ViewHolder vh = new ViewHolder(view);
return vh;*/
//here I tried a few codes but didn't help
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
ModelFree free = modelFrees.get(position);
DecimalFormat decimalFormat = new DecimalFormat("###,###");
String price = decimalFormat.format(Integer.valueOf(free.getPrice()));
holder.textPriceFree.setText(price + " " + "$");
holder.textVisitFree.setText(free.getVisit());
holder.textTitle.setText(free.getTitle());
holder.textFreePrice.setText(free.getFree());
//holder.imageFree.setImageResource(free.getImage());
holder.imageFree.setImageResource(Integer.parseInt(free.getImage()));
}
#Override
public int getItemCount() {
return modelFrees.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
LinearLayout linearLayout;
CardView cardViewFree;
ImageView imageFree;
TextView textTitle, textVisitFree, textPriceFree, textFreePrice;
Typeface typeface = Typeface.createFromAsset(itemView.getContext().getAssets(), "fonts/vaziri.ttf");
public ViewHolder(#NonNull View itemView) {
super(itemView);
linearLayout = itemView.findViewById(R.id.linearLayout);
cardViewFree = itemView.findViewById(R.id.cardViewFree);
imageFree = itemView.findViewById(R.id.imageFree);
textTitle = itemView.findViewById(R.id.textTitle);
textTitle.setTypeface(typeface);
textVisitFree = itemView.findViewById(R.id.textVisitFree);
textVisitFree.setTypeface(typeface);
textPriceFree = itemView.findViewById(R.id.textPriceFree);
textPriceFree.setTypeface(typeface);
textFreePrice = itemView.findViewById(R.id.textFreePrice);
textFreePrice.setTypeface(typeface);
}
}
}
my main activity :
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
ImageView image1;
CoordinatorLayout coordinator;
DrawerLayout drawerLayout;
NavigationView navigationView;
Toolbar mainToolbar;
RecyclerView recyclerFree, recyclerOnly, recyclerVisit, recyclerSales;
AdapterFree adapterFree;
List<ModelFree> modelFreeList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
coordinator = findViewById(R.id.coordinator);
drawerLayout = findViewById(R.id.drawerLayout);
navigationView = findViewById(R.id.navigationView);
mainToolbar = findViewById(R.id.main_toolbar);
image1 = findViewById(R.id.image1);
recyclerFree = findViewById(R.id.recyclerFree);
recyclerOnly = findViewById(R.id.recyclerOnly);
recyclerVisit = findViewById(R.id.recyclerVisit);
recyclerSales = findViewById(R.id.recyclerSales);
setSupportActionBar(mainToolbar);
ActionBarDrawerToggle toggle;
toggle = new ActionBarDrawerToggle(this, drawerLayout, mainToolbar, R.string.open, R.string.close);
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
navigationView.setNavigationItemSelectedListener(this);
Picasso.get().load(R.drawable.lexuse).into(image1);
setDataFree();
}
private void setDataFree() {
adapterFree = new AdapterFree(getApplicationContext(), modelFreeList);
recyclerFree.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.HORIZONTAL, false));
recyclerFree.setAdapter(adapterFree);
modelFreeList.add(new ModelFree(1, String.valueOf(R.drawable.lexus2), "lexus2", "10", "10000$", "5$"));
modelFreeList.add(new ModelFree(2, String.valueOf(R.drawable.lexus3), "lexus3", "20", "20000$", "6$"));
modelFreeList.add(new ModelFree(3, String.valueOf(R.drawable.lexus3), "lexus3", "30", "30000$", "7$"));
modelFreeList.add(new ModelFree(4, String.valueOf(R.drawable.lexus4), "lexus4", "40", "40000$", "8$"));
modelFreeList.add(new ModelFree(5, String.valueOf(R.drawable.lexus5), "lexus5", "50", "50000$", "9$"));
modelFreeList.add(new ModelFree(6, String.valueOf(R.drawable.lexusd), "lexus6", "60", "60000$", "5$"));
adapterFree.notifyDataSetChanged();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.option_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
int optionId = item.getItemId();
switch (optionId) {
case R.id.page2:
startActivity(new Intent(this, MainActivity2.class));
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
}
my model class :
public class ModelFree {
int id;
String image;
String title;
String visit;
String price;
String free;
public ModelFree(int id, String image, String title, String visit, String price, String free) {
this.id = id;
this.image = image;
this.title = title;
this.visit = visit;
this.price = price;
this.free = free;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getVisit() {
return visit;
}
public void setVisit(String visit) {
this.visit = visit;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getFree() {
return free;
}
public void setFree(String free) {
this.free = free;
}
}
xml layout that I write recycler view:
<?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"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.appcompat.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/purple_200"
android:id="#+id/main_toolbar"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
<ImageView
android:layout_width="match_parent"
android:layout_height="200dp"
android:id="#+id/image1"
android:scaleType="fitXY"/>
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#e7e7e7">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="60dp"
app:cardCornerRadius="10dp"
app:cardElevation="1dp"
app:cardBackgroundColor="#color/teal_200"
android:layout_marginLeft="60dp"
android:layout_marginRight="60dp"
android:layout_marginTop="20dp"
android:layout_marginBottom="10dp"
android:id="#+id/cardCategory">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="horizontal"
android:layoutDirection="rtl">
<ImageView
android:layout_width="34dp"
android:layout_height="34dp"
android:src="#drawable/ic_baseline_format_list_bulleted_24"
app:tint="#color/cardview_light_background" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:textSize="18sp"
android:textColor="#color/white"
android:text="Category"/>
</LinearLayout>
</androidx.cardview.widget.CardView>
<androidx.appcompat.widget.AppCompatTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textSize="16sp"
android:gravity="left"
android:text="Special Discounts"
android:textColor="#color/black"
android:layout_marginLeft="15dp"/>
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/recyclerFree"
android:layoutDirection="ltr"
android:layout_marginTop="10dp"
android:layout_marginLeft="3dp"/>
<androidx.appcompat.widget.AppCompatTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textSize="16sp"
android:gravity="left"
android:text="Just Here"
android:textColor="#color/black"
android:layout_marginLeft="15dp"/>
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/recyclerOnly"
android:layoutDirection="ltr"
android:layout_marginTop="10dp"
android:layout_marginLeft="3dp"/>
<ImageView
android:layout_width="match_parent"
android:layout_height="180dp"
android:layout_marginTop="10dp"
android:scaleType="fitXY"
android:src="#drawable/lexusa"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="140dp"
android:layout_marginTop="5dp"
android:layout_marginBottom="15dp"
android:orientation="horizontal">
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.5"
android:layout_margin="1dp">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY"
android:src="#drawable/lexusb"/>
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.5"
android:layout_margin="1dp">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY"
android:src="#drawable/lexusc"/>
</LinearLayout>
</LinearLayout>
<androidx.appcompat.widget.AppCompatTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textSize="16sp"
android:textColor="#color/black"
android:gravity="left"
android:text="Most visited"
android:layout_marginLeft="15dp"/>
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layoutDirection="ltr"
android:layout_marginTop="10dp"
android:layout_marginLeft="3dp"
android:id="#+id/recyclerVisit"/>
<androidx.appcompat.widget.AppCompatTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textSize="16sp"
android:textColor="#color/black"
android:gravity="left"
android:text="Most sales"
android:layout_marginLeft="15dp"/>
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layoutDirection="ltr"
android:layout_marginTop="10dp"
android:layout_marginLeft="3dp"
android:id="#+id/recyclerSales"/>
</LinearLayout>
</androidx.core.widget.NestedScrollView>
my xml layout for items:
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.material.card.MaterialCardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="170dp"
android:layout_height="260dp"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:clickable="true"
android:id="#+id/cardViewFree"
android:layout_margin="4dp"
android:orientation="vertical"
app:cardCornerRadius="2dp"
app:cardElevation="1dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/linearLayout"
android:visibility="visible"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="match_parent"
android:layout_height="170dp"
android:scaleType="centerInside"
android:id="#+id/imageFree"
android:src="#drawable/lexus2"/>
</RelativeLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="start"
android:id="#+id/textTitle"
android:layout_margin="3dp"
android:gravity="left"
android:text="lexus2"
android:textColor="#color/black"
android:textSize="12dp"
android:singleLine="true" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layoutDirection="ltr"
android:orientation="horizontal">
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.4"
android:gravity="center_vertical"
android:layoutDirection="ltr"
android:orientation="horizontal"
android:padding="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="12dp"
android:id="#+id/textVisitFree"
android:text="10"
android:textColor="#color/black"/>
<ImageView
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_marginRight="5dp"
android:src="#drawable/ic_baseline_visibility_24"
app:tint="#color/black" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.6"
android:gravity="center_vertical|right"
android:padding="5dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/textPriceFree"
android:gravity="center_vertical|right"
android:text="123000$"
android:textColor="#color/black"
android:textSize="12sp"/>
</LinearLayout>
</LinearLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/textFreePrice"
android:padding="1dp"
android:layout_marginRight="5dp"
android:gravity="right|center_vertical"/>
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
I found the problem and solved it.
the main problem was about MaterialCardView, so I changed my codes to this:
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.material.card.MaterialCardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="170dp"
android:layout_height="260dp"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:card_view="http://schemas.android.com/tools"
app:cardCornerRadius="2dp"
app:cardElevation="1dp"
android:clickable="true"
android:id="#+id/cardViewFree"
android:layout_margin="4dp"
android:orientation="vertical"
android:theme="#style/Theme.MaterialComponents.DayNight"
style="#style/Widget.MaterialComponents.CardView">
<LinearLayout
............
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
after that I changed the part of the codes of Model class to this:
public class ModelFree {
int id;
int image;
String title;
String visit;
int price;
String free;
so I write some of variables to "int"
of course I changed this method in MainActivity:
private void setDataFree() {
adapterFree = new AdapterFree(getApplicationContext(), modelFreeList);
recyclerFree.setLayoutManager(new
LinearLayoutManager(getApplicationContext(), LinearLayoutManager.HORIZONTAL,
false));
recyclerFree.setAdapter(adapterFree);
modelFreeList.add(new ModelFree(1, R.drawable.lexus2, "lexus2", "10",
100000, "5%"));
modelFreeList.add(new ModelFree(2, R.drawable.lexus3, "lexus3", "20", 20000,
"6$"));
modelFreeList.add(new ModelFree(3, R.drawable.lexus3, "lexus3", "30", 30000,
"7$"));
modelFreeList.add(new ModelFree(4, R.drawable.lexus4, "lexus4", "40", 40000,
"8$"));
modelFreeList.add(new ModelFree(5, R.drawable.lexus5, "lexus5", "50", 50000,
"9$"));
modelFreeList.add(new ModelFree(6, R.drawable.lexusd, "lexus6", "60", 60000,
"5$"));
adapterFree.notifyDataSetChanged();
}
finally I commented some lines in Adapter class because they caused error and I couldn't solve that:
public class MyViewHolder extends RecyclerView.ViewHolder {
LinearLayout linearLayout;
CardView cardViewFree;
ImageView imageFree;
TextView textTitle, textVisitFree, textPriceFree, textFreePrice;
//Typeface typeface =
Typeface.createFromAsset(itemView.getContext().getAssets(),
String.valueOf(R.font.times));
public MyViewHolder(#NonNull View itemView) {
super(itemView);
linearLayout = itemView.findViewById(R.id.linearLayout);
cardViewFree = itemView.findViewById(R.id.cardViewFree);
imageFree = itemView.findViewById(R.id.imageFree);
textTitle = itemView.findViewById(R.id.textTitle);
//textTitle.setTypeface(typeface);
textVisitFree = itemView.findViewById(R.id.textVisitFree);
//textVisitFree.setTypeface(typeface);
textPriceFree = itemView.findViewById(R.id.textPriceFree);
//textPriceFree.setTypeface(typeface);
textFreePrice = itemView.findViewById(R.id.textFreePrice);
//textFreePrice.setTypeface(typeface);
}
}
I tried to retrive images from firebase with correct url link. The RecyclerView keep shown "first" info of Food which is cookie-milk-cup:
This is my firebase data structure:
all_uploaded_image //directory
|-cookie milk cup
|-description: "yes!" //shown successful
|-image_uri: "content://com.android.providers.media.documents..." //no necessary in this case
|-name: "cookie milk cup" //shown successful
|-price: "1.20" //not shown
|-uploader_uid: "GSsY4tEo5ZZpS8kkJEpWGLCbFmC3" //no necessary in this case
fish n chips //recursive only on cookie milk cup, so nothing appear in here
|-description: "delicious fc"
|-image_uri: "content://com.android.providers.media.documents..."
|-name: "fish n chips"
|-price: "1.20"
|-uploader_uid: "GSsY4tEo5ZZpS8kkJEpWGLCbFmC3"
I am using android with java, want to get the info from firebase using fragment.
This is the AllFOodFragment.java
public class AllFoodFragment extends Fragment {
private View contactsView;
private ArrayList<Food> entries;
private DatabaseReference ref;
private FirebaseDatabase dbr;
private FoodAdapter adapter;
private RecyclerView recycler_view;
public AllFoodFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View contactsView = inflater.inflate(R.layout.home_main, container, false); //v
recycler_view = (RecyclerView) contactsView.findViewById(R.id.recycler_view);
recycler_view.setHasFixedSize(true);
recycler_view.setItemAnimator(new DefaultItemAnimator());
final FragmentActivity ga = getActivity(); //2a
LinearLayoutManager lm = new LinearLayoutManager(ga); //2
recycler_view.setLayoutManager(lm);
entries = new ArrayList<Food>();
ref = FirebaseDatabase.getInstance().getReference().child("all_uploaded_image");
ref.addChildEventListener(new ChildEventListener(){
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
for(DataSnapshot ds: dataSnapshot.getChildren()) {
//Log.e("Count " ,"" + dataSnapshot.getChildrenCount());
Food data = dataSnapshot.getValue(Food.class);
//data.setPrice(dataSnapshot.child("price").getValue().toString());
//data.setImageUrl(dataSnapshot.child("image_uri").getValue().toString());
entries.add(data);
//Log.e("Get All Description", data.get_price());
}
adapter = new FoodAdapter(getActivity(), entries);
adapter.notifyDataSetChanged();
adapter.setListFood(entries);
//3; No adapter attached in here, but program runs
recycler_view.setAdapter(adapter);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(getContext(), databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
return contactsView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
public void onViewCreated(View view, #Nullable Bundle savedUbstabceState){
super.onViewCreated(view, savedUbstabceState);
this.contactsView = view;
}
}
And, this is FoodAdapter.java
public class FoodAdapter extends RecyclerView.Adapter<FoodAdapter.FoodViewHolder> {
private Context m_context;
private ArrayList<Food> m_listFood = new ArrayList<Food>();
public FoodAdapter(Context context, ArrayList<Food> food_list) {//m_context, food_list
this.m_context = context;
this.m_listFood = food_list;
}
#NonNull
#Override
public FoodViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_fragment_all_food, parent, false);
return new FoodViewHolder(v);
}
public class FoodViewHolder extends RecyclerView.ViewHolder{
public ImageView FoodIcon;
public TextView FoodName;
public TextView FoodDescription;
public TextView FoodPrice;
public Button Fooddetail;
public FoodViewHolder (View itemView){
super(itemView);
FoodIcon = (ImageView)itemView.findViewById(R.id.thumbnail); //icon
FoodName = itemView.findViewById(R.id.foodname);
FoodDescription = itemView.findViewById(R.id.fooddescription);
FoodPrice = itemView.findViewById(R.id.foodprice);
Fooddetail = itemView.findViewById(R.id.fooddetail);
}
public void onClick(View view) {
}
}
#Override
public void onBindViewHolder(#NonNull FoodViewHolder holder, int position) {
Food f = m_listFood.get(position);
holder.FoodName.setText(f.get_name());
holder.FoodDescription.setText(f.get_description());
holder.FoodPrice.setText(f.get_price());
holder.FoodPrice.setText(f.get_url());
//Picasso.get().load(m_listFood.get(position).get_url()).fit().into(holder.FoodIcon);
Glide.with(m_context).load(f.get_url()).into(holder.FoodIcon); //getListFood().get(position).get_icon()
}
#Override
public int getItemCount() {
return m_listFood.size();
}
public Context get_context() {
return m_context;
}
public void setListFood(ArrayList<Food> m_listFood){
this.m_listFood = m_listFood;
}
}
this is item_fragment_all_food.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:cardCornerRadius="4dp"
android:layout_marginTop="4dp"
android:layout_marginBottom="4dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView //icon not shown, white
android:id="#+id/thumbnail"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_marginStart="8dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#android:drawable/star_big_on" />
<TextView
android:id="#+id/foodname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_marginStart="191dp"
android:layout_marginTop="16dp"
android:text="Name"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/thumbnail"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/fooddescription"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/foodname"
android:layout_marginEnd="86dp"
android:layout_marginBottom="-91dp"
android:text="Description"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/thumbnail"
app:layout_constraintTop_toBottomOf="#+id/foodname" />
<TextView
android:id="#+id/foodprice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_marginTop="85dp"
android:layout_marginEnd="95dp"
android:text="Price"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.487"
app:layout_constraintStart_toEndOf="#+id/thumbnail"
app:layout_constraintTop_toBottomOf="#+id/fooddescription"
app:layout_constraintVertical_bias="0.0" />
<Button
android:id="#+id/fooddetail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_marginEnd="79dp"
android:layout_marginBottom="16dp"
android:background="#color/colorPrimary"
android:text="Detail"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.496"
app:layout_constraintStart_toEndOf="#+id/thumbnail"
app:layout_constraintTop_toBottomOf="#+id/foodprice"
app:layout_constraintVertical_bias="0.0" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
And, this is activity_main.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"
tools:context=".MainActivity">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</com.google.android.material.appbar.AppBarLayout>
<LinearLayout
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<EditText
android:autofillHints="email"
android:layout_margin="15dp"
android:inputType="textEmailAddress"
android:hint="Enter Email"
android:id="#+id/et_email"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<EditText
android:layout_margin="15dp"
android:inputType="textPassword"
android:hint="Enter Password"
android:id="#+id/et_password"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:layout_margin="15dp"
android:hint="Register"
android:id="#+id/btn_register"
android:layout_width="match_parent"
android:onClick="click_to_register_new_user"
android:layout_height="wrap_content" />
<Button
android:layout_margin="15dp"
android:hint="Login"
android:id="#+id/btn_login"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="137dp"
android:text="#string/reset_string" />
</RelativeLayout>
Lastly, my Food Model
public class Food {
public String name;
public String description;
public String price;
public String img_url;
public String icon;
public Food() {
//empty
}
public Food(String name, String description, String price, String imageUrl) {
if (name.trim().equals("")) {
name = "No Name";
}
this.name = name;
this.description = description;
this.price = price;
this.img_url = imageUrl;
}
public String get_name() {
return name;
}
public String get_description() {
return description;
}
public String get_price() {
return price;
}
public String get_icon() {
return icon;
}
public String get_url() {
return img_url;
}
public void setPrice(String price) {
this.price = price;
}
public void setImageUrl(String imageUrl) {
img_url = imageUrl;
}
public void set_icon(String icon) {
this.icon = icon;
}
}
The error I get is E/RecyclerView: No adapter attached; skipping layout
and No setter/field for image_uri found on class com.example.hungrystomach.Model.Food [but really I do not want image_uri shown in my recyclerview so I skip the TextView]
The recyclerView does not have any Image shown even I've FoodIcon with thumbnail in FOodAdaper.java. I've tried for three weeks already still no hope. I suppose to get all the info I need. I know it is little bit long but any suggestion and answer would appreciate.
I have something wrong with recyclerView. It doesn't show all items. For example, recyclerView has 12 items, but it shows like 10 with a half items. I can set paddingBottom for it, and it shows all items, but I don't think it is a good way. How can I fix it? I think maybe it becouse of my buttons above it.
acctivity_search_coin.xml
<?xml version="1.0" encoding="utf-8"?>
<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">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:paddingBottom="50dp"
app:layout_constraintTop_toBottomOf="#+id/lianerForThreeBtn" />
<Button
android:id="#+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:background="#FFFFFF"
android:paddingStart="5dp"
android:paddingEnd="5dp"
android:textSize="15sp"
android:drawablePadding="6dp"
android:gravity="center_vertical"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<LinearLayout
android:id="#+id/lianerForThreeBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintTop_toBottomOf="#+id/button2">
<Button
android:id="#+id/btn1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:background="#FFFFFF"
android:layout_weight="1"/>
<Button
android:id="#+id/btn2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:background="#FFFFFF"
android:layout_weight="1"/>
<Button
android:id="#+id/btn3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:background="#FFFFFF"
android:layout_weight="1"/>
</LinearLayout>
</android.support.constraint.ConstraintLayout>
activity_recycler_view_adapter_coin_list.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/recyclerImage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp">
<TextView
android:id="#+id/denominationTV"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_marginStart="20dp"
android:layout_marginEnd="8dp"
android:layout_toEndOf="#+id/secondIV"
android:textSize="20sp" />
<TextView
android:id="#+id/yearTV"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/denominationTV"
android:layout_alignStart="#+id/denominationTV"
android:layout_alignParentEnd="true"
android:layout_marginStart="0dp"
android:layout_marginTop="6dp"
android:layout_marginEnd="8dp"
android:textSize="20sp" />
<ImageView
android:id="#+id/firstIV"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_alignParentStart="true"
android:layout_marginStart="0dp"/>
<ImageView
android:id="#+id/secondIV"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_marginStart="4dp"
android:layout_toEndOf="#+id/firstIV"/>
</RelativeLayout>
RecyclerViewAdapterCoinList.java
public class RecyclerViewAdapterCoinList extends RecyclerView.Adapter<RecyclerViewAdapterCoinList.ViewHolder> {
private List<String> mYearList;
private List<String> mDenominationList;
private List<String> mImageList1;
private List<String> mImageList2;
private LayoutInflater mInflater;
private ItemClickListener mClickListener;
Context context;
RecyclerViewAdapterCoinList(Context context, List<String> denominationList,List<String> yearList, List<String> imageList1,List<String> imageList2) {
this.mInflater = LayoutInflater.from(context);
this.mYearList = yearList;
this.mDenominationList = denominationList;
this.mImageList1 = imageList1;
this.mImageList2 = imageList2;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.activity_recycler_view_adapter_coin_list, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
String year = mYearList.get(position);
String denomination = mDenominationList.get(position);
String imageString1 = mImageList1.get(position);
String imageString2 = mImageList2.get(position);
holder.denominationTV.setText(denomination);
holder.yearTV.setText(year);
try {
Glide.with(context).load(imageString1).into(holder.firstIV);
Glide.with(context).load(imageString2).into(holder.secondIV);
}catch (Exception e){e.printStackTrace();}
}
// total number of rows
#Override
public int getItemCount() {
return mDenominationList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView denominationTV;
TextView yearTV;
ImageView firstIV;
ImageView secondIV;
ViewHolder(View itemView) {
super(itemView);
denominationTV = itemView.findViewById(R.id.denominationTV);
yearTV = itemView.findViewById(R.id.yearTV);
firstIV = itemView.findViewById(R.id.firstIV);
secondIV = itemView.findViewById(R.id.secondIV);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
}
}
String getItem(int id) {
return mDenominationList.get(id);
}
void setClickListener(ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
public interface ItemClickListener {
void onItemClick(View view, int position);
}
}
Try adding app:layout_constraintBottom_toBottomOf="parent" in the recycler view and also make the height of the recycler view to be 0dp (match_constraint).
I have an adapter class which loads items dynamically and shows them in a RecyclerView. My problem is that when I swipe up and down the recycler view the images get mixed and are shown in wrong positions (i.e. in other item's view).
For example, I have an item X and another item Y. Now when I swipe up and down the image which was to be shown in item Y get shown in item X and the same happens with other attributes.
Here is my adapter class:
public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.NewsViewHolder> {
private DatabaseReference refDNewsTable= FirebaseDatabase.getInstance().getReference().child("news_feeds");
private StorageReference refStorage = FirebaseStorage.getInstance().getReferenceFromUrl("firebase_url_comes_here");
private Context mContext;
private List<NewsModel> newsList;
public class NewsViewHolder extends RecyclerView.ViewHolder {
public TextView nHeading, nDes,nDaTi;
public ImageView nImg;
public NewsViewHolder(View view) {
super(view);
nHeading = (TextView) view.findViewById(R.id.tv_newsHeadline);
nDes = (TextView) view.findViewById(R.id.tv_nDes);
nImg = (ImageView) view.findViewById(R.id.iv_nImg);
nDaTi=(TextView) view.findViewById(R.id.tv_nDaTi);
}
}
public NewsAdapter(Context mContext, List<NewsModel> newsList) {
this.mContext = mContext;
this.newsList = newsList;
}
#Override
public NewsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.news_model, parent, false);
return new NewsViewHolder(itemView);
}
#Override
public void onBindViewHolder(final NewsViewHolder holder, int position) {
NewsModel news = newsList.get(position);
holder.nHeading.setText(news.getnHeading());
if(news.hasDes()) {
holder.nDes.setText(news.getnDes());
}else{
holder.nDes.setVisibility(View.GONE);
}
if(news.hasImg()){
// Reference to an image file in Firebase Storage
StorageReference imgReference =refStorage.child(news.getnId());
// Load the image using Glide
Glide.with(mContext)
.using(new FirebaseImageLoader())
.load(imgReference)
.into(holder.nImg);
}else{
holder.nImg.setVisibility(View.GONE);
}
holder.nDaTi.setText(news.getnDaTi());
}
public void downloadFile(final NewsViewHolder holder){
try {
final File localFile = File.createTempFile("images", "jpg");
refStorage.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
Bitmap bitmap = BitmapFactory.decodeFile(localFile.getAbsolutePath());
holder.nImg.setImageBitmap(bitmap);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
}
});
} catch (IOException e ) {}
}
#Override
public int getItemCount() {
return newsList.size();
}
}
And this is my news_model.xml file:
<?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"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:padding="10dp"
android:layout_margin="4dp"
card_view:cardPreventCornerOverlap="true"
card_view:cardElevation="16dp"
android:layout_height="wrap_content"
android:id="#+id/card_view"
android:layout_gravity="center"
card_view:cardCornerRadius="0dp">
<LinearLayout
android:orientation="vertical"
android:background="#color/cBgNews"
android:padding="0dp"
android:gravity="center_horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:padding="10dp"
card_view:cardElevation="6dp"
card_view:cardBackgroundColor="#color/cNewsHeadline"
android:layout_height="wrap_content"
android:layout_marginTop="0dp"
android:layout_marginStart="10dp"
android:layout_marginEnd="10dp"
android:layout_marginBottom="0dp"
android:id="#+id/card_des"
android:layout_gravity="center"
card_view:cardCornerRadius="0dp">
<TextView
android:text="TextView"
android:textSize="17sp"
android:textStyle="normal"
android:padding="10dp"
android:maxLines="3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#color/cWhite"
android:gravity="start"
android:layout_margin="0dp"
android:id="#+id/tv_newsHeadline" />
</android.support.v7.widget.CardView>
<LinearLayout
android:orientation="vertical"
android:gravity="center_horizontal"
android:background="#0000"
android:paddingEnd="6dp"
android:paddingStart="6dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="wrap_content"
android:layout_marginBottom="0dp"
android:layout_height="wrap_content"
android:maxHeight="300dp"
app:srcCompat="#mipmap/ic_launcher"
android:scaleType="fitCenter"
android:layout_gravity="center_horizontal"
android:id="#+id/iv_nImg" />
<TextView
android:text="Description..."
android:maxLines="8"
android:textSize="16sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="end"
android:padding="10dp"
android:textColor="#color/cBlack"
android:id="#+id/tv_nDes" />
<TextView
android:text="Date and Time"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="10sp"
android:textColor="#999999"
android:gravity="end"
android:id="#+id/tv_nDaTi" />
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
NOTE: I am using firebase to receive the content directly and haven't created any kind of database in my app yet. i.e. it loads data every time it needs it directly in adapter class.