same data appear in whole recylerview - android

same data appear in whole Recyclerview and position increasing but data same appear
in useradapter i log the position and position increase but data is same in onbindviewholder
useradapter
public class useradapter extends RecyclerView.Adapter<useradapter.CustomView> {
String nn = "m";
List<allusermodel> list1;
private Context context;
private LayoutInflater layoutInflater;
public useradapter(Context context, List<allusermodel> list1) {
Log.e("reached1", nn);
this.context = context;
this.list1 = list1;
}
#Override
public useradapter.CustomView onCreateViewHolder(final ViewGroup parent, final int viewType) {
Log.e("reached2", nn);
if (layoutInflater == null) {
layoutInflater = LayoutInflater.from(parent.getContext());
}
final Entrys newsBinding = Entrys.inflate(layoutInflater, parent, false);
// View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.innerlayout,parent,false);
return new CustomView(newsBinding);
}
#Override
public void onBindViewHolder(useradapter.CustomView holder,int position) {
Log.e("reached3", nn);
// News news = newsList.get(position);
// holder.desc.setText(news.getDesc());
allusermodel newsModel1 = list1.get(position);
// Log.e("list", String.valueOf(list1));
Log.e("nameeeee",newsModel1.getAll_user());
// Log.e("position", String.valueOf(position));
//Log.e("names",newsModel1.getAll_user());
holder.bind(newsModel1);
}
#Override
public int getItemCount() {
return list1.size();
}
public class CustomView extends RecyclerView.ViewHolder {
private Entrys newsBinding;
// public TextView title;
//TextView title, desc;
public CustomView(Entrys newsBinding) {
super(newsBinding.getRoot());
this.newsBinding = newsBinding;
Log.e("reached4", nn);
// title = (TextView)itemView.findViewById(R.id.titleval);
//desc =(TextView)itemView.findViewById(R.id.descval);
newsBinding.setRecyclerclick(new Presenters2() {
#Override
public void onclickListener() {
int pos = getAdapterPosition();
if (pos != RecyclerView.NO_POSITION) {
allusermodel clickedDataItem = list1.get(pos);
Intent intent = new Intent(context, messagelist.class);
intent.putExtra("clickid", clickedDataItem.getId());
context.startActivity(intent);
}
}
});
}
public void bind(allusermodel newsModel1)
{
Log.e("reached5", String.valueOf(newsModel1));
//String j = newsModel1.getAll_user();
// Log.e("bind",nn);
this.newsBinding.setAlluserentry(newsModel1);
}
public Entrys getNewsBinding() {
Log.e("reached6", nn);
return newsBinding;
}
}
}
userlist
public class userlist extends AppCompatActivity {
private static final String TAG = "userlist";
private RecyclerView recyclerView;
private LinearLayoutManager linearLayoutManager;
private DividerItemDecoration dividerItemDecoration;
private useradapter customAdapter;
private DataManager2 dataManger;
private List<allusermodel> newsList;
private RecyclerView.Adapter adapter;
String token2;
String URL1 = "https://chat.promactinfo.com/api/user";
private int userid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_userlist);
SharedPreferences pref = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
token2 = pref.getString("sherdtoken", "");
Log.e("token", token2);
dataManger = new DataManager2(this);
recyclerView = (RecyclerView) findViewById(R.id.recycle);
/*recyclerView.setLayoutManager(new LinearLayoutManager(this));
newsList = new ArrayList<>();
customAdapter = new useradapter(this, newsList);
recyclerView.setAdapter(customAdapter);*/
newsList = new ArrayList<>();
getdata();
}
public void getdata() {
dataManger.sendVolleyRequest1(token2, userlist.this, new DataValue() {
#Override
public void setJsonDataResponse1(JSONArray response) {
allusermodel userModel = new allusermodel();
// newsList = new ArrayList<>();
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jsonObject = response.getJSONObject(i);
// Log.e("final", String.valueOf(i));
// userid = jsonObject.getInt("id");
userModel.setId(jsonObject.getInt("id"));
// Log.e("getid", String.valueOf(jsonObject.getInt("id")));
userModel.setAll_user(jsonObject.getString("name"));
// Log.e("getname", String.valueOf(jsonObject.getString("name")));
newsList.add(userModel);
// Log.e("userlist", String.valueOf(newsList));
} catch (JSONException jsonDataResponse) {
Log.e("error", String.valueOf(jsonDataResponse));
}
}
adapter = new useradapter(getApplicationContext(),newsList);
linearLayoutManager = new LinearLayoutManager(getApplicationContext());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(), linearLayoutManager.getOrientation());
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.addItemDecoration(dividerItemDecoration);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
#Override
public void setVolleyError1(VolleyError volleyError) {
Log.e("Volley", volleyError.toString());
}
});
}
}
allusermodel
public class allusermodel extends BaseObservable {
public int id;
public String all_user;
public allusermodel() {
}
public allusermodel(int id,String name ) {
this.id = id;
this.all_user = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAll_user() {
return all_user;
}
public void setAll_user(String all_user) {
this.all_user = all_user;
}
#Override
public String toString() {
return "allusermodel{" +
"id=" + id +
", all_user='" + all_user + '\'' +
'}';
}
}
userlist.xml
<?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="com.example.mayurpancholi.chat_mvvm.userlist"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/recycle"
android:scrollbars="vertical">
</android.support.v7.widget.RecyclerView>
innerlayout.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data class ="Entrys">
<variable
name="alluserentry"
type="com.example.mayurpancholi.chat_mvvm.viewmodel.allusermodel"/>
<variable
name="recyclerclick"
type="com.example.mayurpancholi.chat_mvvm.interfaces.Presenters2"/>
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_marginTop="10dp"
android:padding="10dp"
android:onClick="#{()->recyclerclick.onclickListener()}"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/titleval"
android:textSize="20dp"
android:text="#{alluserentry.all_user}"
android:textStyle="bold"
android:layout_marginTop="10dp"
/>
</LinearLayout>
</layout>
whole recyclerview have same data which i previous add in api
(if i enter name in entry then it show previous entry in whole recylerview
ane then if i enter name1 in entry then it show name in whole recylerview )

It seems, the issue is coming because you have created the Model object outside the for loop when you are populating the data from sever. As a result the last value in the list will show to all the RecyclerView items.
Now the solution is that you create the model inside the "for-loop" as a first statement.
public void getdata() {
dataManger.sendVolleyRequest1(token2, userlist.this, new DataValue() {
#Override
public void setJsonDataResponse1(JSONArray response) {
//allusermodel userModel = new allusermodel();
// newsList = new ArrayList<>();
for (int i = 0; i < response.length(); i++) {
allusermodel userModel = new allusermodel();
try {
JSONObject jsonObject = response.getJSONObject(i);
I hope it will resolve your issue.

Related

when i click recylerview text to go another activity then that activity won't open and gave some binding error

did not start activity and give data binding error
useradapter
public class useradapter extends RecyclerView.Adapter<useradapter.CustomView> {
String nn = "m";
List<allusermodel> list1;
private Context context;
private LayoutInflater layoutInflater;
public useradapter(Context context, List<allusermodel> list1) {
Log.e("reached1", nn);
this.context = context;
this.list1 = list1;
}
#Override
public useradapter.CustomView onCreateViewHolder(final ViewGroup parent, final int viewType) {
Log.e("reached2", nn);
if (layoutInflater == null) {
layoutInflater = LayoutInflater.from(parent.getContext());
}
final Entrys newsBinding = Entrys.inflate(layoutInflater, parent, false);
// View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.innerlayout,parent,false);
return new CustomView(newsBinding);
}
#Override
public void onBindViewHolder(useradapter.CustomView holder,int position) {
Log.e("reached3", nn);
// News news = newsList.get(position);
// holder.desc.setText(news.getDesc());
allusermodel newsModel1 = list1.get(position);
// Log.e("list", String.valueOf(list1));
Log.e("nameeeee",newsModel1.getAll_user());
// Log.e("position", String.valueOf(position));
//Log.e("names",newsModel1.getAll_user());
holder.bind(newsModel1);
}
#Override
public int getItemCount() {
return list1.size();
}
public class CustomView extends RecyclerView.ViewHolder {
private Entrys newsBinding;
// public TextView title;
//TextView title, desc;
public CustomView(Entrys newsBinding) {
super(newsBinding.getRoot());
this.newsBinding = newsBinding;
Log.e("reached4", nn);
// title = (TextView)itemView.findViewById(R.id.titleval);
//desc =(TextView)itemView.findViewById(R.id.descval);
newsBinding.setRecyclerclick(new Presenters2() {
#Override
public void onclickListener() {
int pos = getAdapterPosition();
if (pos != RecyclerView.NO_POSITION) {
allusermodel clickedDataItem = list1.get(pos);
Intent intent = new Intent(context, messagelist.class);
intent.putExtra("clickid", clickedDataItem.getId());
context.startActivity(intent);
}
}
});
}
public void bind(allusermodel newsModel1)
{
Log.e("reached5", String.valueOf(newsModel1));
//String j = newsModel1.getAll_user();
// Log.e("bind",nn);
this.newsBinding.setAlluserentry(newsModel1);
}
public Entrys getNewsBinding() {
Log.e("reached6", nn);
return newsBinding;
}
}
}
messagelist
public class messagelist extends AppCompatActivity {
private RecyclerView recyclerView;
private ActivityMainBinding activityMainBinding1;
private Postmessagemodel postmessagemodel;
private messageadapter customAdapter;
private messagelist_datamanager dataManger;
private postmessage_datamanager postmessage_datamanager;
private List<messagemodel> newsList;
String tokens;
String sendmsg;
private int toid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_messagelist);
toid=getIntent().getExtras().getInt("clickid");
SharedPreferences pref = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
tokens = pref.getString("sherdtoken", "");
Log.e("token", tokens);
activityMainBinding1 = DataBindingUtil.setContentView(this,R.layout.activity_messagelist);
postmessagemodel = new Postmessagemodel();
postmessage_datamanager = new postmessage_datamanager(this);
//activityMainBinding1.setPostmsg(postmessagemodel);
/* activityMainBinding1.setPostbtn(new Post() {
#Override
public void onclick() {
postmessage();
}
});*/
sendmsg = postmessagemodel.getMSG();
dataManger = new messagelist_datamanager(this);
recyclerView = (RecyclerView) findViewById(R.id.recycle1);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
newsList = new ArrayList<>();
customAdapter = new messageadapter(this, newsList);
recyclerView.setAdapter(customAdapter);
getmessage();
postmessage();
}
public void getmessage()
{
dataManger.sendVolleyRequest2(tokens,toid,messagelist.this, new messagelist_datavalue() {
#Override
public void setJsonDataResponse(JSONArray response) {
messagemodel userModel = new messagemodel();
newsList = new ArrayList<>();
try {
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = response.getJSONObject(i);
// Log.e("final", String.valueOf(i));
userModel.setFromUserId(jsonObject.getInt("fromUserId"));
userModel.setMessage(jsonObject.getString("message"));
userModel.setToUserId(jsonObject.getInt("toUserId"));
newsList.add(userModel);
}
} catch (JSONException jsonDataResponse) {
Log.e("error", String.valueOf(jsonDataResponse));
}
customAdapter.notifyDataSetChanged();
}
#Override
public void setVolleyError(VolleyError volleyError) {
Log.e("Volley", volleyError.toString());
}
});
}
private void postmessage() {
postmessage_datamanager.sendVolleyRequest3(sendmsg,toid,tokens,messagelist.this,new postmessage_datavalue() {
#Override
public void setJsonDataResponse(JSONObject response) {
try {
Log.e("success",sendmsg);
} catch (Exception e) {
Log.e("error", e.toString());
}
}
#Override
public void setVolleyError(VolleyError volleyError) {
}
});
}
}
messagelist.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/layout">
<data>
<variable
name="postmsg"
type="com.example.mayurpancholi.chat_mvvm.viewmodel.Postmessagemodel"/>
<variable
name="postbtn"
type="com.example.mayurpancholi.chat_mvvm.interfaces.Post"/>
</data>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.mayurpancholi.chat_mvvm.messagelist">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/recycle1"
android:scrollbars="vertical"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
android:layout_marginBottom="80dp">
</android.support.v7.widget.RecyclerView>
<EditText
android:id="#+id/post_text"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="13dp"
android:text="#={postmsg.MSG}"
android:layout_marginLeft="9dp"
android:ems="10"
android:inputType="textPersonName" />
<Button
android:id="#+id/post_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/post_text"
android:layout_alignParentEnd="true"
android:layout_marginBottom="7dp"
android:layout_marginRight="5dp"
android:background="#color/colorPrimary"
android:onClick="#{()->postbtn.onclick()}"
android:text="post" />
</RelativeLayout>
</layout>
innerlayout.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data class ="MessageBinding">
<variable
name="message_list"
type="com.example.mayurpancholi.chat_mvvm.viewmodel.messagemodel"/>
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp">
<TextView
android:id="#+id/main_message"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginTop="10dp"
android:text="#{message_list.message}"
android:textSize="17dp" />
</LinearLayout>
</layout>
messagelistadapter
public class messageadapter extends RecyclerView.Adapter<messageadapter.CustomView1> {
List<messagemodel> list;
private Context context;
private LayoutInflater layoutInflater;
public messageadapter(Context context,List<messagemodel> list)
{
this.context =context;
this.list = list;
}
public messageadapter() {
}
#Override
public messageadapter.CustomView1 onCreateViewHolder(ViewGroup parent, int viewType) {
if(layoutInflater == null)
{
layoutInflater = LayoutInflater.from(parent.getContext());
}
final MessageBinding newsBinding = MessageBinding.inflate(layoutInflater,parent,false);
// View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.innerlayout,parent,false);
return new CustomView1(newsBinding);
}
#Override
public void onBindViewHolder(messageadapter.CustomView1 holder, int position) {
messagemodel newsModel = list.get(position);
holder.bind(newsModel);
}
#Override
public int getItemCount() {
return list.size();
}
public class CustomView1 extends RecyclerView.ViewHolder {
private MessageBinding newsBinding;
// TextView title, desc;
public CustomView1(MessageBinding newsBinding) {
super(newsBinding.getRoot());
this.newsBinding = newsBinding;
//title = (TextView)itemView.findViewById(R.id.titleval);
//desc =(TextView)itemView.findViewById(R.id.descval);
}
public void bind(messagemodel newsModel1)
{
// this.newsBinding.setMessage_list(newsModel1);
}
public MessageBinding getNewsBinding()
{
return newsBinding;
}
}
}
when i click the recyclerview text it open messagelist but messagelist won't open and give error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.mayurpancholi.chat_mvvm, PID: 21181
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.mayurpancholi.chat_mvvm/com.example.mayurpancholi.chat_mvvm.messagelist}: java.lang.ClassCastException: com.example.mayurpancholi.chat_mvvm.databinding.ActivityMessagelistBinding cannot be cast to com.example.mayurpancholi.chat_mvvm.databinding.ActivityMainBinding
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
I think the error is self explanatory. As per your flow I can see you want to bind the messagelist actity layout with the Data binding of of MainActity class for which you might have layout as "activity_main.xml". For, As your messagelist activity binding layout name is "activity_messagelist.xml" so the generated binding class name will be "ActivityMessagelistBinding". Therefore, as per the logic of databinding the layout will bind with ActivityMessagelistBinding instead of ActivityMainBinding. So as a conclusion, you change the statement
private ActivityMainBinding activityMainBinding1;
activityMainBinding1 = DataBindingUtil.setContentView(this,R.layout.activity_messagelist);
to
private ActivityMessagelistBinding activityMessagelistBinding;
activityMessagelistBinding = DataBindingUtil.setContentView(this,R.layout.activity_messagelist);
Hope it should work.

RecyclerView doesn't display any item view at load

I am retrieving JSON data and parcing it by Retrofit. I want to display it on RecyclerView but can't make it display the views. Where am I doing it wrong? Here MainActivity, Model and ListFlowerAdapter are given
public class MainActivity extends AppCompatActivity {
private ListFlowerAdapter mListFlowerAdapter;
private RecyclerView mRecyclerView;
private RetrofitClient mRetrofitClient;
LinearLayoutManager linearLayoutManager;
//private List<FlowerModel> myFlowers;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
configViews();
mRetrofitClient = new RetrofitClient();
Call<List<FlowerModel>> listCall = mRetrofitClient.getFlowerService().getAllFlowers();
listCall.enqueue(new Callback<List<FlowerModel>>() {
#Override
public void onResponse(Call<List<FlowerModel>> call, Response<List<FlowerModel>> response) {
if (response.isSuccessful()) {
List<FlowerModel> flowerList = response.body();
for (int i = 0; i < flowerList.size(); i++) {
FlowerModel flowerModel = flowerList.get(i);
mListFlowerAdapter.addFlower(flowerModel);
}
} else {
int sc = response.code();
switch (sc) {
}
}
}
#Override
public void onFailure(Call<List<FlowerModel>> call, Throwable t) {
}
});
}
private void configViews() {
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setRecycledViewPool(new RecyclerView.RecycledViewPool());
linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mRecyclerView.setLayoutManager(linearLayoutManager);
mListFlowerAdapter = new ListFlowerAdapter();
mRecyclerView.setAdapter(mListFlowerAdapter);
//mRecyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(),LinearLayoutManager.VERTICAL,false));
//mListFlowerAdapter = new ListFlowerAdapter();
// mRecyclerView.setAdapter(mListFlowerAdapter);
}
}
ListFlowerAdapter class
public class ListFlowerAdapter extends RecyclerView.Adapter<ListFlowerAdapter.MyViewHolder> {
private static final String TAG = ListFlowerAdapter.class.getSimpleName();
private Context context;
private List<FlowerModel> myFlowers;
public ListFlowerAdapter() {
myFlowers = new ArrayList<>();
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View row = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_item, null, false);
return new MyViewHolder(row);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
FlowerModel currFlower = myFlowers.get(position);
holder.mName.setText(currFlower.getName());
holder.mPrice.setText(Double.toString(currFlower.getPrice()));
Picasso.with(holder.itemView.getContext()).load("http://services.hanselandpetal.com/photos/" + currFlower.getPhoto()).into(holder.mPhoto);
}
#Override
public int getItemCount() {
return myFlowers.size();
}
public void addFlower(FlowerModel flowerModel) {
myFlowers.add(flowerModel);
notifyDataSetChanged();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private ImageView mPhoto;
private TextView mName, mPrice;
public MyViewHolder(View itemView) {
super(itemView);
mPhoto = itemView.findViewById(R.id.flower_photo);
mName = itemView.findViewById(R.id.flower_name);
mPrice = itemView.findViewById(R.id.flower_price);
}
}
}
FlowerModel class
public class FlowerModel implements Serializable {
#Expose
private String category;
#Expose
private String price;
#Expose
private String instructions;
#Expose
private String photo;
#Expose
private String name;
#Expose
private int productId;
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public double getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getInstructions() {
return instructions;
}
public void setInstructions(String instructions) {
this.instructions = instructions;
}
public String getPhoto() {
return photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getProductId() {
return productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
}
XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:orientation="horizontal">
<ImageView
android:id="#+id/flower_photo"
android:layout_width="150dp"
android:layout_height="150dp"
android:background="#mipmap/ic_launcher"
android:scaleType="centerCrop" />
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/flower_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"
android:text="Large Text" />
<TextView
android:id="#+id/flower_price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Medium"
android:text="Medium Text" />
</LinearLayout>
<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"
android:orientation="vertical"
android:padding="16dp"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Stop Downloading" />
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="none"
android:visibility="visible" />
Could you help me with the issue, please? Thank you very much.
Don't notify your adapter recursively,
Your code :
for (int i = 0; i < flowerList.size(); i++) {
FlowerModel flowerModel = flowerList.get(i);
mListFlowerAdapter.addFlower(flowerModel); // Called from here
}
Code from adapter
public void addFlower(FlowerModel flowerModel) {
myFlowers.add(flowerModel);
notifyDataSetChanged(); // Notifying everytime
}
Instead, you should add all data to adapter and notify only once : (Updated code)
for (int i = 0; i < flowerList.size(); i++) {
FlowerModel flowerModel = flowerList.get(i);
mListFlowerAdapter.addFlower(flowerModel);
}
mListFlowerAdapter.notifyDataSetChanged(); // Notify like this
Code from adapter
public void addFlower(FlowerModel flowerModel) {
myFlowers.add(flowerModel);
//notifyDataSetChanged(); Remove from here
}
Pass activity context to the adapter and use that context for populating item on list view.
private Context mContext;
public ListFlowerAdapter(Context context) {
myFlowers = new ArrayList<>();
this.mContext = context;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View row = LayoutInflater.from(mContext).inflate(R.layout.row_item, parent, false);
return new MyViewHolder(row);
}
From activity send the activity context for initializing the adapter like this
mListFlowerAdapter = new ListFlowerAdapter(this);
And for adding a new item
public void addFlowers(List<FlowerModel> flowerModels) {
for (int i = 0; i < flowerModels.size(); i++) {
FlowerModel flowerModel = flowerModels.get(i);
myFlowers.add(flowerModel);
}
notifyDataSetChanged();
}
And successful response just send the list for updating the adapter
List<FlowerModel> flowerList = response.body();
mListFlowerAdapter.addFlowers(flowerList);
Hope this will help.
Try to remove this line:
mRecyclerView.setHasFixedSize(true);
And add this in the XML file:
android:fillViewport="true"
Without that line, your RecyclerView content initial height is 0 (empty list), and with the fixed size it can't grow although you add items to the adapter.

Two recyclerview is not showing in one layout

i am trying to implement two recyclerview in one layout with same adapter. but only one recyclerview is showing.
MainActivity.java
public class MainActivity extends AppCompatActivity {
List<DataAdapter> ListOfdataAdapter;
String HTTP_JSON_URL = "http://example.com";
String Image_Name_JSON = "Menu_name";
String Image_URL_JSON = "Menu_image";
JsonArrayRequest RequestOfJSonArray ;
RequestQueue requestQueue ;
View view ;
int RecyclerViewItemPosition ;
RecyclerView.LayoutManager layoutManagerOfrecyclerView;
RecyclerView.Adapter recyclerViewadapter;
ArrayList<String> ImageTitleNameArrayListForClick;
long Category_ID;
String MenuAPI;
private RecyclerView secondRecyclerView;
private RecyclerView.LayoutManager secondLayoutManager;
private RecyclerView firstrecyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageTitleNameArrayListForClick = new ArrayList<>();
// menu API url
Intent iGet = getIntent();
Category_ID = iGet.getLongExtra("category_id",0);
MenuAPI += Category_ID;
ListOfdataAdapter = new ArrayList<>();
firstrecyclerView = (RecyclerView) findViewById(R.id.recyclerview1);
firstrecyclerView.setHasFixedSize(true);
layoutManagerOfrecyclerView = new LinearLayoutManager(MainActivity.this, LinearLayoutManager.HORIZONTAL, true);
firstrecyclerView.setLayoutManager(layoutManagerOfrecyclerView);
firstrecyclerView.post(new Runnable() {
#Override
public void run() {
JSON_HTTP_CALL();// a method which requests remote data
}
});
secondRecyclerView = (RecyclerView) findViewById(R.id.recyclerview2);
secondRecyclerView.setHasFixedSize(true);
secondLayoutManager = new LinearLayoutManager(MainActivity.this, LinearLayoutManager.VERTICAL, true);
secondRecyclerView.setLayoutManager(secondLayoutManager);
secondRecyclerView.post(new Runnable() {
#Override
public void run() {
JSON_HTTP_CALL2();// a method which requests remote data
}
});
// Implementing Click Listener on RecyclerView.
}
public void JSON_HTTP_CALL(){
RequestOfJSonArray = new JsonArrayRequest(HTTP_JSON_URL + "/api/example.php" +"&category_id=2",
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
ParseJSonResponse(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(MainActivity.this);
requestQueue.add(RequestOfJSonArray);
}
public void ParseJSonResponse(JSONArray array){
for(int i = 0; i<array.length(); i++) {
DataAdapter GetDataAdapter2 = new DataAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataAdapter2.setImageTitle2(json.getString(Image_Name_JSON));
// Adding image title name in array to display on RecyclerView click event.
ImageTitleNameArrayListForClick.add(json.getString(Image_Name_JSON));
GetDataAdapter2.setImageUrl2(HTTP_JSON_URL + "/" + json.getString(Image_URL_JSON));
} catch (JSONException e) {
e.printStackTrace();
}
ListOfdataAdapter.add(GetDataAdapter2);
}
recyclerViewadapter = new RecyclerViewAdapter(ListOfdataAdapter, getApplicationContext());
firstrecyclerView.setAdapter(recyclerViewadapter);
}
public void JSON_HTTP_CALL2(){
RequestOfJSonArray = new JsonArrayRequest(HTTP_JSON_URL + "/api/example.php" +"&category_id=2",
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
ParseJSonResponse2(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(MainActivity.this);
requestQueue.add(RequestOfJSonArray);
}
public void ParseJSonResponse2(JSONArray array){
for(int i = 0; i<array.length(); i++) {
DataAdapter GetDataAdapter2 = new DataAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataAdapter2.setImageTitle2(json.getString(Image_Name_JSON));
// Adding image title name in array to display on RecyclerView click event.
ImageTitleNameArrayListForClick.add(json.getString(Image_Name_JSON));
GetDataAdapter2.setImageUrl2(HTTP_JSON_URL + "/" + json.getString(Image_URL_JSON));
} catch (JSONException e) {
e.printStackTrace();
}
ListOfdataAdapter.add(GetDataAdapter2);
}
recyclerViewadapter = new RecyclerViewAdapter(ListOfdataAdapter, getApplicationContext());
secondRecyclerView.setAdapter(recyclerViewadapter);
}
}
Adapter class
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
Context context;
List<DataAdapter> dataAdapters;
ImageLoader imageLoader;
private Activity activity;
private static final int CITY_TYPE = 0;
JsonArrayRequest RequestOfJSonArray;
private static final int EVENT_TYPE = 1;
public RecyclerViewAdapter(Activity act) {
this.activity = act;
}
public RecyclerViewAdapter(List<DataAdapter> getDataAdapter, Context context){
super();
this.dataAdapters = getDataAdapter;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
switch (viewType) {
case CITY_TYPE:
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview, parent, false);
return new ViewHolder(view);
case EVENT_TYPE:
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card2, parent, false);
return new ViewHolder(view);
}
return null;
}
#Override
public void onBindViewHolder(ViewHolder Viewholder, int position) {
DataAdapter dataAdapterOBJ = dataAdapters.get(position);
imageLoader = ImageAdapter.getInstance(context).getImageLoader();
if (dataAdapterOBJ != null) {
switch (dataAdapterOBJ.getType()) {
case CITY_TYPE:
imageLoader.get(dataAdapterOBJ.getImageUrl2(),
ImageLoader.getImageListener(
Viewholder.VollyImageView,//Server Image
R.mipmap.ic_launcher,//Before loading server image the default showing image.
android.R.drawable.ic_dialog_alert //Error image if requested image dose not found on server.
)
);
Viewholder.VollyImageView.setImageUrl(dataAdapterOBJ.getImageUrl2(), imageLoader);
Viewholder.ImageTitleTextView.setText(dataAdapterOBJ.getImageTitle2());
break;
case EVENT_TYPE:
imageLoader.get(dataAdapterOBJ.getImageUrl2(),
ImageLoader.getImageListener(
Viewholder.VollyImageView,//Server Image
R.mipmap.ic_launcher,//Before loading server image the default showing image.
android.R.drawable.ic_dialog_alert //Error image if requested image dose not found on server.
)
);
Viewholder.VollyImageView.setImageUrl(dataAdapterOBJ.getImageUrl2(), imageLoader);
Viewholder.ImageTitleTextView.setText(dataAdapterOBJ.getImageTitle2());
break;
}
}
}
#Override
public int getItemCount() {
return dataAdapters.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
public TextView ImageTitleTextView;
public NetworkImageView VollyImageView ;
public ViewHolder(View itemView) {
super(itemView);
ImageTitleTextView = (TextView) itemView.findViewById(R.id.MenuNameTV) ;
VollyImageView = (NetworkImageView) itemView.findViewById(R.id.VolleyImageView) ;
}
}
}
main activity xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="Most Watched"/>
<!-- A RecyclerView to display horizontal list -->
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerview1"
android:scrollbars="none"
android:layout_width="fill_parent"
android:layout_height="240dp"
android:paddingLeft="0dp"
android:paddingRight="15dp"
android:paddingTop="15dp"
android:paddingBottom="25dp"
android:background="#ffc000"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="All Dramas"/>
<!-- A RecyclerView to display vertical list -->
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerview2"
android:layout_width="fill_parent"
android:layout_height="240dp"
android:paddingLeft="0dp"
android:paddingRight="15dp"
android:paddingTop="15dp"
android:paddingBottom="25dp"/>
i try every possible way available on internet but dont get solution.
Anything wrong i am doing?
any idea how to run two recyclerview with above code.
thankx
You can do this-
<android.support.v4.widget.NestedScrollView>
<LinearLayout>
.
.
.
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
This is used to attach 2 or more scrolling views together and one more thing you can do is to make the height of recycler view as "wrap_content".
Hope this helps.

ArrayList not being displayed in RecyclerView

I'm trying to display an ArrayList of Integers inside of a RecyclerView, the Integer values in the ArrayList are downloaded from JSON, all that is done, the thing I need help with is to display them in a RecyclerView.
This is my code so far but the RecyclerView does not display anything.
All code updated to my current code
Here's part of the MainActivity:
public class MainActivity extends AppCompatActivity {
private ActivityMainViewModel viewmodel;
RecyclerView recyclerView;
MainAdapter mAdapter;
public static ArrayList<Integer> rideList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
viewmodel = new ActivityMainViewModel();
binding.setViewmodel(viewmodel);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
mAdapter = new MainAdapter(rideList);
recyclerView.setAdapter(mAdapter);
}
Here's the MainAdapter class:
class MainAdapter extends android.support.v7.widget.RecyclerView.Adapter<MainAdapter.ViewHolder> {
private ArrayList<Integer> rideList;
public MainAdapter(ArrayList<Integer> rideList)
{
this.rideList = rideList;
}
#Override
public MainAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(MainAdapter.ViewHolder holder, int position)
{
holder.rideHeight.setText(String.valueOf(rideList.get(position)));
}
#Override
public int getItemCount()
{
return rideList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView rideHeight;
public ViewHolder(View itemView) {
super(itemView);
rideHeight = (TextView) itemView.findViewById(R.id.rideHeight_textView);
}
}
}
row.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/rideHeight_textView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="20sp"/>
</LinearLayout>
I know that it probably looks a mess but that's because I have been searching both on google and youtube on how to use RecyclerView so I might have mixed from different tutorials and tried somethings myself.
Thanks!
Edit: JsonData code added on request:
JsonData:
public class JsonData
{
public ObservableField<String> dropHeight = new ObservableField<>();
public ObservableField<String> rideCount = new ObservableField<>();
int eID;
int sID;
public JsonData()
{
dropHeight.set("");
rideCount.set("");
}
public void downloadFromSkistar()
{
if (SettingsActivity.submitClicked)
{
eID = SettingsActivity.x;
sID = SettingsActivity.y;
}
else
{
eID = 3206;
sID = 11;
}
try
{
URL url = new URL("https://www.skistar.com/myskistar/api/v2/views/statisticspage.json?entityId=" + eID + "&seasonId=" + sID + " ");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
// Starts the query
conn.connect();
int response = conn.getResponseCode();
Log.i("AndroidExample", "Response: " + response);
if (response == 200)
{
String json = getJson(conn.getInputStream());
JSONObject jsonObject = new JSONObject(json);
JSONArray jsonArray = jsonObject.getJSONArray("rideStatistics");
int reponame = 0;
int rHeight = 0;
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject skiRun = jsonArray.getJSONObject(i);
reponame += skiRun.getInt("height");
rHeight += skiRun.getInt("height");
MainActivity.rideList.add(new Integer(rHeight));
rHeight = 0;
}
final int height = reponame;
final int count = jsonArray.length();
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
dropHeight.set("" + height);
rideCount.set("" + count);
}
});
}
}
catch (Exception e)
{
Log.i("AndroidExample", "Error");
}
finally
{
}
}
private String getJson(InputStream stream) throws IOException
{
BufferedReader reader;
reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line + '\n');
}
//Should be placed in finally
stream.close();
return builder.toString();
}
}
You can use like..
Model..to set value and get value
public class CustomModel {
private int it;
public int getIt() {
return it;
}
public void setIt(int it) {
this.it = it;
}
}
Adapter ...
private class MainAdapter extends RecyclerView.Adapter<MainAdapter.ViewHolder>{
public MainAdapter(ArrayList<CustomModel> list){
dataSet = list;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View itemLayoutView = LayoutInflater.from(viewGroup.getContext()).inflate(
R.layout.row, null);
itemLayoutView.setLayoutParams(new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.WRAP_CONTENT));
MainAdapter.ViewHolder viewHolder = new MainAdapter.ViewHolder(itemLayoutView);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
CustomModel cardModel = dataSet.get(position);
viewHolder.rideHeight_textView.setText(String.valueOf(cardModel.getId()));
}
#Override
public int getItemCount() {
return dataSet.size();
}
public void updateList(List<CustomModel> temp) {
dataSet = (ArrayList<CustomModel>) temp;
notifyDataSetChanged();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView rideHeight_textView;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
rideHeight_textView = (TextView) itemLayoutView .findViewById(R.id.rideHeight_textView);
itemLayoutView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//action ****
}
});
}
}
}
Just call like
ArrayList<CustomModel> menuList = new ArrayList<>();
CustomModel c = new CustomModel();
c.setIt(1);
recyclerView.setHasFixedSize(true);
// ListView
recyclerView.setLayoutManager(new LinearLayoutManager(Your activity.this));
// create an Object for Adapter
MainAdapter mAdapter = new MainAdapter(menuList);
// set the adapter object to the Recyclerview
recyclerView.setAdapter(mAdapter);
row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:background="#ffffff"
android:padding="#dimen/activity_vertical_margin"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/rideHeight_textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#000000"
android:textSize="20sp"/>
</LinearLayout>
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
LinearLayoutManager layoutManager = new LinearLayoutManager(context);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layoutManager);
mAdapter = new MainAdapter(JsonData.rideList, MainActivity.this);
recyclerView.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
adapter:
class MainAdapter extends android.support.v7.widget.RecyclerView.Adapter<MainAdapter.ViewHolder> {
private ArrayList<Integer> rideList = new ArrayList<>();
private Context context;
public MainAdapter(ArrayList<Integer> rideList, Context context)
{
this.context = context;
this.rideList = rideList;
}
#Override
public MainAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(context).inflate(R.layout.row, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(MainAdapter.ViewHolder holder, int position)
{
holder.rideHeight.setText(String.valueOf(rideList.get(position)));
}
#Override
public int getItemCount()
{
return rideList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView rideHeight;
public ViewHolder(View itemView) {
super(itemView);
rideHeight = (TextView) itemView.findViewById(R.id.rideHeight_textView);
}
}
}
row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:background="#ffffff"
android:padding="#dimen/activity_vertical_margin"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/rideHeight_textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#000000"
android:textSize="20sp"/>
</LinearLayout>
For starters you are not calling your data fetcher method in JsonData class. Your code is kind of messy so you can try the following solution:
In your adapter class add this method:
public void setList(ArrayList<Integer> rideList)
{
this.rideList = rideList;
notifyDataSetChanged();
}
Then in you JsonData class add:
private MainAdapter adapter;
public JsonData(MainAdapter adapter)
{
this.adapter = adapter;
dropHeight.set("");
rideCount.set("");
}
And change downloadFromSkistar to:
public void downloadFromSkistar()
{
if (SettingsActivity.submitClicked)
{
eID = SettingsActivity.x;
sID = SettingsActivity.y;
}
else
{
eID = 3206;
sID = 11;
}
new AsyncTask<Void, Void, List<Integer>>() {
#Override
protected List<Integer> doInBackground(Void... voids) {
try
{
URL url = new
URL("https://www.skistar.com/myskistar/api/v2/views/statisticspage.json?
entityId=" + eID + "&seasonId=" + sID + " ");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
// Starts the query
conn.connect();
int response = conn.getResponseCode();
Log.i("AndroidExample", "Response: " + response);
if (response == 200)
{
String json = getJson(conn.getInputStream());
JSONObject jsonObject = new JSONObject(json);
JSONArray jsonArray = jsonObject.getJSONArray("rideStatistics");
int reponame = 0;
int rHeight = 0;
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject skiRun = jsonArray.getJSONObject(i);
reponame += skiRun.getInt("height");
rHeight += skiRun.getInt("height");
rideList.add(new Integer(rHeight));
rHeight = 0;
}
}
}
catch (Exception e)
{
Log.i("AndroidExample", "Error");
}
finally
{
}
return rideList;
}
#Override
protected void onPostExecute(List<Integer> list)
{
super.onPostExecute(list);
adapter.setList(rideList);
}
};
}
And in the end finally change MainActivity to:
public class MainActivity extends AppCompatActivity {
private ActivityMainViewModel viewmodel;
RecyclerView recyclerView;
MainAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
viewmodel = new ActivityMainViewModel();
binding.setViewmodel(viewmodel);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
mAdapter = new MainAdapter(JsonData.rideList);
recyclerView.setAdapter(mAdapter);
new JsonData(mAdapter).downloadFromSkistar();
}
PS: You are going to get NetworkOnMainThread exception. So try to add the network code in AsyncTask
Here's what I did to solve it, and btw I'm also using the SwipeRefreshLayout.
public class MainActivity extends AppCompatActivity {
private ActivityMainViewModel viewmodel;
RecyclerView recyclerView;
MainAdapter mAdapter;
public static ArrayList<Integer> rideList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
viewmodel = new ActivityMainViewModel();
binding.setViewmodel(viewmodel);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
mAdapter = new MainAdapter(rideList);
recyclerView.setAdapter(mAdapter);
viewmodel.jdDownloadFromSkistar();
final SwipeRefreshLayout swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipelayout);;
swipeRefreshLayout.setColorSchemeResources(R.color.refresh,R.color.refresh1,R.color.refresh2);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
swipeRefreshLayout.setRefreshing(true);
refreshRecyclerView();
swipeRefreshLayout.setRefreshing(false);
}
});
}
private void refreshRecyclerView()
{
mAdapter.notifyDataSetChanged();
}
So what I did was make a call to the jdDownloadFromSkistar(); Method and when I swipe to refresh it updates the adapter by using the notifyDataSetChanged(); method.

RecyclerView with SearchView will not populate upon initialization

I am currently using searchView to filter results on a RecyclerView. The problem is when the fragment is initialized, the list won't appear not until I click on the search icon on the toolbar and type some texts on it. I've tried modifying the codes. Take a look specifically at the adapter and holder classes, if you'll try to exchange my current codes to these:
public MembershipActivationAdapter(Context context, List<Member> members){
this.context = context;
this.mMembers = members;
}
and
#Override
public MembershipActivationViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
final View itemView = LayoutInflater.from(context).inflate(R.layout.member_activation_content, viewGroup, false);
}
,it will show the list upon calling the fragment however if I'll type something on the SearchView, it seems to function only as a one way filter. It will filter names but whenever I'll try to remove a character or a text on the searchview, it won't show the list back. Please help me with this. These are my codes:
Adapter & ViewHolder class:
public class MembershipActivationAdapter extends RecyclerView.Adapter<MembershipActivationAdapter.MembershipActivationViewHolder> {
private final List<Member> mMembers;
private final LayoutInflater inflater;
//private final Context context;
public MembershipActivationAdapter(Context context, List<Member> members){
inflater = LayoutInflater.from(context);
mMembers = new ArrayList<>(members);
//this.context = context;
//this.mMembers = members;
}
#Override
public int getItemCount() {
return mMembers.size();
}
#Override
public void onBindViewHolder(MembershipActivationViewHolder holder, final int position) {
final Member m = mMembers.get(position);
holder.name.setText(m.getName());
holder.email.setText(m.getEmail());
if(m.getStatus().equals("Active")){
holder.status.setText(Html.fromHtml("<font color='#00CD00'>" + m.getStatus() + "</font>"));
}else{
holder.status.setText(Html.fromHtml("<font color='#ff0000'>" + m.getStatus() + "</font>"));
}
}
#Override
public MembershipActivationViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
final View itemView = inflater.inflate(R.layout.member_activation_content, viewGroup, false);
return new MembershipActivationViewHolder(itemView);
//final View itemView = LayoutInflater.from(context).inflate(R.layout.member_activation_content, viewGroup, false);
}
public static class MembershipActivationViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public final TextView name;
public final TextView email;
public final TextView status;
public MembershipActivationViewHolder(View v) {
super(v);
v.setOnClickListener(this);
name = (TextView) v.findViewById(R.id.member_name);
email = (TextView) v.findViewById(R.id.member_email);
status = (TextView) v.findViewById(R.id.member_status);
}
}
public List<Member> getMemberList() {
return mMembers;
}
public void animateTo(List<Member> members) {
applyAndAnimateRemovals(members);
applyAndAnimateAdditions(members);
applyAndAnimateMovedItems(members);
}
private void applyAndAnimateRemovals(List<Member> newMembers) {
for (int i = mMembers.size() - 1; i >= 0; i--) {
final Member member = mMembers.get(i);
if (!newMembers.contains(member)) {
removeItem(i);
}
}
}
private void applyAndAnimateAdditions(List<Member> newMembers) {
for (int i = 0, count = newMembers.size(); i < count; i++) {
final Member member = newMembers.get(i);
if (!mMembers.contains(member)) {
addItem(i, member);
}
}
}
private void applyAndAnimateMovedItems(List<Member> newMembers) {
for (int toPosition = newMembers.size() - 1; toPosition >= 0; toPosition--) {
final Member member = newMembers.get(toPosition);
final int fromPosition = mMembers.indexOf(member);
if (fromPosition >= 0 && fromPosition != toPosition) {
moveItem(fromPosition, toPosition);
}
}
}
public Member removeItem(int position) {
final Member member = mMembers.remove(position);
notifyItemRemoved(position);
return member;
}
public void addItem(int position, Member member) {
mMembers.add(position, member);
notifyItemInserted(position);
}
public void moveItem(int fromPosition, int toPosition) {
final Member member = mMembers.remove(fromPosition);
mMembers.add(toPosition, member);
notifyItemMoved(fromPosition, toPosition);
}
}
Fragment Class:
public class MembershipActivationFragment extends Fragment implements SearchView.OnQueryTextListener{
private static String url = "http://www.xxxxx.org/portal/webservices/get_members.php";
private List<Member> memberList;
private RecyclerView recyclerView;
private MembershipActivationAdapter adapter;
private String pid;
private ProgressDialog progressDialog;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.member_activation, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.members_recycler_view);
setHasOptionsMenu(true);
memberList = new ArrayList<>();
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Loading...");
progressDialog.show();
populate();
return rootView;
}
public void populate(){
JsonArrayRequest request = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
hidePDialog();
String name, email, status;
Member member;
for(int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject object = jsonArray.getJSONObject(i);
name = object.getString("firstname") + " " + object.getString("lastname");
email = object.getString("email");
if(Integer.parseInt(object.getString("activated"))==1){
status = "Active";
}else{
status = "Not Active";
}
member = new Member(name, email, status);
memberList.add(member);
} catch (Exception e) {
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError volleyError) {
volleyError.printStackTrace();
}
});
AppController.getInstance().addToRequestQueue(request);
adapter = new MembershipActivationAdapter(getActivity(), memberList);
recyclerView.setAdapter(adapter);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.search_menu, menu);
final MenuItem item = menu.findItem(R.id.action_search);
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(this);
}
#Override
public boolean onQueryTextChange(String query) {
final List<Member> filteredMemberList = filter(memberList, query);
adapter.animateTo(filteredMemberList);
recyclerView.scrollToPosition(0);
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
private List<Member> filter(List<Member> members, String query) {
query = query.toLowerCase();
final List<Member> filteredModelList = new ArrayList<>();
for (Member member : members) {
final String text = member.getName().toLowerCase();
if (text.contains(query)) {
filteredModelList.add(member);
}
}
return filteredModelList;
}
private void hidePDialog() {
if (progressDialog != null) {
progressDialog.dismiss();
progressDialog = null;
}
}
}
RecyclerView container xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/members_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"/>
</LinearLayout>
Content class:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:padding="5dip">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name here"
android:textStyle="bold"
android:id="#+id/member_name"
android:layout_centerVertical="true"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="email#gmail.com"
android:id="#+id/member_email"
android:layout_below="#+id/member_name"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="email#gmail.com"
android:id="#+id/member_status"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"/>
</RelativeLayout>
</LinearLayout>
Model Class:
public class Member {
private String name;
private String email;
private String status;
public Member(String name, String email, String status) {
this.name = name;
this.email = email;
this.status = status;
}
public Member(String name){
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
Atlast! I was able to find the resolution for this. Kudos to the developer himself, Xaver Kapeller!
public void populate(){
JsonArrayRequest request = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
// hidePDialog();
String email, status;
// Member member;
for(int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject object = jsonArray.getJSONObject(i);
final String name = object.getString("firstname") + " " + object.getString("lastname");
email = object.getString("email");
if(Integer.parseInt(object.getString("activated"))==1){
status = "Active";
}else{
status = "Not Active";
}
mModels.add(new ExampleModel(name));
// member = new Member(name, email, status);
} catch (Exception e) {
}
}
mAdapter = new ExampleAdapter(getActivity(), mModels);
mRecyclerView.setAdapter(mAdapter);
}
}, new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError volleyError) {
volleyError.printStackTrace();
}
});
AppController.getInstance().addToRequestQueue(request);
}
Just tranfer these two lines of code inside onResponse() and everything will work perfectly fine:
mAdapter = new ExampleAdapter(getActivity(), mModels);
mRecyclerView.setAdapter(mAdapter);

Categories

Resources