RecyclerView + CardView: Inflating Wrong Data - java

Im using CardView to create a list of cards with newsletters. The basic elements are 3 TextViews + 1 ImageView. I cant inflate 2 elements properly: the title is fine, but the link text the gets the wrong string(it gets the string referring to the body text) and the body TextView dont change at all.
Aeres a picture with the general ideia:
preview on android studio (left) and app running on device(right)
This is my CardView XML code:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
tools:context=".News">
<android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/card1_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardCornerRadius="4dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/news_title"
android:layout_width="match_parent"
android:layout_height="40dp"
android:paddingLeft="8dp"
android:text="articleTitle articleTitle articleTitle articleTitle articleTitle articleTitle articleTitle articleTitle articleTitle articleTitle articleTitle articleTitle articleTitle articleTitle "
android:textColor="#000000"
android:textSize="16sp"
android:textStyle="bold" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="150dp"
android:orientation="horizontal">
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="6"
android:orientation="vertical">
<TextView
android:id="#+id/news_link"
android:layout_width="match_parent"
android:layout_height="25dp"
android:gravity="center_vertical"
android:paddingLeft="8dp"
android:text="http://www.articleLink.com/" />
<TextView
android:id="#+id/news_body"
android:layout_width="match_parent"
android:layout_height="120dp"
android:paddingLeft="8dp"
android:text="Body Body Body Body Body Body Body Body Body Body Body Body Body Body Body Body Body Body Body Body Body Body Body Body Body Body Body Body Body Body Body Body Body ..."
android:textColor="#000000" />
</LinearLayout>
<ImageView
android:id="#+id/news_photoId"
android:layout_width="0dp"
android:layout_height="145dp"
android:layout_weight="5"
android:src="#drawable/enfnotum" />
</LinearLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="20dp"
android:gravity="end"
android:paddingEnd="6dp"
android:paddingRight="6dp"
android:text="Coments Share" />
<TextView
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#bab7b7" />
</LinearLayout>
</android.support.v7.widget.CardView>
RecycleView list layout XML code:
<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=".News">
<android.support.v7.widget.RecyclerView
android:id="#+id/rv"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Now the java classes:
Here im populating the list, calling the adapter
public class News extends AppCompatActivity {
private List<Article> articles = new ArrayList<>();
private RecyclerView rv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news);
rv = (RecyclerView) findViewById(R.id.rv);
LinearLayoutManager llm = new LinearLayoutManager(this);
rv.setLayoutManager(llm);
initializeData();
initializeAdapter();
}
private void initializeData() {
articles.add(new Article("0title", "0link", "0body", R.drawable.enfnotum));
articles.add(new Article("1title", "1link", "1body", R.drawable.enfnoticias));
articles.add(new Article("2title", "2link", "2body", R.drawable.image1));
articles.add(new Article("3title", "3link", "3body", R.drawable.image2));
articles.add(new Article("4title", "4link", "4body", R.drawable.image3));
articles.add(new Article("5title", "5link", "5body", R.drawable.enfnotum));
articles.add(new Article("6title", "6link", "6body", R.drawable.image3));
articles.add(new Article("7title", "7link", "7body", R.drawable.enfnoticias));
//TODO: database
}
private void initializeAdapter() {
NewsRVAdapter adapter = new NewsRVAdapter(articles);
rv.setAdapter(adapter);
}
}
My classe to create the list object, few getters
public class Article {
private String articleTitle;
private String articleLink;
private String articleBody;
private int articlePhotoId;
public Article(String articleTitle, String articleLink, String articleBody, int articlePhotoId) {
this.articleTitle = articleTitle;
this.articleLink = articleLink;
this.articleBody = articleBody;
this.articlePhotoId = articlePhotoId;
}
public String getArticleTitle() {
return articleTitle;
}
public String getArticleLink() {
return articleLink;
}
public String getArticleBody() {
return articleBody;
}
public int getArticlePhotoId() {
return articlePhotoId;
}
}
Inflating the layout
public class NewsRVAdapter extends RecyclerView.Adapter<NewsRVAdapter.ArticleViewHolder> {
List<Article> articles;
NewsRVAdapter(List<Article> articles) {
this.articles = articles;
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
#Override
public ArticleViewHolder onCreateViewHolder(ViewGroup viewGroup, int position) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.news_item_list, viewGroup, false);
return new ArticleViewHolder(v);
}
#Override
public void onBindViewHolder(ArticleViewHolder ArticleViewHolder, int position) {
ArticleViewHolder.articleTitle.setText(articles.get(position).getArticleTitle());
ArticleViewHolder.articleLink.setText(articles.get(position).getArticleLink());
ArticleViewHolder.articleLink.setText(articles.get(position).getArticleBody());
ArticleViewHolder.articlePhotoID.setImageResource(articles.get(position).getArticlePhotoId());
}
#Override
public int getItemCount() {
return articles.size();
}
public static class ArticleViewHolder extends RecyclerView.ViewHolder {
CardView cv;
TextView articleTitle;
TextView articleLink;
TextView articleBody;
ImageView articlePhotoID;
ArticleViewHolder(View itemView) {
super(itemView);
cv = (CardView) itemView.findViewById(R.id.card1_view);
articleTitle = (TextView) itemView.findViewById(R.id.news_title);
articleLink = (TextView) itemView.findViewById(R.id.news_link);
articleBody = (TextView) itemView.findViewById(R.id.news_body);
articlePhotoID = (ImageView) itemView.findViewById(R.id.news_photoId);
}
}
}

Looks like a typo error. Try to replace your NewsRVAdapter's onBindViewHolder with:
#Override
public void onBindViewHolder(ArticleViewHolder ArticleViewHolder, int position) {
ArticleViewHolder.articleTitle.setText(articles.get(position).getArticleTitle());
ArticleViewHolder.articleLink.setText(articles.get(position).getArticleLink());
ArticleViewHolder.articleBody.setText(articles.get(position).getArticleBody());
ArticleViewHolder.articlePhotoID.setImageResource(articles.get(position).getArticlePhotoId());
}

The reason is your wrong code in onBindViewHolder ^^
#Override
public void onBindViewHolder(ArticleViewHolder ArticleViewHolder, int position) {
ArticleViewHolder.articleTitle.setText(articles.get(position).getArticleTitle());
ArticleViewHolder.**articleLink**.setText(articles.get(position).getArticleLink());
ArticleViewHolder.**articleLink**.setText(articles.get(position).getArticleBody());
ArticleViewHolder.articlePhotoID.setImageResource(articles.get(position).getArticlePhotoId());
}
ArticleViewHolder.articleLink was assigned two times so its value was overriden.
Correct it and your code work fine :)

You have a mistake on onBindViewHolder. You were referencing to articleLink twice.
it should have been
#Override
public void onBindViewHolder(ArticleViewHolder ArticleViewHolder, int position){
ArticleViewHolder.articleTitle.setText(articles.get(position).getArticleTitle());
ArticleViewHolder.articleLink.setText(articles.get(position).getArticleLink());
ArticleViewHolder.articleBody.setText(articles.get(position).getArticleBody());
ArticleViewHolder.articlePhotoID.setImageResource(articles.get(position).getArticlePhotoId());
}

Related

how to get data from mysql database into recycler view?

I am making an app that let users create meetings and I would like the details of the meeting (eg name, type, location) in a recycler view.I ran the php code by itself and was able to get the values from the database.
Currently, I am getting an error of
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at in recyclerviewAdapter
holder.Name.setText(users.getName());
holder.Type.setText(users.getType());
holder.Location.setText(users.getLocation());
which is linked to
public class Users {
private String name,type,location;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
}
recyclerviewAdapter
public class UserAdapter extends RecyclerView.Adapter<UserAdapter.UserHolder>{
Context context;
List<Users> usersList;
public UserAdapter(Context context, List<Users> usersList) {
this.context = context;
this.usersList = usersList;
}
#NonNull
#Override
public UserHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View userLayout= LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_main2,parent,false);
return new UserHolder(userLayout);
}
#Override
public void onBindViewHolder(#NonNull UserHolder holder, int position) {
Users users=usersList.get(position);
holder.Name.setText(users.getName());
holder.Type.setText(users.getType());
holder.Location.setText(users.getLocation());
}
#Override
public int getItemCount() {
return usersList.size();
}
public class UserHolder extends RecyclerView.ViewHolder{
TextView Name,Type,Location;
public UserHolder(#NonNull View itemView){
super(itemView);
Name=itemView.findViewById(R.id.textTitle);
Type=itemView.findViewById(R.id.textType);
Location=itemView.findViewById(R.id.textLocation);
}
}
}
main activity code
public class MainActivity2 extends AppCompatActivity {
private static final String URL = "http://10.0.2.2/mad/activitydisplay.php";
RecyclerView recyclerView;
UserAdapter userAdapter;
List<Users> usersList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
recyclerView = findViewById(R.id.recylcerList);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
usersList=new ArrayList<>();
LoadAllUser();
}
private void LoadAllUser() {
JsonArrayRequest request =new JsonArrayRequest(URL, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray array) {
for (int i=0;i<array.length();i++){
try {
JSONObject object=array.getJSONObject(i);
String name=object.getString("eventname").trim();
String type=object.getString("type").trim();
String location=object.getString("location").trim();
Users user= new Users();
user.setName(name);
user.setType(type);
user.setLocation(location);
usersList.add(user);
} catch (JSONException e) {
e.printStackTrace();
}
}
userAdapter=new UserAdapter(MainActivity2.this,usersList);
recyclerView.setAdapter(userAdapter);
}
},new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error){
Toast.makeText(MainActivity2.this, error.toString(), Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue=Volley.newRequestQueue(MainActivity2.this);
requestQueue.add((request));
}
}
php code to get data from table
$sql="SELECT * FROM `activitytable` ";
$result=mysqli_query($conn,$sql);
$user=array();
while($row = mysqli_fetch_assoc($result)){
$index['eventname']=$row['eventname'];
$index['type']=$row['type'];
$index['location']=$row['location'];
array_push($user, $index);
}
echo json_encode($user);
activity_main2.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity2">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recylcerList"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
activity_list resource file
<?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">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:orientation="vertical">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:orientation="horizontal" >
<TextView
style="bold"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Title:"
android:textColor="#color/black"
android:textSize="24dp" />
<TextView
android:id="#+id/textTitle"
style="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/black"
android:textSize="24dp" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:orientation="horizontal" >
<TextView
style="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Type:"
android:textColor="#color/black"
android:textSize="24dp" />
<TextView
android:id="#+id/textType"
style="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/black"
android:textSize="24dp" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:orientation="horizontal" >
<TextView
style="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Location:"
android:textColor="#color/black"
android:textSize="24dp" />
<TextView
android:id="#+id/textLocation"
style="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/black"
android:textSize="24dp" />
</LinearLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
instead of
public UserHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View userLayout= LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_main2,parent,false);
return new UserHolder(userLayout);
}
use this
public UserHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View userLayout= LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_list ,parent,false);
return new UserHolder(userLayout);
}
because activity_main2 doesn't contain R.id.textTitle,R.id.textType,R.id.textLocation
check your xml(R.layout.activity_main2) looks like id of your view are from another layout

Add ArrayLIst to Recyclerview

I have an AlertDialog in it there used to be a ListView in which the contents of the ArrayList were displayed. For beauty, I decided to replace it with Recyclerview, Card and the problems started.
Items are added to ArrayList <String> mainListWord during the work and they should be included in the Recyclerview cards. The problem is that either the entire list falls into one card at once, or each next card contains the previous elements + 1. For example: the first card: 1 element, the second card: 2 elements, etc.
How to implement it so that when a new element is added to the array, it will be placed in its own card?
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"
tools:context=".MainActivity">
<EditText
android:id="#+id/innerText"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_centerInParent="true"/>
<Button
android:id="#+id/press"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Press"
android:layout_below="#id/innerText"
android:layout_centerHorizontal="true"
android:onClick="openDialog"/>
</RelativeLayout>
recycler_item.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:cardCornerRadius="4dp"
android:layout_margin="4dp"
app:cardBackgroundColor="#color/colorCardBack">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:background="#color/colorCard">
<ImageView
android:id="#+id/imageView_1"
android:layout_width="50dp"
android:layout_height="50dp"
android:padding="4dp" />
<TextView
android:id="#+id/textview_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text_1"
android:textStyle="bold"
android:textColor="#android:color/black"
android:layout_centerInParent="true"
android:textSize="16sp"
android:layout_marginStart="5dp"
android:layout_toEndOf="#id/imageView_1"/>
</RelativeLayout>
</androidx.cardview.widget.CardView>
stats_fragment.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=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="50dp"
android:layout_margin="10dp"
android:background="#color/colorAccent"
android:scrollbars="vertical"
android:layout_above="#id/butClose"/>
<Button
android:id="#+id/butClose"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"/>
</RelativeLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
private EditText innerText;
private Button press, butClose;
private ArrayList<RecyclerViewItem> recyclerViewItem;
private ArrayList<String> mainListWord;
private AlertDialog OptionDialog;
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerViewItem = new ArrayList<>();
mainListWord = new ArrayList<>();
innerText = findViewById(R.id.innerText);
press = findViewById(R.id.butClose);
}
#RequiresApi(api = Build.VERSION_CODES.O)
public void makeRecyclerList(ArrayList<String> income){
String[] listWord_lenght = income.toArray(new String[0]);
String keyWord = (String.join("", listWord_lenght));
recyclerViewItem.add(new RecyclerViewItem(R.drawable.star, keyWord));
}
#RequiresApi(api = Build.VERSION_CODES.O)
public void openDialog(View v){
String word = innerText.getText().toString();
mainListWord.add(word);
makeRecyclerList(mainListWord);
Dialogus();
innerText.setText("");
}
public void Dialogus(){
LayoutInflater li = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = li.inflate(R.layout.stats_fragment, null, false);
OptionDialog = new AlertDialog.Builder(this).create();
OptionDialog.setTitle("TestInfo");
recyclerView = v.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
adapter = new RecyclerViewAdapter(recyclerViewItem);
layoutManager = new LinearLayoutManager(this);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(layoutManager);
butClose = v.findViewById(R.id.butClose);
OptionDialog.setView(v);
OptionDialog.setCancelable(true);
butClose.setBackgroundColor(Color.CYAN);
butClose.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
OptionDialog.dismiss();
}
});
OptionDialog.show();
}
}
RecyclerViewAdapter.java
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.RecyclerViewViewHolder> {
private ArrayList<RecyclerViewItem> arrayList;
public static class RecyclerViewViewHolder extends RecyclerView.ViewHolder {
public ImageView imageView_1;
public TextView textview_1;
public RecyclerViewViewHolder(#NonNull View itemView) {
super(itemView);
imageView_1 = itemView.findViewById(R.id.imageView_1);
textview_1 = itemView.findViewById(R.id.textview_1);
}
}
public RecyclerViewAdapter(ArrayList<RecyclerViewItem> arrayList){
this.arrayList = arrayList;
}
#NonNull
#Override
public RecyclerViewViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int viewType) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recycler_item, viewGroup, false);
RecyclerViewViewHolder recyclerViewViewHolder= new RecyclerViewViewHolder(view);
return recyclerViewViewHolder;
}
#Override
public void onBindViewHolder(#NonNull RecyclerViewViewHolder recyclerViewViewHolder, int position) {
RecyclerViewItem recyclerViewItem = arrayList.get(position);
recyclerViewViewHolder.imageView_1.setImageResource(recyclerViewItem.getImageResource());
recyclerViewViewHolder.textview_1.setText(recyclerViewItem.getText_1());
}
#Override
public int getItemCount() {
return arrayList.size();
}
}
RecyclerViewItem.java
package freijer.app.one;
public class RecyclerViewItem {
private int imageResource;
private String text_1;
public int getImageResource() {
return imageResource;
}
public void setImageResource(int imageResource) {
this.imageResource = imageResource;
}
public String getText_1() {
return text_1;
}
public void setText_1(String text_1) {
this.text_1 = text_1;
}
public RecyclerViewItem(int imageResource, String text_1) {
this.imageResource = imageResource;
this.text_1 = text_1;
}
}

Android View InflateExeption showing up when trying to start an app

I'm new to android development, and I'm having issues with my app crashing when I'm trying to start it
This is the error message:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.cybermath/com.example.cybermath.modules.MainActivity}: android.view.InflateException: Binary XML file line #25: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
And this is the XML file for the data within recycler viewer:
'''
<?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="wrap_content"
android:weightSum="100"
android:gravity="center_vertical"
android:background="#color/colorPrimaryDark"
>
<TextView
android:id="#+id/account_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="70"
android:background="#color/colorPrimary"
android:lines="1"
android:padding="10dp"
android:text="#string/app_name"
android:textColor="#color/colorText" >
</TextView>
<TextView
android:id="#+id/account_progress"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="20"
android:background="#color/colorPrimary"
android:text="Enter"
android:textSize="12sp"
android:textColor="#color/colorText"
>
</TextView>
'''
This is the XML for the MainActivity:
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="416dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/informationView"
android:id="#+id/recyclerView">
</androidx.recyclerview.widget.RecyclerView>
<!--<TextView
android:id="#+id/informationView"
android:layout_width="408dp"
android:layout_height="50dp"
android:foregroundTint="#00050000"
android:paddingStart="10dp"
android:paddingLeft="10dp"
android:paddingTop="10dp"
android:paddingRight="10dp"
android:paddingBottom="10dp"
android:text="Choose an account"
android:textAlignment="center"
android:textColor="#000000"
android:textSize="20sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.333"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
</TextView>-->
</androidx.constraintlayout.widget.ConstraintLayout>
And here is the code for the MainActivity:
'''
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
// UI
private RecyclerView mRecyclerView;
// Variables
#NonNull
private ArrayList<Account> mAccounts = new ArrayList<>();
private AccountsRecyclerAdapter mAccountsRecyclerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_account_list);
mRecyclerView = findViewById(R.id.recyclerView);
initRecyclerView();
insertFakeAccounts();
}
private void insertFakeAccounts(){
for(int i = 0; i < 1000; i++){
Account account = new Account();
account.setName("title #" + i);
mAccounts.add(account);
}
mAccountsRecyclerAdapter.notifyDataSetChanged();
}
private void initRecyclerView(){
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(linearLayoutManager);
mAccountsRecyclerAdapter = new AccountsRecyclerAdapter(mAccounts);
mRecyclerView.setAdapter(mAccountsRecyclerAdapter);
}
'''
And my adapter public class AccountsRecyclerAdapter extends
RecyclerView.Adapter<AccountsRecyclerAdapter.ViewHolder> {
private ArrayList<Account> mAccounts = new ArrayList<>();
public AccountsRecyclerAdapter(ArrayList<Account> accounts) {
this.mAccounts = accounts;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int i) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_account_list, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull AccountsRecyclerAdapter.ViewHolder viewHolder, int i) {
viewHolder.name.setText(mAccounts.get(i).getName());
}
#Override
public int getItemCount() {
return mAccounts.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView name;
public ViewHolder(#NonNull View itemView) {
super(itemView);
name = itemView.findViewById(R.id.account_name);
}
}
Some if the thing are not as per requirement may cause an exception. Check for condition as
if(yourValue !=null && yourValue.equals("desired value"){
//do your stuff
}

Recycler View and Card View not displaying cards

This is my Activity:
public String id;
public String passPhrase;
public ArrayList<SongCell> songs;
private RecyclerView recyclerView;
private MyAdapter myAdapter;
private RecyclerView.LayoutManager layoutManager;
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.songs_view_layout);
Context context = this.getApplicationContext();
Bundle stateData = getIntent().getExtras();
try
{
id = stateData.getString("id");
passPhrase = stateData.getString("passPhrase");
ArrayList data;
recyclerView = (RecyclerView) findViewById(R.id.song_list);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
data = new ArrayList<SongCell>();
for (int i=0; i<5;i++)
{
data.add(new SongCell("Song "+i,"Artist "+i, null));
}
myAdapter = new MyAdapter(data);
recyclerView.setAdapter(myAdapter);
}
catch(Exception e)
{
Log.d("Error: ", e.toString());
}
}
card.xml
<android.support.v7.widget.CardView android:layout_width="fill_parent"
android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="6dp"
>
<ImageView
android:layout_width="70dp"
android:layout_height="70dp"
android:id="#+id/song_photo"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginRight="16dp"
android:background="#drawable/error" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/song_name"
android:textSize="30sp"
android:text="Song Name"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:textColor="#000000" />
<ImageButton
android:layout_width="60dp"
android:layout_height="60dp"
android:id="#+id/vote_button"
android:layout_alignParentRight="true"
android:layout_marginRight="8dp"
android:background="#drawable/arrow" />
</RelativeLayout>
</android.support.v7.widget.CardView>
Activity.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="match_parent"
android:background="#2d2d2d">
<TableLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TableRow
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:paddingBottom="30dp"
android:layout_marginBottom="10dp"
android:background="#222222"></TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:paddingBottom="10dp">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<ImageView
android:layout_width="70dp"
android:layout_height="70dp"
android:id="#+id/featSongImage1"
android:contentDescription="#string/newsongimage"
android:background="#drawable/error" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="#string/songname"
android:id="#+id/featSongName1" />
<ImageButton
android:layout_width="25dp"
android:layout_height="25dp"
android:id="#+id/featSongButt1"
android:background="#drawable/arrow"
android:contentDescription="#string/votearrow" />
</LinearLayout>
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:foregroundGravity="fill_horizontal"
android:gravity="fill_horizontal|center">
<android.support.v7.widget.RecyclerView
android:id="#+id/song_list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center_horizontal" />
</TableRow>
</TableLayout>
</LinearLayout>
And this is my custom adapter
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder>
{
private ArrayList<SongCell> data;
public MyAdapter(ArrayList<SongCell> dataI)
{
data = dataI;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType)
{
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.song_card,viewGroup,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder viewholder, int pos) {
viewholder.songName.setText(data.get(pos).getName());
viewholder.artist.setText(data.get(pos).getArtist());
viewholder.image.setImageBitmap(data.get(pos).getArtwork());
}
#Override
public int getItemCount() {
return 0;
}
#Override
public int getItemViewType(int position) {
return 0;
}
public class ViewHolder extends RecyclerView.ViewHolder
{
TextView songName;
TextView artist;
ImageView image;
ImageButton voteButton;
public ViewHolder(View v)
{
super(v);
this.songName = (TextView) v.findViewById(R.id.song_name);
this.image = (ImageView) v.findViewById(R.id.song_photo);
this.voteButton = (ImageButton) v.findViewById(R.id.vote_button);
}
}
}
I have looked at a ton of guides on how to get this working but it still doesn't work. Anyone have any clue what's going on? I'm on version 25.0.1, and have all the modules imported. But it's not adding a single card into the layout.
I thought it would be difficult to debug such a big code you uploaded. But luckily my eye went on this line
#Override
public int getItemCount() {
return 0;
}
return 0; in adapter.
Your list size is always 0.
instead write this
#Override
public int getItemCount() {
return data.size();
}
EDIT-1:
You will also get null pointer exception here
viewholder.artist.setText(data.get(pos).getArtist());
Because you are not initializing the artist variable in ViewHolder class.
Edit-2
#Override
public int getItemCount() {
return 0;
}
you can remove this particular code from your adapter. Because overriding the methods of class that we don't use might sometimes result in errors that you can't even imagine.

row layout not set on on Main Activity Recycler View

I am just parse some data and display on my ListProperty Class. I am using RecyclerView and CardView as a row layout. Somehow all is working fine i don't see any error in verbose. But the Data and row layout dosent display in my main activity. Activity is showing blank. I am trying from hours but kind find the error. Please someone help
My MainActivity.xml
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin">
<android.support.v7.widget.RecyclerView
android:id="#+id/cardList"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
This is 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="match_parent">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:id="#+id/imageViewFront" />
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_marginLeft="100dp"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:text="New Text"
android:textColor="#0055CC"
android:id="#+id/textViewPropertyname" />
<TextView
android:layout_marginTop="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:textColor="#0055CC"
android:layout_columnWeight="1"
android:id="#+id/textViewPropertyDescription"/>
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
This is myAdapter.java
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
List<Bean> DataList;
public MyAdapter(List<Bean> List){
super();
DataList = List;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView propertyName;
public TextView propertyDesc;
public ImageView ImageFront;
public MyViewHolder(View v) {
super(v);
propertyName = (TextView) v.findViewById(R.id.textViewPropertyname);
propertyDesc = (TextView) v.findViewById(R.id.textViewPropertyDescription);
ImageFront = (ImageView) v.findViewById(R.id.imageViewFront);
}
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).
inflate(R.layout.list_card_view,parent,false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyAdapter.MyViewHolder holder, int position) {
Bean bean = DataList.get(position);
holder.propertyName.setText(bean.getPropertyName());
holder.propertyDesc.setText(bean.getPropertyDescription());
holder.ImageFront.setImageResource(R.drawable.agriculture);
}
#Override
public int getItemCount() {
return DataList.size();
}
}
And this is my MainActivity.java
public class ListProperty extends AppCompatActivity {
private RecyclerView mRecyclerView;
private MyAdapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
Bean bean;
AQuery aQuery;
JSONObject jsonObject;
List<Bean> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_property);
aQuery= new AQuery(getApplicationContext());
String URL = "http://192.168.0.107/propertyapp/service/simpleservice.php";
list = new ArrayList<Bean>();
mRecyclerView = (RecyclerView) findViewById(R.id.cardList);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new MyAdapter(list);
mRecyclerView.setAdapter(mAdapter);
aQuery.ajax(URL, JSONObject.class,new AjaxCallback<JSONObject>(){
#Override
public void callback(String url, JSONObject object, AjaxStatus status) {
try {
bean = new Bean();
list = new ArrayList<Bean>();
String string = object.getString("data");
JSONArray jsonArray = new JSONArray(string);
for (int i=0;i<jsonArray.length();i++) {
jsonObject = jsonArray.getJSONObject(i);
bean.setPropertyName("property_name");
bean.setPropertyDescription("property_desc");
list.add(bean);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}
Try to remove parent LinearLayout. Because you have CardView which is acting as list item.
Try this row.xml -
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:id="#+id/imageViewFront" />
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_marginLeft="100dp"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:text="New Text"
android:textColor="#0055CC"
android:id="#+id/textViewPropertyname" />
<TextView
android:layout_marginTop="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:textColor="#0055CC"
android:layout_columnWeight="1"
android:id="#+id/textViewPropertyDescription"/>
</LinearLayout>
</android.support.v7.widget.CardView>
Hope it will help :)
Just add notifyDataSetChanged() to your Activity as below:
aQuery.ajax(URL, JSONObject.class,new AjaxCallback<JSONObject>(){
#Override
public void callback(String url, JSONObject object, AjaxStatus status) {
try {
bean = new Bean();
list = new ArrayList<Bean>();
String string = object.getString("data");
JSONArray jsonArray = new JSONArray(string);
for (int i=0;i<jsonArray.length();i++) {
jsonObject = jsonArray.getJSONObject(i);
bean.setPropertyName("property_name");
bean.setPropertyDescription("property_desc");
list.add(bean);
}
//here notify your adapter
//is to Notify any registered observers that the data set has changed.
mAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Because on your callback you have created new instance of list
list = new ArrayList<Bean>();
then in fact, the new created list and DataList in your adapter are pointing to 2 difference objects => calling notifyDataSetChanged here won't work. Try writing method updateData on MyAdapter and call it from your callback method
public void updateData(List<Bean> List){
DataList = List;
notifyDataSetChanged();
}
On your callback:
aQuery.ajax(URL, JSONObject.class,new AjaxCallback<JSONObject>(){
#Override
public void callback(String url, JSONObject object, AjaxStatus status) {
try {
bean = new Bean();
list = new ArrayList<Bean>();
String string = object.getString("data");
JSONArray jsonArray = new JSONArray(string);
for (int i=0;i<jsonArray.length();i++) {
jsonObject = jsonArray.getJSONObject(i);
bean.setPropertyName("property_name");
bean.setPropertyDescription("property_desc");
list.add(bean);
}
// update data
mAdapter.updateData(list);
} catch (JSONException e) {
e.printStackTrace();
}
}
});

Categories

Resources