RecyclerView inside RecyclerView scroll in same direction - android

I have 2 recycler views, let's call then recycler1 and recycler2 (purple background). The squares with yellow background are elements of recycler2 which has an instance inside of each element of recycler1. What I'm trying to achieve is that it should scroll elements of recycler2 on purple area fling and recycler1 outside it. I made it with horizontal scroll (which is very easy) but can't do it vertically. I tried to set and reset nested scrolling and behaviour and whatever but can't make it work.
Below the code (a lot of it):
InnerItem Layout
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout android:layout_height="50dp"
android:layout_width="60dp"
android:background="#38f"
android:padding="4dp"
xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:background="#ffff00"
android:id="#+id/tag_text_view"
android:text="Some Content"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout>
Nested recycler item
<?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:background="#cfcfcf"
>
<TextView
android:id="#+id/first_name_textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="10dp"
android:textSize="20sp"
android:text="New Text"
android:background="#1ad"
/>
<TextView
android:id="#+id/last_name_textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="New Text"
android:gravity="center"
android:layout_margin="10dp"
android:textSize="16sp"
android:padding="10dp"
android:background="#d65"
/>
<android.support.v7.widget.RecyclerView
android:id="#+id/nested_recycler"
android:layout_width="match_parent"
android:layout_height="100dp"
android:background="#659"
>
</android.support.v7.widget.RecyclerView>
</LinearLayout>
Activity
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
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">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</RelativeLayout>
InnerItem
package com.yrs.androidltx.features.adapterviews.nestedrecycler;
public class InnerItem {
String tag;
public InnerItem(String tag) {
this.tag = tag;
}
}
InnerItem Adapter
package com.yrs.androidltx.features.adapterviews.nestedrecycler;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.yrs.androidltx.R;
import java.util.List;
public class InnerItemAdapter extends RecyclerView.Adapter<InnerItemViewHolder> {
List<InnerItem> innerItemList;
public InnerItemAdapter(List<InnerItem> innerItemList) {
this.innerItemList = innerItemList;
}
#Override
public InnerItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater
.from(parent.getContext())
.inflate(R.layout.inner_item, parent, false);
InnerItemViewHolder viewHolder = new InnerItemViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(InnerItemViewHolder holder, int position){
holder.tagTextVIew.setText(innerItemList.get(position).tag);
}
#Override
public int getItemCount() {
return innerItemList.size();
}
}
InnerItem ViewHolder
package com.yrs.androidltx.features.adapterviews.nestedrecycler;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
import com.yrs.androidltx.R;
public class InnerItemViewHolder extends RecyclerView.ViewHolder {
TextView tagTextVIew;
public InnerItemViewHolder(View itemView) {
super(itemView);
tagTextVIew = (TextView) itemView.findViewById(R.id.tag_text_view);
}
}
Person
package com.yrs.androidltx.features.adapterviews.nestedrecycler;
public class Person {
private String firstName;
private String lastName;
public Person(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
Person ViewHolder
package com.yrs.androidltx.features.adapterviews.nestedrecycler;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
import com.yrs.androidltx.R;
public class PersonViewHolder extends RecyclerView.ViewHolder {
//Keep package visibility
TextView firstNameTextView;
TextView lastNameTextView;
RecyclerView nestedRecyclerView;
public PersonViewHolder(View itemView) {
super(itemView);
firstNameTextView = (TextView) itemView.findViewById(R.id.first_name_textView);
lastNameTextView = (TextView) itemView.findViewById(R.id.last_name_textView);
nestedRecyclerView = (RecyclerView) itemView.findViewById(R.id.nested_recycler);
}
}
Person Adapter
package com.yrs.androidltx.features.adapterviews.nestedrecycler;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.yrs.androidltx.R;
import java.util.ArrayList;
import java.util.List;
public class PersonAdapter extends RecyclerView.Adapter<PersonViewHolder> {
List<Person> personList;
public PersonAdapter(List<Person> personList) {
this.personList = personList;
}
#Override
public PersonViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater
.from(parent.getContext())
.inflate(R.layout.nested_recycler_item, parent, false);
PersonViewHolder personViewHolder = new PersonViewHolder(view);
return personViewHolder;
}
#Override
public void onBindViewHolder(PersonViewHolder holder, int position) {
holder.firstNameTextView.setText(personList.get(position).getFirstName());
holder.lastNameTextView.setText(personList.get(position).getLastName());
holder.nestedRecyclerView.setLayoutManager(new GridLayoutManager(holder.nestedRecyclerView.getContext(), 3, GridLayoutManager.VERTICAL, false ));
holder.nestedRecyclerView.setAdapter(new InnerItemAdapter(initTagList()));
}
#Override
public int getItemCount() {
return personList.size();
}
private List<InnerItem> initTagList() {
List<InnerItem> tagList = new ArrayList<>();
tagList.add(new InnerItem("android"));
tagList.add(new InnerItem("iOS"));
tagList.add(new InnerItem("windows"));
tagList.add(new InnerItem("linux"));
tagList.add(new InnerItem("NetBSD"));
tagList.add(new InnerItem("NetWare"));
//repeat few times...
return tagList;
}
}
Main activity
package com.yrs.androidltx.features.adapterviews.nestedrecycler;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import com.yrs.androidltx.R;
import com.yrs.androidltx.activities.base.BaseActivity;
import java.util.ArrayList;
import java.util.List;
public class WithNestedRecyclerActivity extends BaseActivity {
private RecyclerView recyclerView;
private PersonAdapter personAdapter;
private RecyclerView.LayoutManager layoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_with_recycler);
recyclerView = (RecyclerView) findViewById(R.id.recycler);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
personAdapter = new PersonAdapter(initDataSet());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(personAdapter);
}
private List<Person> initDataSet() {
List<Person> personList = new ArrayList<>();
personList.add(new Person("Ned","Flanders"));
personList.add(new Person("Homer","Simpson"));
personList.add(new Person("Bart","Simpson"));
personList.add(new Person("Mr","Burns"));
//... repeat few times
return personList;
}
}

Related

App crashes on attaching fetched data from Retrofit to adapter

I am working with Retrofit. I followed a tutorial and did exactly what he said. Response is working perfectly in a single TextView but not in RecyclerView. When I added an adapter class, it start crashing. I read logcat file too but didn't seem helpful. The app crashes without showing any error or exception.
Here is my main XML class with a RecyclerView.
<?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"
android:orientation="vertical">
<!-- <ScrollView-->
<!-- android:layout_width="match_parent"-->
<!-- android:layout_height="match_parent">-->
<!-- <TextView-->
<!-- android:layout_width="match_parent"-->
<!-- android:layout_height="wrap_content"-->
<!-- android:id="#+id/text1"-->
<!-- android:layout_marginTop="5dp"-->
<!-- android:layout_marginStart="2dp">-->
<!-- </TextView>-->
<!-- </ScrollView>-->
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recview"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
</androidx.recyclerview.widget.RecyclerView>
</LinearLayout>
My main class is working fine with a for loop to print data in one TextView but not for adapter or RecyclerView.
package com.example.apipractice;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
public class MainActivity extends AppCompatActivity {
apiInterface instanceforAPI;
LinearLayoutManager linearLayoutManager;
//TextView txt;
RecyclerView recview;
adapter ad;
List<jsonData> data = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//txt = findViewById(R.id.text1);
recview = findViewById(R.id.recview);
linearLayoutManager = new LinearLayoutManager(this);
recview.setLayoutManager(linearLayoutManager);
instanceforAPI = retrofitInstance.getRetrofit().create(apiInterface.class);
instanceforAPI.getdata().enqueue(new Callback<List<jsonData>>() {
#Override
public void onResponse(Call<List<jsonData>> call, Response<List<jsonData>> response) {
if(response.body().size()>0){
Toast.makeText(MainActivity.this,"yayy",Toast.LENGTH_LONG).show();
data.addAll(response.body());
ad = new adapter(data);
ad.notifyDataSetChanged();
recview.setAdapter(ad);
// for (int index=0;index<data.size();index++){
// txt.setText(txt.getText()+ " SRNo.: "+data.get(index).getTitle()+" \n" + data.size());
//
// }
}
else
{
Toast.makeText(MainActivity.this,"No yayy",Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<List<jsonData>> call, Throwable t) {
Toast.makeText(MainActivity.this,t.getMessage(),Toast.LENGTH_LONG).show();
}
});
}
}
SingleRow design XML class (single.xml) is as follows:
<?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="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:rotationX="8">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/t1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"
></TextView>
<TextView
android:id="#+id/t2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="title"
></TextView>
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
Adapter class (adapter.java) for fetching data is as follows:
package com.example.apipractice;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class adapter extends RecyclerView.Adapter<adapter.myviewholder> {
List<jsonData> data;
public adapter(List<jsonData> data){
this.data = data;
}
#Override
public myviewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.single,parent,false );
return new myviewholder(v);
}
#Override
public void onBindViewHolder(#NonNull adapter.myviewholder holder, int position) {
holder.t1.setText((int) data.get(position).getId());
holder.t2.setText( data.get(position).getTitle());
}
#Override
public int getItemCount() {
return data.size();
}
public class myviewholder extends RecyclerView.ViewHolder
{
TextView t1,t2;
public myviewholder(#NonNull View itemView) {
super(itemView);
t1= itemView.findViewById(R.id.t1);
t2 = itemView.findViewById(R.id.t2);
}
}
}
The following class is for retrofit instance, retrofitInstance.java:
package com.example.apipractice;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class retrofitInstance {
private static Retrofit retrofit;
private static final String commonURL = "https://jsonplaceholder.typicode.com";
public static Retrofit getRetrofit() {
if(retrofit ==null) {
retrofit = new Retrofit.Builder().baseUrl(commonURL).addConverterFactory(GsonConverterFactory.create()).build();
}
return retrofit;
}
}
This interface class (apiInterfce.java) is for the API get call:
package com.example.apipractice;
import java.util.List;
import retrofit2.Call;
import retrofit2.http.GET;
public interface apiInterface {
#GET("/posts?type=json")
Call<List<jsonData>> getdata();
}
My model class, jsonData.java:
package com.example.apipractice;
public class jsonData {
private float userId;
private float id;
private String title;
private String body;
// Getter Methods
public float getUserId() {
return userId;
}
public float getId() {
return id;
}
public String getTitle() {
return title;
}
public String getBody() {
return body;
}
// Setter Methods
public void setUserId(float userId) {
this.userId = userId;
}
public void setId(float id) {
this.id = id;
}
public void setTitle(String title) {
this.title = title;
}
public void setBody(String body) {
this.body = body;
}
}
Don't pass int value in setText() method. Because it consider int value as a resource id.
Please do as follow:
#Override
public void onBindViewHolder(#NonNull adapter.myviewholder holder, int position) {
holder.t1.setText(data.get(position).getId() + "");
holder.t2.setText( data.get(position).getTitle());
}

ViewPager2 Adapter is being called Twice

I am starting with Android java development and I am facing a issue on the ViewPager2 implementation.
On my app I have a ViewPager2 and I am inflate on it a layout which has a RecycleView.
The problem is, when I turn the ViewPager2 from page 0 to page 1, the adapter execulte onBindViewHolder twice, jumping from adapter position 0 to 1 and imediatelly from position 1 to 2. (ViewPager2 position stay on 1)
As I am populating the RecycleView with a Volley DB consult, this theard start only after the ViewPAger2 Adapter finish its works (after adapter execulte onBindViewHolder twice). So, only the ViewPager2 position 2 is populated (twice), ViewPager2 page 1 stay empty.
Thus, I kindly ask your help to avoid adapter execute onBindViewHolder twice once ViewPAger2 change. Or makes Volley executes its thread when the adapter position change from 0 to 1 and again when it change from 1 to 2.
Please help me since I have 5 days working around this problem without success.
See belwo my codes:
MY VIEWPAGER2 ADAPTER (Adapter_Department)
package br.com.portosaue.portosaueapp;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class Adapter_Department extends RecyclerView.Adapter<Adapter_Department.UserViewHolder> {
Context mContext;
private RecyclerView rcv_products;
private RecyclerView.Adapter mAdapter;
private LinearLayoutManager mLayoutManager;
ViewPager2 vpg_productList;
List<Department> departmentList;
String Host_IP;
String ProductComment;
public MyAdapter(Context mContext, List<Department> departmentList) {
this.mContext = mContext;
this.departmentList = departmentList;
}
#NonNull
#Override
public UserViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
Host_IP = "192.168.0.100";
View view = LayoutInflater.from(mContext).inflate(R.layout.products_list, parent, false);
return new UserViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull UserViewHolder holder, int position) {
productsList(departmentList.get(position).getName());
}
#Override
public int getItemCount() {
return departmentList.size();
}
public class UserViewHolder extends RecyclerView.ViewHolder {
public UserViewHolder(#NonNull final View itemView) {
super(itemView);
rcv_products = itemView.findViewById(R.id.rcv_Products);
vpg_productList = ((Activity) mContext).findViewById(R.id.vpg_Products);
}
}
private void productsList(String department){
//SELECTING URL
String json_products;
switch (department) {
case "Salao":
json_products = "http://" + Host_IP + "/getSalon.php";
break;
case "Cozinha":
json_products = "http://" + Host_IP + "/getKitchen.php";
break;
case "Copa":
json_products = "http://" + Host_IP + "/getDrink.php";
break;
case "Churrasqueira":
json_products = "http://" + Host_IP + "/getBarbecue.php";
break;
case "Caixa":
json_products = "http://" + Host_IP + "/getCash.php";
break;
default:
json_products = "http://" + Host_IP + "/getProducts";
}
//VOLLEY / FETCH / JSONOBJECT
StringRequest stringRequest = new StringRequest(Request.Method.GET, json_products,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//converting the string to json array object
JSONArray array = new JSONArray(response);
ArrayList<Func_LoadProduct> loadproduct = new ArrayList<Func_LoadProduct>();
Func_LoadProduct p;
String ImagePath;
//traversing through all the object
for (int i = 0; i < array.length(); i++) {
//getting product object from json array
JSONObject product = array.getJSONObject(i);
//adding the product to product list
ImagePath = "http://" + Host_IP + "/PS APP Images/" + product.getString("Imagem");
p = new Func_LoadProduct(product.getInt("ID"),
product.getString("Nome"),
product.getDouble("Preco"),
ImagePath,
"");
loadproduct.add(p);
}
rcv_products=((Activity)mContext).findViewById(R.id.rcv_Products);
rcv_products.setHasFixedSize(true);
mLayoutManager=new LinearLayoutManager(mContext);
mAdapter=new Adapter_Products(loadproduct);
rcv_products.setLayoutManager(mLayoutManager);
rcv_products.setAdapter(mAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
Volley.newRequestQueue(mContext).add(stringRequest);
}
}
VIEWPAGER2 CLASS (Products)
package br.com.portosaue.portosaueapp;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.viewpager2.widget.ViewPager2;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class Products extends AppCompatActivity {
ViewPager2 vpg_products;
List<Department> departmentList;
Adapter_Department adapterDepartment;
String TableNumb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_products);
vpg_products = findViewById(R.id.vpg_Products);
departmentList = new ArrayList<>();
departmentList.add(new Department("Salon"));
departmentList.add(new Department("Kitchen"));
departmentList.add(new Department("Bar"));
adapterDepartment = new Adapter_Department(this, departmentList);
vpg_products.setAdapter(adapterDepartment);
}
}
VIEWPAGER2 LAYOUT (activity_departments.xml)
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Products"
android:orientation="vertical">
<include
android:id="#+id/tbr_toobar"
layout = "#layout/toolbar"/>
<androidx.viewpager2.widget.ViewPager2
android:id="#+id/vpg_Products"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_below="#+id/tbr_toobar"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/tbr_toobar"
app:layout_constraintVertical_bias="1.0" />
</androidx.constraintlayout.widget.ConstraintLayout>
RECYCLEVIEW ADAPTER (Adapter_Products)
package br.com.portosaue.portosaueapp;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class Adapter_Products extends RecyclerView.Adapter<Adapter_Products.MyViewHolder>{
private ArrayList<Func_LoadProduct> mProductList;
public static class MyViewHolder extends RecyclerView.ViewHolder {
public ImageView img_ProductImage;
public TextView txv_ProductName;
public TextView txv_ProductPrice;
public TextView txv_ProductID;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
img_ProductImage = itemView.findViewById(R.id.imv_ProductImage);
txv_ProductName = itemView.findViewById(R.id.txv_ProductName);
txv_ProductPrice = itemView.findViewById(R.id.txv_ProductPrice);
txv_ProductID = itemView.findViewById(R.id.txv_ProcutID);
}
}
public Adapter_Products( ArrayList<Func_LoadProduct> productList){
this.mProductList=productList;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.product_line, parent, false);
MyViewHolder evh = new MyViewHolder(v);
return evh;
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
Func_LoadProduct currentItem = mProductList.get(position);
Picasso.get().load(mProductList.get(position).getProductImageName()).into(holder.img_ProductImage);
holder.txv_ProductName.setText(currentItem.getProductName());
holder.txv_ProductPrice.setText("R$ " + Double.toString(currentItem.getProductPrice()));
holder.txv_ProductID.setText("ID: " + Integer.toString(currentItem.getProductID()));
}
#Override
public int getItemCount() {
return mProductList.size();
}
}
RECYCLEVIEW LAYOUT (product_list.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">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rcv_Products"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="0dp"
android:layout_marginTop="0dp" />
</RelativeLayout>
ITEMS CLASS (Func_LoadProduct)
package br.com.portosaue.portosaueapp;
public class Func_LoadProduct {
private int ProductID;
private String ProductName;
private double ProductPrice;
private String ProductImageName;
private String ProductComment;
public Func_LoadProduct(int productID, String productName, double productPrice, String productImageName, String productComment){
this.ProductID = productID;
this.ProductName = productName;
this.ProductPrice = productPrice;
this.ProductImageName = productImageName;
this.ProductComment = productComment;
}
//SET
public void setProductID(int productID) {
this.ProductID = productID;
}
public void setProductName(String productName) {
this.ProductName = productName;
}
public void setProductPrice(double productPrice) {
this.ProductPrice = productPrice;
}
public void setProductImageName(String productImageName) { this.ProductImageName = productImageName; }
public void setProductComment(String productComment) { this.ProductComment = productComment; }
//GET
public int getProductID() {
return this.ProductID;
}
public String getProductName() {
return this.ProductName;
}
public double getProductPrice() {
return this.ProductPrice;
}
public String getProductImageName() { return this.ProductImageName; }
public String getProductComment() { return this.ProductComment; }
}
ITEMS LAYOUT (product_line.xml)
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
app:cardCornerRadius="4dp"
android:layout_marginTop="2dp"
android:layout_marginBottom="2dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="4dp">
<ImageView
android:id="#+id/imv_ProductImage"
android:layout_width="60dp"
android:layout_height="60dp"
android:padding="2dp"
android:scaleType="fitXY"
tools:srcCompat="#tools:sample/avatars"/>
<TextView
android:id="#+id/txv_ProductName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="64dp"
android:layout_marginTop="2dp"
android:textColor="#android:color/black"
android:textSize="20sp"
android:layout_weight="10"
android:text="Produto"
android:textAppearance="#style/TextAppearance.AppCompat.Large"/>
<TextView
android:id="#+id/txv_ProductPrice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="#+id/txv_ProductName"
android:layout_alignParentTop="true"
android:layout_marginStart="2dp"
android:layout_marginTop="31dp"
android:layout_weight="3"
android:text="Valor"
android:textSize="15sp" />
<TextView
android:id="#+id/txv_ProcutID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/txv_ProductPrice"
android:layout_alignParentStart="true"
android:layout_marginStart="347dp"
android:layout_marginBottom="0dp"
android:layout_weight="1"
android:text="ID"
android:textSize="15sp" />
</RelativeLayout>
</androidx.cardview.widget.CardView>

Data not showing up in recyclerview from firebase using firebase ui

I am using firebase ui to load data from firebase database to recycler view but the data is not showing up inside the recycler view.
This is my fragment
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.database.FirebaseDatabase;
import com.infinity.houseestimatorandmodeler.R;
import com.infinity.houseestimatorandmodeler.databinding.FragmentBuildersBinding;
public class BuilderFragment extends Fragment {
private BuilderAdapter adapter;
public BuilderFragment() {
// Required empty public constructor
}
#Override
public void onStart() {
super.onStart();
adapter.startListening();
}
#Override
public void onStop() {
super.onStop();
adapter.stopListening();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
FragmentBuildersBinding databinding= DataBindingUtil.inflate(inflater, R.layout.fragment_builders, container, false);
FirebaseRecyclerOptions<buildersModel> options =
new FirebaseRecyclerOptions.Builder<buildersModel>()
.setQuery(FirebaseDatabase.getInstance().getReference().child("builders"), buildersModel.class)
.build();
adapter = new BuilderAdapter(options);
databinding.buildersRecyclerView.setAdapter(adapter);
return databinding.getRoot();
}
}`
this is my adapter class that is adapting the data for showing in the recycler view
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.infinity.houseestimatorandmodeler.R;
public class BuilderAdapter extends FirebaseRecyclerAdapter<buildersModel, BuilderAdapter.BuilderViewHolder> {
public BuilderAdapter(#NonNull FirebaseRecyclerOptions<buildersModel> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull BuilderViewHolder holder, int i, #NonNull buildersModel builder) {
holder.name.setText(builder.getName());
holder.builderClass.setText(builder.getBuilderClass());
holder.address.setText(builder.getAddress());
}
#NonNull
#Override
public BuilderViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.builders_card, parent, false);
return new BuilderViewHolder(view);
}
class BuilderViewHolder extends RecyclerView.ViewHolder{
TextView name, builderClass, address;
public BuilderViewHolder(#NonNull View itemView) {
super(itemView);
name = itemView.findViewById(R.id.nameofbuilder);
builderClass = itemView.findViewById(R.id.classOfBuilder);
address = itemView.findViewById(R.id.address);
}
}
}
this is my model class for data coming from firebase `
class buildersModel
{
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getBuilderClass() {
return builderClass;
}
public void setBuilderClass(String builderClass) {
this.builderClass = builderClass;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public buildersModel(String address, String builderClass, String name) {
this.address = address;
this.builderClass = builderClass;
this.name = name;
}
String address;
String builderClass;
String name;}
this is my firebase database
card view for individual element in recycler view
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:background="#drawable/rounded_cards"
android:layout_height="wrap_content"
android:layout_margin="10dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<androidx.appcompat.widget.AppCompatImageView
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_margin="20dp"
android:src="#drawable/ic_builder" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#drawable/rounded_cards">
<TextView
android:id="#+id/nameofbuilder"
android:layout_marginTop="8dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/baloo"
android:textSize="20dp"
android:padding="2dp"
android:text="Abdul Shakoor"/>
<TextView
android:id="#+id/classOfBuilder"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:textSize="15sp"
android:textColor="#342C2C"
android:padding="2dp"
android:text="Location Islambad"/>
<TextView
android:id="#+id/address"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15sp"
android:textColor="#342C2C"
android:padding="2dp"
android:text="Address : I10 Islamabad near Rahimia mosque"/>
</LinearLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
recycler view layout
<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"
>
<data>
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:layout_width="match_parent"
android:layout_height="250dp"
android:src="#drawable/ic_builders"
android:background="#75CDDC"
/>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/buildersRecyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"/>
</LinearLayout>
You didn't set the RecyclerView LayoutManger, you can either set it in you layout
<androidx.recyclerview.widget.RecyclerView
....
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
Or in the fragment
databinding.buildersRecyclerView.setLayoutManager(new LinearLayoutManager(requireActivity()));

Switch Between layouts on list to grid recyclerview

How to switch layout when RecyclerView is List to Grid or vice versa.
build.gradle app level
compile 'com.android.support:recyclerview-v7:25.0.0'
compile 'com.android.support:cardview-v7:25.0.0'
compile 'com.android.support:design:25.0.0'
compile 'com.jakewharton:butterknife:8.4.0'
apt 'com.jakewharton:butterknife-compiler:8.4.0'
compile 'com.github.bumptech.glide:glide:3.7.0'
compile 'de.hdodenhof:circleimageview:2.0.0'
ItemModel.java
public class ItemModel {
private String name;
private String imagePath;
public ItemModel(){
}
public ItemModel(String name, String imagePath) {
this.name = name;
this.imagePath = imagePath;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImagePath() {
return imagePath;
}
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
}
MainActivity.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
public class MainActivity extends AppCompatActivity {
String imageUrl[] = Constant.image;
String names[] = Constant.name;
#BindView(R.id.my_recycler_view)
RecyclerView mRecyclerView;
private RecyclerAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
initView();
}
private void initView() {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
List list = getList();
mAdapter = new RecyclerAdapter(this, list);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
}
private List getList() {
List list = new ArrayList<>();
for (int i = 0; i < imageUrl.length; i++) {
ItemModel model = new ItemModel();
model.setName(names[i]);
model.setImagePath(imageUrl[i]);
list.add(model);
}
return list;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.switch_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case android.R.id.home:
finish();
break;
case R.id.switch_view:
supportInvalidateOptionsMenu();
boolean isSwitched = mAdapter.toggleItemViewType();
mRecyclerView.setLayoutManager(isSwitched ? new LinearLayoutManager(this) : new GridLayoutManager(this, 2));
mAdapter.notifyDataSetChanged();
break;
}
return super.onOptionsItemSelected(item);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
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.sunil.switchlisttogridrecyclerview.MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/my_recycler_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scrollbars="vertical"/>
</RelativeLayout>
RecyclerAdapter.java
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by sunil on 12/10/16.
*/
public class RecyclerAdapter extends RecyclerView.Adapter {
private List itemModels;
private Context context;
private static final int LIST_ITEM = 0;
private static final int GRID_ITEM = 1;
boolean isSwitchView = true;
public RecyclerAdapter(Context context, List itemModels) {
this.itemModels = itemModels;
this.context = context;
}
#Override
public int getItemCount() {
return itemModels.size();
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View itemView;
if (i == LIST_ITEM){
itemView = LayoutInflater.from(viewGroup.getContext()).inflate( R.layout.item_layout, null);
}else{
itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_view_grid, null);
}
return new ItemViewHolder(itemView);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
ItemModel model = itemModels.get(position);
initializeViews(model, holder, position);
}
#Override
public int getItemViewType (int position) {
if (isSwitchView){
return LIST_ITEM;
}else{
return GRID_ITEM;
}
}
public boolean toggleItemViewType () {
isSwitchView = !isSwitchView;
return isSwitchView;
}
private void initializeViews(ItemModel model, final RecyclerView.ViewHolder holder, int position) {
String imageUrl = model.getImagePath();
if (imageUrl != null && !imageUrl.isEmpty()){
Glide.with(context)
.load(imageUrl)
.into(((ItemViewHolder)holder).imageView);
}
((ItemViewHolder)holder).name.setText(model.getName());
}
public static class ItemViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.name)
TextView name;
#BindView(R.id.imageView)
ImageView imageView;
public ItemViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
}
item_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp">
<de.hdodenhof.circleimageview.CircleImageView
android:src="#mipmap/ic_launcher"
android:id="#+id/imageView"
android:layout_width="70dp"
android:layout_height="70dp" />
<TextView
android:id="#+id/name"
android:text="name"
android:textStyle="bold"
android:layout_alignBaseline="#id/imageView"
android:layout_margin="10dp"
android:gravity="center_vertical"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_toRightOf="#+id/imageView"/>
</RelativeLayout>
item_layout_grid.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="0dp">
<RelativeLayout
android:padding="10dp"
android:layout_centerHorizontal="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal">
<de.hdodenhof.circleimageview.CircleImageView
android:src="#mipmap/ic_launcher"
android:id="#+id/imageView"
android:layout_width="70dp"
android:layout_height="70dp" />
<TextView
android:id="#+id/name"
android:text="name"
android:textStyle="bold"
android:layout_margin="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/imageView"/>
</RelativeLayout>
</RelativeLayout>

I have created a horizontal List view. Now I want this horizontal listview in every item of Vertical List View .How to do this??

Here is my main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.smartrix.horizontal_listview.MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
Here is my row.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_margin="12dp"
android:layout_width="150dp"
android:layout_height="250dp">
<TextView
android:id="#+id/title"
android:textStyle="bold"
android:textSize="20dp"
android:textAlignment="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</android.support.v7.widget.CardView>
Here is my mainActivity.java
package com.smartrix.horizontal_listview;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private RecyclerView.LayoutManager mLayoutManager;
private RecyclerView.Adapter mAdapter;
private ArrayList<String> mDataSet;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDataSet = new ArrayList<>();
for (int i = 0; i < 20; i++) {
mDataSet.add("New Title #"+i);
}
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new MainAdapter(mDataSet);
mRecyclerView.setAdapter(mAdapter);
}
}
Here is my mainAdapter.java ::
package com.smartrix.horizontal_listview;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
public class MainAdapter extends RecyclerView.Adapter<MainAdapter.ViewHolder> {
private ArrayList<String> mDataSet;
public MainAdapter(ArrayList<String> mDataSet){
this.mDataSet = mDataSet;
}
#Override
public MainAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.row, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(MainAdapter.ViewHolder holder, int position) {
holder.mTitle.setText(mDataSet.get(position));
}
#Override
public int getItemCount() {
return mDataSet.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView mTitle;
public ViewHolder(View itemView) {
super(itemView);
mTitle = (TextView) itemView.findViewById(R.id.title);
}
}
}
This Code Works Perfectly. Now I want to add this Horizontal ListView in Every ListItem of Vertical ListView. How to do this ??
You would simply add a new Horizontally oriented RecyclerView as an item in your list (and you would add it to your adapter).
It is fine to nest RelativeViews into each other.
In your case, add it to your row.xml layout, then inflate it in your mainAdapter.java class

Categories

Resources