Reason of RecyclerView Not Loading Data - java

I tried to create a List with RecyclerView in Android. However, I don't understand why the RecyclerView could not load data properly. I tried to compare my codes with the example available online and I could not tell what is the difference between example codes and my codes.
Can anyone help to point out what is missing or what is wrong with my code?
activity_main.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="daozui.assignment3_task3.MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/RecyclerView"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
contact_arrangement.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="match_parent">
<ImageView
android:id="#+id/contactIcon_ID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/man"
android:layout_margin="10dp"/>
<TextView
android:id="#+id/contactName_ID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:textSize="30sp"
android:text="Name"
android:layout_toEndOf="#id/contactIcon_ID"
android:layout_marginTop="25dp"
android:layout_marginStart="25dp"/>
<TextView
android:id="#+id/contactRelationship_ID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FFBEB9B9"
android:textSize="20sp"
android:text="Relationship"
android:layout_alignStart="#id/contactName_ID"
android:layout_below="#id/contactName_ID"/>
</RelativeLayout>
MainActivity.Java
package daozui.assignment3_task3;
import android.app.ListFragment;
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;
import java.util.List;
public class MainActivity extends AppCompatActivity {
RecyclerView theRecyclerView;
List<Contact> contactList;
ContactAdapter theAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createList();
theRecyclerView = (RecyclerView) findViewById(R.id.RecyclerView);
theRecyclerView.setLayoutManager(new LinearLayoutManager(this));
theAdapter = new ContactAdapter(contactList);
theRecyclerView.setAdapter(theAdapter);
}
private void createList() {
contactList = new ArrayList<Contact>();
contactList.add(new Contact("Alex", "male", "Friends", "0123456789"));
contactList.add(new Contact("Mona", "female", "Friends", "9876543210"));
}
}
ContactAdapter.Java
package daozui.assignment3_task3;
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 android.widget.Toast;
import java.util.List;
public class ContactAdapter extends RecyclerView.Adapter<ContactAdapter.theViewHolder> {
private List<Contact> contacList;
public ContactAdapter(List<Contact> ContactList) {
this.contacList = ContactList;
}
#Override
public ContactAdapter.theViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.contact_arrangement, parent, false);
return new theViewHolder(itemView);
}
#Override
public void onBindViewHolder(theViewHolder holder, int position) {
Contact contact = contacList.get(position);
holder.contactName.setText(contact.getName());
holder.contactRelationship.setText(contact.getRelationship());
if (contact.getGender().equals("male")) {
holder.contactIcon.setImageResource(R.drawable.man);
} else {
holder.contactIcon.setImageResource(R.drawable.woman);
}
}
#Override
public int getItemCount() {
return 0;
}
public static class theViewHolder extends RecyclerView.ViewHolder {
public TextView contactName, contactRelationship;
public ImageView contactIcon;
public theViewHolder(View itemView) {
super(itemView);
contactIcon = (ImageView) itemView.findViewById(R.id.contactIcon_ID);
contactName = (TextView) itemView.findViewById(R.id.contactName_ID);
contactRelationship = (TextView) itemView.findViewById(R.id.contactRelationship_ID);
// itemView.setOnClickListener(this);
}
// #Override
// public void onClick(View view)
// {
// int pos= getAdapterPosition();
// Toast.makeText(itemView.getContext(),contacList.get(pos).getContactNumber(),Toast.LENGTH_LONG);
// }
}
}
Contact.Java
package daozui.assignment3_task3;
public class Contact {
private String name;
private String gender;
private String relationship;
private String contactNumber;
public Contact(String Name, String Gender, String Relationship, String ContactNumber) {
this.name = Name;
this.gender = Gender;
this.relationship = Relationship;
this.contactNumber = ContactNumber;
}
public String getName() {
return name;
}
public String getGender() {
return gender;
}
public String getRelationship() {
return relationship;
}
public String getContactNumber() {
return contactNumber;
}
}

The problem is here:
#Override
public int getItemCount() {
return 0;
}
You should return the size of your list:
#Override
public int getItemCount() {
return contactList.size();
}

You should return the size of your collection here:
#Override
public void getItemCount(){
return contactList.size();
}
getItemCount() Returns the total number of items in the data set held by the adapter.
The int value that getItemCount() returns is the number of times the RecyclerView is going to look for data from your collection to bind.

notify your adapter that data is updated.!
notifyDataSetChanged();
#Override
public int getItemCount() {
return contactList.size();
}

In the event the list is null, use this simple ternary to avoid a null pointer exception;
#Override
public int getItemCount() {
return contactList == null ? 0 : contactList.size();
}

Related

How to set different images in the adapter of a cardview using recyclerview

I'm trying to use different images in different cardviews but the app displays on every card the image set in the xml layout.
App appearance in emulator
XML code for the card
<androidx.cardview.widget.CardView 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/cv"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:animateLayoutChanges="true"
app:cardCornerRadius="20dp"
app:cardElevation="4dp"
android:layout_margin="5dp">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/iconImageView"
android:src="#drawable/metodologia"
android:layout_width="70dp"
android:layout_height="70dp"
android:paddingLeft="14dp"
android:paddingRight="14dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
Elements that are in the card
package com.example.recyclerviewcardview;
import java.io.Serializable;
public class ListElement implements Serializable {
public Integer icon;
public String topic;
public String law1;
public ListElement(Integer icon, String topic, String law1) {
this.icon = icon;
this.topic = topic;
this.law1 = law1;
}
public Integer getIcon() { return icon; }
public void setIcon(Integer icon) { this.icon = icon; }
public String getTopic() {
return topic;
}
public void setTopic(String topic) { this.topic = topic; }
public String getLaw1() { return law1; }
public void setLaw1(String law1) { this.law1 = law1; }
}
The adapter
package com.example.recyclerviewcardview;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
public class ListAdapter extends RecyclerView.Adapter<ListAdapter.ViewHolder> {
private List<ListElement> mData;
private LayoutInflater mInflater;
private Context context;
final ListAdapter.OnItemClickListener listener;
public interface OnItemClickListener {
void onItemClick(ListElement item);
}
public ListAdapter (List<ListElement> itemList, Context context, ListAdapter.OnItemClickListener listener) {
this.mInflater = LayoutInflater.from(context);
this.context = context;
this.mData = itemList;
this.listener = listener;
}
#Override
public int getItemCount() {return mData.size();}
#Override
public ListAdapter.ViewHolder onCreateViewHolder (ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_element, parent, false);
return new ListAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder (final ListAdapter.ViewHolder holder, final int position) {
holder.bindData(mData.get(position));
}
// public void setItems(List<ListElement> items) {mData = items; }
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView iconImage;
TextView topic, law1;
ViewHolder (View itemView) {
super (itemView);
iconImage = itemView.findViewById(R.id.iconImageView);
topic = itemView.findViewById(R.id.topicTextView);
law1 = itemView.findViewById(R.id.law1TextView);
}
void bindData (final ListElement item) {
iconImage.setImageResource(getIcon());
topic.setText(item.getTopic());
law1.setText(item.getLaw1());
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listener.onItemClick(item);
}
});
}
}
}
The problem is this, at the end of the adapter
void bindData (final ListElement item) {
//--------------> iconImage.setImageResource(getIcon());
topic.setText(item.getTopic());
law1.setText(item.getLaw1());
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listener.onItemClick(item);
}
});
}
I can't make the getIcon() method to work
iconImage.setImageResource(getIcon());
How could I do it? Thanks.

Cannot resolve method 'setAdapter' in 'ConstraintLayout'

I am new to android development and am trying to bind recycler View with setAdapter but am getting this error "Cannot resolve method 'setAdapter' in 'ConstraintLayout' "
my mainActivity.java code is:
my main objective is to use ActivityMainBinding to bind recyclerView with setAdapter
package com.example.baatcheet;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import com.example.baatcheet.usersAdapter.*;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.example.baatcheet.databinding.ActivityMainBinding;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ActivityMainBinding binding;
FirebaseDatabase database;
ArrayList<User> users;
usersAdapter UserAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
database = FirebaseDatabase.getInstance();
users = new ArrayList<>();
UserAdapter = new usersAdapter(this, users);
binding.recyclerView.setAdapter(UserAdapter);
database.getReference().child("users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
users.clear();
for(DataSnapshot snapshot1 : snapshot.getChildren()){
User user = snapshot1.getValue(User.class);
users.add(user);
}
UserAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.search:
Toast.makeText(this,"Search Clicked" , Toast.LENGTH_SHORT).show();
break;
case R.id.settings:
Toast.makeText(this , " setting Clicked" , Toast.LENGTH_SHORT).show();
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.top_menu,menu);
return super.onCreateOptionsMenu(menu);
}
}
this is the part where i am getting an error -> binding.recyclerView.setAdapter(UserAdapter);
and it tells me to rename reference
what does this actually mean?
the activity_main.xml file is:
<?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:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottomNavigationView2"
android:layout_width="match_parent"
android:layout_height="0dp"
app:elevation="30dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:menu="#menu/menu">
</com.google.android.material.bottomnavigation.BottomNavigationView>
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintBottom_toTopOf="#+id/bottomNavigationView2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:listitem="#layout/row_conversation"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
the users.java code is:
package com.example.baatcheet;
public class User {
private String uid,name,phoneNumber,profileImage;
public User(){
}
public User(String uid, String name, String phoneNumber, String profileImage) {
this.uid = uid;
this.name = name;
this.phoneNumber = phoneNumber;
this.profileImage = profileImage;
}
public void setUid(String uid) {
this.uid = uid;
}
public void setName(String name) {
this.name = name;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public void setProfileImage(String profileImage) {
this.profileImage = profileImage;
}
public String getUid() {
return uid;
}
public String getName() {
return name;
}
public String getPhoneNumber() {
return phoneNumber;
}
public String getProfileImage() {
return profileImage;
}
}
the usersAdapter.java code is:
package com.example.baatcheet;
import android.content.Context;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.baatcheet.databinding.RowConversationBinding;
import java.util.ArrayList;
public class usersAdapter extends RecyclerView.Adapter<usersAdapter.UsersViewHolder>{
Context context;
ArrayList<User> users;
public usersAdapter(Context context , ArrayList<User> users){
this.context = context;
this.users = users;
}
{
}
#NonNull
#Override
public UsersViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.row_conversation,parent,false);
return new UsersViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull UsersViewHolder holder, int position) {
User user = users.get(position);
holder.binding.userName.setText(user.getName());
}
#Override
public int getItemCount() {
return users.size();
}
public class UsersViewHolder extends RecyclerView.ViewHolder{
RowConversationBinding binding;
public UsersViewHolder(#NonNull View itemView) {
super(itemView);
binding = RowConversationBinding.bind(itemView);
}
}
}
In your layout file, it is the root ConstraintLayout that has the #+id/recyclerView id:
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/recyclerView"
... />
You should move this id to the RecyclerView itself:
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
... />
Once you do this, binding.recyclerView will refer to the RecyclerView instead of the ConstraintLayout.
If you need to access the ConstraintLayout via the view binding for some other reason, you can use binding.root.

I am trying to retrieved data from firestore in recyclerview in android studio but getting blank page and no error i have tried many way but not work

sorry in adavaced bcz i am first time askking question on stack flow so and if need any other please let me know
okk my firestore Collestion is like these collection("user").document(currentUserId).collection("AddBlog").document
and i need AddBlog document and last my field name of firestore is same to model.java variable
code of activity name Trial.java
package com.example.talkvirtual;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.ArrayList;
import java.util.List;
public class TrialActivity extends AppCompatActivity {
RecyclerView recyclerView;
ArrayList<Model> dataList;
FirebaseFirestore db;
FirebaseAuth mAuth;
MyAdapter myAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_trial);
recyclerView = findViewById(R.id.recyclerViewTrial);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
dataList = new ArrayList<>();
recyclerView.setAdapter(myAdapter);
myAdapter = new MyAdapter(dataList,this);
db = FirebaseFirestore.getInstance();
mAuth= FirebaseAuth.getInstance();
String currentUserId = mAuth.getCurrentUser().getUid();
db.collection("user").document(currentUserId).collection("AddBlog").get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
List<DocumentSnapshot> list = queryDocumentSnapshots.getDocuments();
for (DocumentSnapshot d : list) {
Model model = d.toObject(Model.class);
dataList.add(model);
}
myAdapter.notifyDataSetChanged();
}
});
}
}
code of adpater class name MyAdapter.java
package com.example.talkvirtual;
import android.content.Context;
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 java.util.ArrayList;
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
public MyAdapter(ArrayList<Model> listblogProfile, Context context) {
this.ListblogProfile = listblogProfile;
this.context = context;
}
private ArrayList<Model> ListblogProfile;
private Context context;
// private ShowActivity activity;
#NonNull
#Override
public MyAdapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.container_blog, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyAdapter.MyViewHolder holder, int position) {
Model model = ListblogProfile.get(position);
holder.blogTitleTv.setText(model.getBlogTitle());
holder.blogContentTv.setText(model.getBlogContent());
}
#Override
public int getItemCount() {
return ListblogProfile.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
private TextView blogTitleTv, blogContentTv;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
blogContentTv = itemView.findViewById(R.id.blogContentContainer);
blogTitleTv = itemView.findViewById(R.id.getTitleContainer);
}
}
}
code of my cardView xml file
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/layoutNote"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:foreground="?attr/selectableItemBackgroundBorderless"
app:cardElevation="8dp"
android:layout_margin="10dp"
android:background="#color/light_dark">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/getTitleContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Title"
android:textColor="#color/textColor"
android:textSize="24dp"
android:textStyle="bold"
android:padding="10dp"
/>
<TextView
android:id="#+id/blogContentContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxHeight="100dp"
android:textColor="#color/textColor"
android:hint="Blog Content"
android:textColorHint="#color/gray"
android:textSize="20dp"
android:padding="10dp"/>
</LinearLayout>
</androidx.cardview.widget.CardView>
code of model class
package com.example.talkvirtual;
public class Model {
String blogTitle;
String blogContent;
String id;
public Model(){}//empty constructor is neccessary firebase
public Model(String blogTitle, String blogContent, String id) {
this.blogTitle = blogTitle;
this.blogContent = blogContent;
this.id = id;
}
public String getBlogTitle() {
return blogTitle;
}
public void setBlogTitle(String blogTitle) {
this.blogTitle = blogTitle;
}
public String getBlogContent() {
return blogContent;
}
public void setBlogContent(String blogContent) {
this.blogContent = blogContent;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
I think There are two mistake
1.Your adapter does not have the valid value
when you set it for the recyclerview
2.Your data is null because you don't add any member to it as well as the adapter.
db.collection("user").document(currentUserId).collection("AddBlog").get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
List<DocumentSnapshot> list = queryDocumentSnapshots.getDocuments();
for (DocumentSnapshot d : list) {
Model model = d.toObject(Model.class);
dataList.add(model);
}
myAdapter.notifyDataSetChanged();
}
});
myAdapter = new MyAdapter(dataList,this);
recyclerView.setAdapter(myAdapter);
I guess this should be work.

listview won't populate from other class

i'm new to java and android(programmed in C# before).
i'm trying to populate a listview with a custom layout but nothing happens.
the listview is in the main activity and is being updated from a separate class.
here is all the stuff that i am trying to find the problem in:
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"
tools:context="com.nasir.pre_alpha.MainActivity"
android:orientation="vertical">
<Button
android:text="Get Messages"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/msg_list"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="18dp"
android:onClick="onClick" />
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="15dp"
android:layout_below="#+id/msg_list"
android:id="#+id/msg_listview" />
</RelativeLayout>
list_view_layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/linearlayout">
<TextView
android:text="Number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView" />
<TextView
android:text="NUMBER"
android:layout_width="171dp"
android:layout_height="wrap_content"
android:id="#+id/txt_number" />
<TextView
android:text="Message Text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView3" />
<TextView
android:text="TEXT"
android:layout_height="wrap_content"
android:id="#+id/txt_msg"
android:layout_width="171dp" />
</LinearLayout>
MainActivity.java:
package com.nasir.pre_alpha;
import android.Manifest;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActivityCompat.requestPermissions(this ,new String[]{Manifest.permission.READ_SMS},255);
}
public void onClick (View l){
ContentResolver rslv=getContentResolver();
final String[] p=new String[]{"*"};
Uri uri=Uri.parse("content://sms");
Cursor cursor=rslv.query(uri,p,null,null,null);
cursor.moveToFirst();
ArrayList<String> numbers=new ArrayList<>();
ArrayList<String> msg_body=new ArrayList<>();
while (cursor.moveToNext()){
numbers.add(cursor.getString(cursor.getColumnIndex("address")));
msg_body.add(cursor.getString(cursor.getColumnIndex("body")));
}
model m=new model();
view v=new view();
controller c=new controller(m,v,getApplicationContext());
c.set_data(numbers,msg_body);
c.view_data();
}
}
model.java:
package com.nasir.pre_alpha;
import java.util.ArrayList;
/**
* Created by Rhasta on 6/26/2017.
*/
public class model {
private ArrayList<String> numbers=new ArrayList<>();
private ArrayList<String> msg_body=new ArrayList<>();
public ArrayList<String> get_numbers(){
return numbers;
}
public ArrayList<String> getMsg_body(){
return msg_body;
}
public void set_numbers(ArrayList<String> numbers){
this.numbers=numbers;
}
public void set_Msgbody(ArrayList<String> msg_body){
this.msg_body=msg_body;
}
}
view.java:
package com.nasir.pre_alpha;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
/**
* Created by Rhasta on 6/26/2017.
*/
public class view {
private Context c;
private class viewadapter extends BaseAdapter{
private ArrayList<String> numbers=new ArrayList<>();
private ArrayList<String> msg_body=new ArrayList<>();
public viewadapter(ArrayList<String> numbers,ArrayList<String> msg_body){
this.numbers=numbers;
this.msg_body=msg_body;
}
public int getCount(){
return numbers.size();
}
public View getView(int pos, View view, ViewGroup viewGroup){
LayoutInflater inflater=(LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row=inflater.inflate(R.layout.list_view_layout,null);
TextView number=(TextView)row.findViewById(R.id.txt_number);
number.setText(numbers.get(pos));
TextView msg_body=(TextView)row.findViewById(R.id.txt_msg);
Toast.makeText(c,msg_body.getText(),Toast.LENGTH_SHORT).show();
msg_body.setText(this.msg_body.get(pos));
return row;
}
public long getItemId(int pos){
return pos;
}
public Object getItem(int arg){
return null;
}
}
void set_context(Context context){
c=context;
}
public void update_data(ArrayList<String> numbers,ArrayList<String> msg_body){
viewadapter adapter=new viewadapter(numbers,msg_body);
LayoutInflater inflater=(LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v=inflater.inflate(R.layout.activity_main,null);
ListView lst=(ListView)v.findViewById(R.id.msg_listview);
lst.setAdapter(adapter);
}
}
controller.java:
package com.nasir.pre_alpha;
import android.content.Context;
import java.util.ArrayList;
/**
* Created by Rhasta on 6/26/2017.
*/
public class controller {
private model m;
private view v;
private Context c;
public controller(model m,view v,Context c){
this.m=m;
this.v=v;
this.c=c;
}
public void set_data(ArrayList<String> numbers,ArrayList<String> msg_body){
this.m.set_numbers(numbers);
this.m.set_Msgbody(msg_body);
}
public void view_data(){
v.set_context(c);
v.update_data(m.get_numbers(),m.getMsg_body());
}
}
but i can't find the problem.
the listview is just empty(won't show up)
You didn't initialize the listview and you haven't assigned a list of items to it. Try:
ListView listview = (ListView) findViewById(R.id.msg_listview);
listview.setAdapter(.......);
I really can't understand your code. I'd suggest you do it like this:
add this:
<uses-permission android:name="android.permission.READ_CONTACTS" />
in your manifest instead of:
ActivityCompat.requestPermissions(this ,new String[]{Manifest.permission.READ_SMS},255);
MainActivity
public class MainActivity extends AppCompatActivity {
private ArrayList<model> list = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewadapter adapter = new viewadapter(list, getApplicationContext());
ListView lst = (ListView) findViewById(R.id.msg_listview);
lst.setAdapter(adapter);
}
public void onClick (View l){
ContentResolver rslv = getContentResolver();
final String[] p = new String[]{"*"};
Uri uri = Uri.parse("content://sms");
Cursor cursor = rslv.query(uri, p, null, null, null);
cursor.moveToFirst();
while (cursor.moveToNext()){
String address = cursor.getString(cursor.getColumnIndex("address"));
String body = cursor.getString(cursor.getColumnIndex("body"));
model m = new model();
m.setNumbers(address);
m.setMsgbody(body);
list.add(m);
}
}
}
model
public class model {
String numbers;
String msg_body;
public String getNumbers(){
return numbers;
}
public String getMsg_body(){
return msg_body;
}
public void setNumbers(String numbers){
this.numbers = numbers;
}
public void setMsgbody(String msg_body){
this.msg_body = msg_body;
}
}
viewadapter
private class viewadapter extends BaseAdapter{
private ArrayList<model> list = new ArrayList<>();
private Context context;
public viewadapter(ArrayList<model> list, Context context){
this.list = list;
this.context = context;
}
public int getCount(){
return list.size();
}
public View getView(int pos, View view, ViewGroup viewGroup){
View row = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_view_layout, null);
model model = list.get(pos)
TextView number = (TextView) row.findViewById(R.id.txt_number);
number.setText(model.getNumbers);
TextView msg_body = (TextView) row.findViewById(R.id.txt_msg);
Toast.makeText(c, msg_body.getText(), Toast.LENGTH_SHORT).show();
msg_body.setText(model.getMsg_body());
return row;
}
public long getItemId(int pos){
return pos;
}
public Object getItem(int arg){
return list.get(arg);
}
}
}
I don't think there is any need for a controller class.

RecyclerView Issue

MainActivity.java
its my main java class
package com.example.shikhu.newpractice;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this,DisplayList.class));
}
});
}
}
DisplayList.java
package com.example.shikhu.newpractice;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class DisplayList extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dsiplay_list);
BackgroundTask backgroundTask = new BackgroundTask(DisplayList.this);
backgroundTask.execute();
}
}
BackgroundTask.java
package com.example.shikhu.newpractice;
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
public class BackgroundTask extends AsyncTask<Void,Fruit,Void> {
String json_string = "http://192.168.1.18:8081/fruitinfo/get_fruit_details.php";
Context ctx;
Activity activity;
RecyclerView recyclerView;
RecyclerView.Adapter adapter;
RecyclerView.LayoutManager layoutManager;
ArrayList<Fruit> arrayList = new ArrayList<>();
public BackgroundTask(Context ctx)
{
this.ctx=ctx;
activity = (Activity)ctx;
}
#Override
protected void onPreExecute() {
recyclerView = (RecyclerView)activity.findViewById(R.id.recyclerview);
layoutManager = new LinearLayoutManager(ctx);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
adapter = new RecyclerAdapter(arrayList);
recyclerView.setAdapter(adapter);
}
#Override
protected Void doInBackground(Void... params) {
try{
URL url = new URL(json_string);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line;
while((line=bufferedReader.readLine())!=null)
{
stringBuilder.append(line + "\n");
}
httpURLConnection.disconnect();
String json_string = stringBuilder.toString().trim();
JSONObject jsonObject = new JSONObject(json_string);
JSONArray jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
while (count<jsonArray.length())
{
JSONObject JO = jsonArray.getJSONObject(count);
count++;
Fruit fruit = new Fruit(JO.getString("name"),JO.getInt("calories"),JO.getDouble("fat"));
publishProgress(fruit);
}
Log.d("JSON STRING",json_string);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Fruit... values) {
arrayList.add(values[0]);
adapter.notifyDataSetChanged();
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
}
RecyclerAdapter.java
package com.example.shikhu.newpractice;
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 RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.RecyclerViewHolder> {
private static final int TYPE_HEAD = 0;
private static final int TYPE_LIST = 1;
ArrayList<Fruit> arrayList = new ArrayList<>();
public RecyclerAdapter(ArrayList<Fruit> arrayList)
{
this.arrayList =arrayList;
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == TYPE_HEAD)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.header_layout,parent,false);
RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(view,viewType);
return recyclerViewHolder;
}
else if (viewType == TYPE_LIST)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_layout,parent,false);
RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(view,viewType);
return recyclerViewHolder;
}
return null;
}
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
if (holder.viewType == TYPE_LIST) {
Fruit fruit = arrayList.get(position);
holder.Name.setText(fruit.getName());
holder.Calories.setText(Integer.toString(fruit.getCalories()));
holder.Fat.setText(Double.toString(fruit.getFat()));
}
}
#Override
public int getItemCount() {
return arrayList.size();
}
public static class RecyclerViewHolder extends RecyclerView.ViewHolder
{
TextView Name,Calories,Fat;
int viewType;
public RecyclerViewHolder(View v,int viewType)
{
super(v);
if (viewType == TYPE_LIST) {
Name = (TextView) v.findViewById(R.id.name);
Calories = (TextView) v.findViewById(R.id.calories);
Fat = (TextView) v.findViewById(R.id.fat);
this.viewType = TYPE_LIST;
}else if (viewType == TYPE_HEAD)
{
this.viewType = TYPE_HEAD;
}
}
public int getItemViewType(int position)
{
if (position==0)
return TYPE_HEAD;
return TYPE_LIST;
}
}
}
Fruit.java
package com.example.shikhu.newpractice;
public class Fruit {
private String name;
private int calories;
private Double fat;
public Fruit(String name,int calories,Double fat)
{
this.setName(name);
this.setCalories(calories);
this.setFat(fat);
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name=name;
}
public int getCalories()
{
return calories;
}
public void setCalories(int calories)
{
this.calories=calories;
}
public Double getFat()
{
return fat;
}
public void setFat(Double fat)
{
this.fat=fat;
}
}
Row_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="75dp"
android:layout_marginRight="15dp"
android:layout_marginLeft="15dp"
android:weightSum="1">
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:textStyle="bold"
android:textSize="20dp"
android:text="Name"
android:id="#+id/name"
android:layout_weight="0.39" />
<TextView
android:layout_width="79dp"
android:layout_height="match_parent"
android:text="Calorie"
android:gravity="center_vertical"
android:textSize="20dp"
android:textStyle="bold"
android:id="#+id/calories"
android:layout_marginLeft="40dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="Fat"
android:gravity="center_vertical"
android:textSize="20dp"
android:textStyle="bold"
android:id="#+id/fat"
android:layout_weight="0.15"
android:layout_marginLeft="60dp" />
</LinearLayout>
Header_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="65dp"
android:background="?attr/colorPrimary">
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:textStyle="bold"
android:textSize="20dp"
android:text="Name"
android:id="#+id/name1"
android:layout_weight="0.20"
android:textColor="#ffffff"
android:layout_marginLeft="10dp" />
<TextView
android:layout_width="79dp"
android:layout_height="match_parent"
android:text="Calorie"
android:gravity="center_vertical"
android:textSize="20dp"
android:textStyle="bold"
android:id="#+id/calories1"
android:layout_marginLeft="10dp"
android:textColor="#ffffff"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="Fat"
android:gravity="center_vertical"
android:textSize="20dp"
android:textStyle="bold"
android:id="#+id/fat1"
android:layout_weight="0.15"
android:layout_marginLeft="60dp"
android:textColor="#ffffff"/>
</LinearLayout>
activity_display_list.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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".DisplayList">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/recyclerview"></android.support.v7.widget.RecyclerView>
</RelativeLayout>
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: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.example.shikhu.newpractice.MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Display List"
android:id="#+id/button"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
My Output
i dont know why it is showing text of textview rather the data fetched from database
enter image description here
PhpScript
<?php
$host = "localhost";
$user = "root";
$pass = "";
$db = "fruit";
$con = mysqli_connect($host,$user,$pass,$db);
$query= "select * from fruit_details;";
$result = mysqli_query($con,$query);
$response = array();
while($row = mysqli_fetch_array($result))
{
array_push($response,array('name'=>$row[0],'calories'=>$row[1],'fat'=>$row[2 ]));
}
mysqli_close($con);
echo json_encode(array('server_response'=>$response));
?>
Your Adapter always return TYPE_HEAD i think this is wrong.
#Override
public int getItemViewType(int position) {
if (position == 0) {
return TYPE_HEAD;
} else {
return TYPE_LIST;
}
}
BackgroundTask.Java
package com.example.shikhu.newpractice;
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
public class BackgroundTask extends AsyncTask<Void,Fruit,Void> {
String json_string = "http://127.0.0.1:8081/fruitinfo/get_fruit_details.php";
Context ctx;
Activity activity;
RecyclerView recyclerView;
RecyclerView.Adapter adapter;
RecyclerView.LayoutManager layoutManager;
ArrayList<Fruit> arrayList = new ArrayList<>();
public BackgroundTask(Context ctx)
{
this.ctx=ctx;
activity = (Activity)ctx;
}
#Override
protected void onPreExecute() {
recyclerView = (RecyclerView)activity.findViewById(R.id.recyclerview);
layoutManager = new LinearLayoutManager(ctx);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
adapter = new RecyclerAdapter(arrayList);
recyclerView.setAdapter(adapter);
}
#Override
protected Void doInBackground(Void... params) {
try{
URL url = new URL(json_string);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line;
while((line=bufferedReader.readLine())!=null)
{
stringBuilder.append(line + "\n");
}
httpURLConnection.disconnect();
String json_string = stringBuilder.toString().trim();
JSONObject jsonObject = new JSONObject(json_string);
JSONArray jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
while (count<jsonArray.length())
{
JSONObject JO = jsonArray.getJSONObject(count);
count++;
Fruit fruit = new Fruit(JO.getString("name"),JO.getInt("calorie"),JO.getDouble("fat"));
publishProgress(fruit);
}
Log.d("JSON STRING",json_string);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Fruit... values) {
arrayList.add(values[0]);
adapter.notifyDataSetChanged();
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
}
RecyclerAdapter.java
package com.example.shikhu.newpractice;
import android.support.annotation.IdRes;
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 RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.RecyclerViewHolder> {
private static final int TYPE_HEAD = 0;
private static final int TYPE_LIST = 1;
ArrayList<Fruit> arrayList = new ArrayList<>();
public RecyclerAdapter(ArrayList<Fruit> arrayList)
{
this.arrayList =arrayList;
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == TYPE_HEAD)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.header_layout,parent,false);
RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(view,viewType);
return recyclerViewHolder;
}
else if (viewType == TYPE_LIST)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_layout,parent,false);
RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(view,viewType);
return recyclerViewHolder;
}
return null;
}
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
if (holder.viewType == TYPE_LIST) {
Fruit fruit = arrayList.get(position-1);
holder.Name.setText(fruit.getName());
holder.Calories.setText(Integer.toString(fruit.getCalories()));
holder.Fat.setText(Double.toString(fruit.getFat()));
}
}
#Override
public int getItemCount() {
return arrayList.size()+1;
}
public static class RecyclerViewHolder extends RecyclerView.ViewHolder
{
TextView Name,Calories,Fat;
int viewType;
public RecyclerViewHolder(View v,int viewType)
{
super(v);
if (viewType == TYPE_LIST) {
Name = (TextView) v.findViewById(R.id.name);
Calories = (TextView) v.findViewById(R.id.calories);
Fat = (TextView) v.findViewById(R.id.fat);
this.viewType = TYPE_LIST;
}else if (viewType == TYPE_HEAD)
{
this.viewType = TYPE_HEAD;
}
}
}
#Override
public int getItemViewType(int position) {
if (position==0)
return TYPE_HEAD;
else
return TYPE_LIST;
}
}
I think you are not managing views for header in your view holder and from bind view holder it is everytime getting only header view in return; SO just debug your code and let me know that are you getting TYPE_LIST data view or not. Also make references for header view in View holder and set text to it also.
I found your problem.
Your method getItemViewType is inside your ViewHolder class. It needs to be moved to be inside your adapter class. Right now, since your adapter has no getItemViewType method, it assumes all view types are 0 (HEADER), and so nothing is being bound.
Move this method to your adapter class and all will work :)
Edit
Another option which should work for you is to stop using viewTypes all together. Since you're using the same viewHolder anyway, when you bind the view, instead of checking the viewType, check the position:
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_layout,parent,false);
RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(view, TYPE_LIST);
return recyclerViewHolder;
}
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
if (position > 0) {
Fruit fruit = arrayList.get(position-1);
holder.Name.setText(fruit.getName());
holder.Calories.setText(Integer.toString(fruit.getCalories()));
holder.Fat.setText(Double.toString(fruit.getFat()));
} else {
holder.Name.setText("Name");
holder.Calories.setText("Calories");
holder.Fat.setText("Fat");
}
}
So now, all your view types will be of type list. This is fine, because the layout is basically identical, only the values of the TextViews changes. Instead of using viewType, simply use the position. If the position is 0, set the header fields, otherwise, use the Fruit data.
I know this is not the solution you wanted - I can't seem to find why the viewType implementation doesn't work, however, this solution should give you the result you wanted.
Hope this helps!

Categories