Hello so I created a simple app that uses cardview and recycler View to display images .
Now when I run the app only a blank app with the name of the app shows up
Here is the code
Main Activity File
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
List<listItem> item;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recycler_Container);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
myAdapter adapter = new myAdapter(dataFile.getListData());
recyclerView.setAdapter(adapter);
}}
Adapter File
public class myAdapter extends RecyclerView.Adapter<myAdapter.pageHolder> {
List<listItem> listData;
LayoutInflater inflater;
public myAdapter(List<listItem> listData) {
this.listData = listData;
}
public class pageHolder extends RecyclerView.ViewHolder{
ImageView image;
TextView text;
View container;
public pageHolder(View itemView) {
super(itemView);
image = (ImageView) itemView.findViewById(R.id.thumbnail);
text = (TextView) itemView.findViewById(R.id.card_text);
container = itemView.findViewById(R.id.layout_container);
}}
#Override
public myAdapter.pageHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card,parent,false);
return new pageHolder(view);
}
#Override
public void onBindViewHolder(myAdapter.pageHolder holder, int position) {
listItem item =listData.get(position);
holder.text.setText(item.getTitle());
holder.image.setImageResource(item.getIconId());
}
#Override
public int getItemCount() {
return listData.size();
}}
list Item File
public class listItem {
String title;
int iconId;
public listItem(int iconId, String title) {
this.iconId = iconId;
this.title = title;
}
public int getIconId() {
return iconId;
}
public void setIconId(int iconId) {
this.iconId = iconId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}}
data File
public class dataFile {
public static int icons[]={R.drawable.album9,R.drawable.album1,R.drawable.album3,R.drawable.album4,R.drawable.album5,R.drawable.album6,
R.drawable.album7,R.drawable.album8,R.drawable.album10,R.drawable.album11,R.drawable.album12,R.drawable.album13,R.drawable.album14,R.drawable.album15,
R.drawable.album16};
public static String title[] = {"Album"};
public static List<listItem> getListData(){
List<listItem> data = new ArrayList<>();
for(int i =0;i<icons.length;i++){
new listItem(icons[i],"ALBUM"+i);
}
return data;
}}
Main XML file
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.adi.customcardview.MainActivity">
<android.support.v7.widget.RecyclerView
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:padding="16dp"
android:id="#+id/recycler_Container"/></RelativeLayout>
Card Layout XML file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/layout_container"
app:cardCornerRadius="5dp"
app:cardBackgroundColor="#efdada"
app:cardElevation="5dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/thumbnail"
android:padding="12dp"
android:src="#drawable/album9"/>
<TextView
android:text="ALBUM NAME"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="55dp"
android:id="#+id/card_text"
android:textSize="18sp"
android:layout_alignParentTop="true"
android:layout_toEndOf="#+id/thumbnail"/>
</RelativeLayout></android.support.v7.widget.CardView></LinearLayout>
As I understand, in the getListData method you are not adding the listItem elements to the data List. So try to change the method as follows:
public static List<listItem> getListData(){
List<listItem> data = new ArrayList<>();
for(int i =0;i<icons.length;i++){
data.add(new listItem(icons[i],"ALBUM"+i));
}
return data;
}
Related
I have 2 CardViews and a RecyclerView but i am
unable to align them vertically
unable to slide them independently (both slide if I slide any one in a bugged workaround)
I tried a few workarounds as well as different tutorials like edmt Dev and CodingWithMitch as well as searched for similar problems on stackoverflow but the problem seems to persist. So how do I align both of the cardviews vertically while still being able to slide each of them independently and horizontally.
(Code works fine for single card view)
Main Activity:
public class MainActivity extends AppCompatActivity {
List<Articles> articlesData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
articlesData = new ArrayList<>();
//Repeats
articlesData.add(new Articles("10 Necessary Gadgets","Gadgets","Gadgets You Must Carry",R.drawable.bagchaincustom));
articlesData.add(new Articles("10 Benefits of Pre-Planning the Day","Self Improvement","Benefits of Planning in Advance",R.drawable.planner1custom));
LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL,false);
RecyclerView recyclerView = findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(layoutManager);
RecyclerViewAdapter adapter = new RecyclerViewAdapter(this, articlesData);
recyclerView.setAdapter(adapter);
}
Here is activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/recyclerview"
android:orientation="horizontal">
</androidx.recyclerview.widget.RecyclerView>
</androidx.constraintlayout.widget.ConstraintLayout>
Here is the RecyclerViewAdapter Class:
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int LAYOUT_ONE= 0;
private static final int LAYOUT_TWO= 1;
#Override
public int getItemViewType(int position)
{
if(position == LAYOUT_ONE){
return LAYOUT_TWO;
}
else {
return LAYOUT_ONE;
}
}
private static final String Tag = "RecyclerViewAdapter";
private Context mContext;
private List<Articles> mData;
public RecyclerViewAdapter(Context mContext, List<Articles> mData) {
this.mContext = mContext;
this.mData = mData;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater mInflater = LayoutInflater.from(mContext);
View view;
switch (viewType) {
case 0:
ViewHolder1 viewHolder1;
view = mInflater.inflate(R.layout.layout_listitem, parent, false);
return new ViewHolder1(view);
case 1:
ViewHolder2 viewHolder2;
view = mInflater.inflate(R.layout.layout_listitem2, parent, false);
return new ViewHolder2(view);
default:
return null;
}
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, final int position) {
switch (holder.getItemViewType()){
case 0:
ViewHolder1 viewHolder1 = (ViewHolder1)holder;
viewHolder1.tv_article_title.setText(mData.get(position).getTitle());
viewHolder1.img_article_thumbnail.setImageResource(mData.get(position).getThumbnail());
viewHolder1.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext, ArticlesActivity.class);
intent.putExtra("Title", mData.get(position).getTitle());
intent.putExtra("Description", mData.get(position).getDescription());
intent.putExtra("Thumbnail", mData.get(position).getThumbnail());
intent.putExtra("Category", mData.get(position).getCategory());
mContext.startActivity(intent);
}
});
break;
case 1:
ViewHolder2 viewHolder2 = (ViewHolder2)holder;
viewHolder2.tv_article_title2.setText(mData.get(position).getTitle());
viewHolder2.img_article_thumbnail2.setImageResource(mData.get(position).getThumbnail());
viewHolder2.cardView2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext, ArticlesActivity.class);
intent.putExtra("Title", mData.get(position).getTitle());
intent.putExtra("Description", mData.get(position).getDescription());
intent.putExtra("Thumbnail", mData.get(position).getThumbnail());
intent.putExtra("Category", mData.get(position).getCategory());
mContext.startActivity(intent);
}
});
break;
}
}
#Override
public int getItemCount() {
return mData.size();
}
public class ViewHolder1 extends RecyclerView.ViewHolder{
TextView tv_article_title;
ImageView img_article_thumbnail;
CardView cardView;
public ViewHolder1(#NonNull View itemView) {
super(itemView);
tv_article_title = (TextView) itemView.findViewById(R.id.article_title_id);
img_article_thumbnail = (ImageView) itemView.findViewById((R.id.article_image_id));
cardView = (CardView) itemView.findViewById(R.id.cardview_id);
}
}
public class ViewHolder2 extends RecyclerView.ViewHolder{
TextView tv_article_title2;
ImageView img_article_thumbnail2;
CardView cardView2;
public ViewHolder2(#NonNull View itemView) {
super(itemView);
tv_article_title2 = (TextView) itemView.findViewById(R.id.article_title_id2);
img_article_thumbnail2 = (ImageView) itemView.findViewById((R.id.article_image_id2));
cardView2 = (CardView) itemView.findViewById(R.id.cardview_id2);
}
}
}
Here is the Articles Class:
public class Articles {
private String Title;
private String Category;
private String Description;
private int Thumbnail;
public Articles(String title, String category, String description, int thumbnail) {
Title = title;
Category = category;
Description = description;
Thumbnail = thumbnail;
}
public String getTitle() {
return Title;
}
public String getCategory() {
return Category;
}
public String getDescription() {
return Description;
}
public int getThumbnail() {
return Thumbnail;
}
And here is the CardView -> layout_listitem Layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:card_view="http://schemas.android.com/tools"
android:layout_alignParentStart="true"
android:id="#+id/rview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:card_view="http://schemas.android.com/tools"
android:id="#+id/cardview_id"
android:layout_width="120dp"
android:layout_height="220dp"
android:clickable="true"
android:foreground="?android:attr/selectableItemBackground"
app:cardCornerRadius="0dp"
app:cardElevation="0dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
android:orientation="vertical">
<ImageView
android:id="#+id/article_image_id"
android:layout_width="match_parent"
android:layout_height="160dp"
android:background="#2d2d2d"
android:scaleType="centerCrop"></ImageView>
<TextView
android:id="#+id/article_title_id"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal"
android:gravity="center"
android:text="Article Name"
android:textSize="14sp">
</TextView>
</LinearLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
And here is the CardView -> layout_listitem2 Layout:
<?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:card_view="http://schemas.android.com/tools"
android:layout_alignParentStart="true"
android:id="#+id/rview2"
android:layout_below="#+id/rview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="300dp">
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:card_view="http://schemas.android.com/tools"
android:id="#+id/cardview_id2"
android:layout_below="#id/cardview_id"
android:layout_width="120dp"
android:layout_height="220dp"
android:clickable="true"
android:foreground="?android:attr/selectableItemBackground"
app:cardCornerRadius="0dp"
app:cardElevation="0dp">
<LinearLayout
android:layout_marginTop="250dp"
android:layout_alignParentBottom="true"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
android:orientation="vertical">
<ImageView
android:id="#+id/article_image_id2"
android:layout_width="match_parent"
android:layout_height="160dp"
android:background="#2d2d2d"
android:scaleType="centerCrop"></ImageView>
<TextView
android:id="#+id/article_title_id2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal"
android:gravity="center"
android:text="Article Name Sec"
android:textSize="14sp">
</TextView>
</LinearLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
ConstraintLayout is not a scrolling parent, so it will create problem if you add a long RecyclerView inside it.
So I made a few modifications to the above code and it has solved the both problems (Independent sliding and vertical alignment)
I have added another recyclerview in main_activity.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerview_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
</androidx.recyclerview.widget.RecyclerView>
<androidx.recyclerview.widget.RecyclerView
android:layout_below="#+id/recyclerview_id2"
android:layout_marginTop="10dp"
android:id="#+id/recyclerview_id2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:ignore="NotSibling">
</androidx.recyclerview.widget.RecyclerView>
</LinearLayout>
I have also created another Adapter for the new recyclerview, seperated classes for both viewholders as well as removed the switch statements and itemViewType from RecyclerViewAdapter and RecyclerViewAdapter2 class :
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view;
LayoutInflater mInflater = LayoutInflater.from(mContext);
view = mInflater.inflate(R.layout.layout_listitem2,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
holder.tv_article_title2.setText(mData.get(position).getTitle());
holder.img_article_thumbnail2.setImageResource(mData.get(position).getThumbnail());
holder.cardView2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext,ArticlesActivity.class);
intent.putExtra("Title",mData.get(position).getTitle());
intent.putExtra("Description",mData.get(position).getDescription());
intent.putExtra("Thumbnail",mData.get(position).getThumbnail());
intent.putExtra("Category",mData.get(position).getCategory());
mContext.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return mData.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder{
TextView tv_article_title2;
ImageView img_article_thumbnail2;
CardView cardView2;
public ViewHolder(#NonNull View itemView) {
super(itemView);
tv_article_title2 = (TextView) itemView.findViewById(R.id.article_title_id2);
img_article_thumbnail2 = (ImageView) itemView.findViewById((R.id.article_image_id2));
cardView2 = (CardView) itemView.findViewById(R.id.cardview_id2);
}
}
I also edited the main_acitivty class by adding the new recyclerview and layout manager at the end:
LinearLayoutManager layoutManager2 = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL,false);
RecyclerView recyclerView2 = findViewById(R.id.recyclerview_id2);
recyclerView2.setLayoutManager(layoutManager2);
RecyclerViewAdapter2 adapter2 = new RecyclerViewAdapter2(this, articlesData);
recyclerView2.setAdapter(adapter2);
Even though this workaround fixes both problems i was facing is there any other better/more refined way of doing this (eg by using single recyclerview) and where did i made the mistake in previous approach?
I am new with Android Studio, and I would like to try a listview with pictures on the left shown below. I managed to make such a list with a simple list item, but when I changed the simple item list with an ActivityList, it does not work anymore.
How can I change the ArrayList to combine imageviews with the names? I think it could be possible by using a new class which contains the imageview and name instead of strings.
Code:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView friendsListView = findViewById(R.id.friendListView);
final ArrayList<String> myFriends = new ArrayList<String>(asList("Mark","Jane","Sussy","Jan"));
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.activity_list_item
, myFriends);
friendsListView.setAdapter(arrayAdapter);
friendsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getApplicationContext(), "Hello " + myFriends.get(i), Toast.LENGTH_LONG).show();
}
});
}
}
You're right, you need to create a model class for your list item; this model class contains things that differ from item to item; for instance in your shared picture, a list item has a typical of a picture and a title; and so your model class.
Next, instead of having ArrayList<String>, use ArrayList<Item>; where Item is the model class
Third, you need to create a custom adapter that extends from ArrayAdapter<Item>; that is because you can't use the built-in list item layout "android.R.layout.activity_list_item", because it just offers you with a single string; and now you need to accompany a picture with it.
Below is a simple demo
Model class (Item.java)
class Item {
private int mPicture;
private String mTitle;
int getPicture() {
return mPicture;
}
Item(int picture, String title) {
mPicture = picture;
mTitle = title;
}
String getTitle() {
return mTitle;
}
}
List View Adapter (ListViewAdapter.java)
public class ListViewAdapter extends ArrayAdapter<Item> {
ListViewAdapter(#NonNull Context context, ArrayList<Item> items) {
super(context, 0, items);
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View listItem = convertView;
if (listItem == null) {
listItem = LayoutInflater.from(getContext()).inflate(R.layout.list_item, parent, false);
}
// Get the {#link Word} object located at this position in the list
Item currentItem = getItem(position);
ImageView picture = listItem.findViewById(R.id.IvPicture);
picture.setBackgroundResource(currentItem.getPicture());
TextView title = listItem.findViewById(R.id.tvTitle);
title.setText(currentItem.getTitle());
return listItem;
}
}
Activity class
public class MainActivity extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<Item> items = new ArrayList<>();
items.add(new Item(R.drawable.item1, "Item1"));
items.add(new Item(R.drawable.item2, "Item2"));
items.add(new Item(R.drawable.item3, "Item3"));
ListViewAdapter adapter = new ListViewAdapter(this, items);
ListView listView = findViewById(R.id.listView);
listView.setAdapter(adapter);
}
}
Activity Layout (activity_main.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:orientation="vertical">
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
</LinearLayout>
List item layout (list_item.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/rootView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="#+id/IvPicture"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/tvTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="item" />
</LinearLayout>
You have to have 3 images into res/drawable named item1, item2, and item3
Hope this satisfies your need.
activity_main.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: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=".MainActivity"
android:background="#color/grey_300"
>
<android.support.v7.widget.RecyclerView
android:id="#+id/my_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
/>
</RelativeLayout>
cards_layout.xml code:
<android.support.v7.widget.CardView
android:id="#+id/card_view"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardBackgroundColor="#color/color_white"
card_view:cardCornerRadius="10dp"
card_view:cardElevation="5dp"
card_view:cardUseCompatPadding="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<ImageView
android:id="#+id/imageView"
android:tag="image_tag"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_weight="1"
android:src="#drawable/ic_launcher"/>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:layout_weight="2"
android:orientation="vertical"
>
<TextView
android:id="#+id/textViewName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp"
android:text="Android Name"
android:textAppearance="?android:attr/textAppearanceLarge"/>
<TextView
android:id="#+id/textViewVersion"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp"
android:text="Android Version"
android:textAppearance="?android:attr/textAppearanceMedium"/>
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
menu_main.xml code:
<menu 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"
tools:context=".MainActivity">
<item android:id="#+id/add_item"
android:title="Add"
android:orderInCategory="100"
app:showAsAction="always"/>
</menu>
MainActivity.java
package com.journaldev.recyclerviewcardview;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private static RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
private static RecyclerView recyclerView;
private static ArrayList<DataModel> data;
static View.OnClickListener myOnClickListener;
private static ArrayList<Integer> removedItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myOnClickListener = new MyOnClickListener(this);
recyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
data = new ArrayList<DataModel>();
for (int i = 0; i < MyData.nameArray.length; i++) {
data.add(new DataModel(
MyData.nameArray[i],
MyData.versionArray[i],
MyData.id_[i],
MyData.drawableArray[i]
));
}
removedItems = new ArrayList<Integer>();
adapter = new CustomAdapter(data);
recyclerView.setAdapter(adapter);
}
private static class MyOnClickListener implements View.OnClickListener {
private final Context context;
private MyOnClickListener(Context context) {
this.context = context;
}
#Override
public void onClick(View v) {
removeItem(v);
}
private void removeItem(View v) {
int selectedItemPosition = recyclerView.getChildPosition(v);
RecyclerView.ViewHolder viewHolder
= recyclerView.findViewHolderForPosition(selectedItemPosition);
TextView textViewName
= (TextView) viewHolder.itemView.findViewById(R.id.textViewName);
String selectedName = (String) textViewName.getText();
int selectedItemId = -1;
for (int i = 0; i < MyData.nameArray.length; i++) {
if (selectedName.equals(MyData.nameArray[i])) {
selectedItemId = MyData.id_[i];
}
}
removedItems.add(selectedItemId);
data.remove(selectedItemPosition);
adapter.notifyItemRemoved(selectedItemPosition);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
if (item.getItemId() == R.id.add_item) {
//check if any items to add
if (removedItems.size() != 0) {
addRemovedItemToList();
} else {
Toast.makeText(this, "Nothing to add", Toast.LENGTH_SHORT).show();
}
}
return true;
}
private void addRemovedItemToList() {
int addItemAtListPosition = 3;
data.add(addItemAtListPosition, new DataModel(
MyData.nameArray[removedItems.get(0)],
MyData.versionArray[removedItems.get(0)],
MyData.id_[removedItems.get(0)],
MyData.drawableArray[removedItems.get(0)]
));
adapter.notifyItemInserted(addItemAtListPosition);
removedItems.remove(0);
}
}
CustomAdapter.java
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 java.util.ArrayList;
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> {
private ArrayList<DataModel> dataSet;
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView textViewName;
TextView textViewVersion;
ImageView imageViewIcon;
public MyViewHolder(View itemView) {
super(itemView);
this.textViewName = (TextView) itemView.findViewById(R.id.textViewName);
this.textViewVersion = (TextView) itemView.findViewById(R.id.textViewVersion);
this.imageViewIcon = (ImageView) itemView.findViewById(R.id.imageView);
}
}
public CustomAdapter(ArrayList<DataModel> data) {
this.dataSet = data;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.cards_layout, parent, false);
view.setOnClickListener(MainActivity.myOnClickListener);
MyViewHolder myViewHolder = new MyViewHolder(view);
return myViewHolder;
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int listPosition) {
TextView textViewName = holder.textViewName;
TextView textViewVersion = holder.textViewVersion;
ImageView imageView = holder.imageViewIcon;
textViewName.setText(dataSet.get(listPosition).getName());
textViewVersion.setText(dataSet.get(listPosition).getVersion());
imageView.setImageResource(dataSet.get(listPosition).getImage());
}
#Override
public int getItemCount() {
return dataSet.size();
}
}
DataModel.java
public class DataModel {
String name;
String version;
int id_;
int image;
public DataModel(String name, String version, int id_, int image) {
this.name = name;
this.version = version;
this.id_ = id_;
this.image=image;
}
public String getName() {
return name;
}
public String getVersion() {
return version;
}
public int getImage() {
return image;
}
public int getId() {
return id_;
}
}
MyData.java
public class MyData {
static String[] nameArray = {"Cupcake", "Donut", "Eclair", "Froyo", "Gingerbread", "Honeycomb", "Ice Cream Sandwich","JellyBean", "Kitkat", "Lollipop", "Marshmallow"};
static String[] versionArray = {"1.5", "1.6", "2.0-2.1", "2.2-2.2.3", "2.3-2.3.7", "3.0-3.2.6", "4.0-4.0.4", "4.1-4.3.1", "4.4-4.4.4", "5.0-5.1.1","6.0-6.0.1"};
static Integer[] drawableArray = {R.drawable.cupcake, R.drawable.donut, R.drawable.eclair,
R.drawable.froyo, R.drawable.gingerbread, R.drawable.honeycomb, R.drawable.ics,
R.drawable.jellybean, R.drawable.kitkat, R.drawable.lollipop,R.drawable.marsh};
static Integer[] id_ = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
}
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView friendsListView = findViewById(R.id.friendListView);
final ArrayList<Item> items = new ArrayList<>();
items.add(new Item(R.drawable.abc, "Item1"));
items.add(new Item(R.drawable.def, "Item2"));
ListViewAdapter adapter = new ListViewAdapter(this, items);
ListView.setAdapter(adapter);
friendsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getApplicationContext(), "Hello " + items.get(i), Toast.LENGTH_LONG).show();
}
});
}
}
I have created RecyclerView and showing data from JSON.
Issue I'm facing is, while Toast data is showing correctly, but in RecyclerView same data is not appear.
Here is code:
public class MainActivity extends AppCompatActivity {
private static final int NUM_LIST_ITEMS = 100;
private static final String TOKEN =
"71cf2d3dec294394e267fbb0bf28916f4198f8d6";
private CuloAdapter culoAdapter;
List<Hotel> lh = new ArrayList<>();
RecyclerView recyclerView;
#Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(newBase);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.rv_tiketapi);
LinearLayoutManager layout = new LinearLayoutManager(this);
layout.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layout);
CuloAdapter ar = new CuloAdapter(lh);
recyclerView.setAdapter(ar);
loadHotelLocation();
}
private void loadHotelLocation() {
final search apiService = ApiService.getService(search.class);
retrofit2.Call<SingleResult<Hotel>> call = apiService.findHotel(TOKEN,
"json");
call.enqueue(new Callback<SingleResult<Hotel>>() {
#Override
public void onResponse(retrofit2.Call<SingleResult<Hotel>> call,
Response<SingleResult<Hotel>> response) {
if (response.body().getDiagnostic().isSuccess()) {
//SingleResult.ResultList list =
response.body().getResults();
List<Hotel> mHotels = (List<Hotel>)
response.body().getResults().getResult();
lh.addAll(mHotels);
Toast.makeText(getApplicationContext(), "OK" +lh,
Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(retrofit2.Call<SingleResult<Hotel>> call,
Throwable t) {
}
});
}
RecyclerView Adapter :
public class CuloAdapter extends
RecyclerView.Adapter<CuloAdapter.ViewHolder> {
public CuloAdapter(List<Hotel> lh) {
this.items = lh;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView txtTitle;
public TextView txtSubTitle;
public ImageView imgIcon;
public ViewHolder(final View container) {
super(container);
txtTitle = (TextView) container.findViewById(R.id.airportName);
txtSubTitle = (TextView) container.findViewById(R.id.airportCode);
}
}
private List<Hotel> items;
public CuloAdapter(final Activity activity, List<Hotel> items) {
this.items = items;
}
#Override
public int getItemCount() {
return items.size();
}
#Override
public void onBindViewHolder(CuloAdapter.ViewHolder holder, int position) {
Hotel item = items.get(position);
holder.txtTitle.setText(item.getLabel());
holder.txtSubTitle.setText(item.getId());
}
#Override
public CuloAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int
viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_flight, parent, false);
return new ViewHolder(v);
}
}
MainActivity 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"
android:orientation="vertical"
tools:context="com.example.admin.exampletiketapi.MainActivity">
<EditText
android:id="#+id/et_find"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAlignment="center" />
<android.support.v7.widget.RecyclerView
android:id="#+id/rv_tiketapi"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
Item List XML :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/airportsLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="10dp">
<TextView
android:id="#+id/airportName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:text="Soekarno Hatta" />
<TextView
android:id="#+id/airportCode"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:text="20" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginTop="5dp"
android:background="#DDD"
android:visibility="visible" />
</LinearLayout>
In your code you are trying to set adapter before loading data.
CuloAdapter ar = new CuloAdapter(lh);
recyclerView.setAdapter(ar);
loadHotelLocation();
What i found is You are getting data in loadHotelLocation(), but trying to set adpter before that,
Call notifyDatasetChanged after lh.addAll(mHotels). And check for null's else you are heading for crash in case search results are zero/null
i have array of objects carts containing itemname and price. Array is coming correctly from sqlite database. i want to display it in a listview. But in a listview it is only showing the package name not itemname and price. I think problem is in this line "ListAdapter buckysAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, carts); "of Main2Activity.java
Below is my code please guide me.It is very important for me
Main2Activity.java
public class Main2Activity extends Activity {
MyDBHandler dbHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Intent intent = getIntent();
final int position = intent.getIntExtra("history",1);
Log.i("positin","position = "+String.valueOf(position));
dbHandler = new MyDBHandler(this,null,null,6);
Cart[] carts = dbHandler.databaseToArray(position);
for (Cart c : carts)
Log.i("jhnbvb1","item1 = "+c.getItemname()+" price1 = "+c.getPrice());
ListAdapter buckysAdapter = new ArrayAdapter<Cart>(this, android.R.layout.simple_list_item_1, carts);
ListView buckysListView = (ListView) findViewById(R.id.buckysListView2);
buckysListView.setAdapter(buckysAdapter);
}}
CustomAdapter2.java
public class CustomAdapter2 extends ArrayAdapter<Cart> {
public CustomAdapter2(Context context, Cart[] foods) {
super(context, R.layout.custom_row2 ,foods);
}
#Override
public Cart getItem(int position) {
return super.getItem(position);
}
#Override
public int getPosition(Cart item) {
return super.getPosition(item);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater buckysInflater = LayoutInflater.from(getContext());
View customView = buckysInflater.inflate(R.layout.custom_row2, parent, false);
Cart singleFoodItem = getItem(position);
String name = singleFoodItem.getItemname();
String price = singleFoodItem.getPrice();
Log.i("rtyiykj","item2 = "+name+" price2 = "+price);
TextView buckysText = (TextView) customView.findViewById(R.id.buckysText2);
TextView buckysText1 = (TextView) customView.findViewById(R.id.buckysText3);
buckysText.setText(name);
buckysText1.setText(price);
return customView;
}}
custom_row2.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="match_parent">
<TextView
android:layout_width="200dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/buckysText2"
android:layout_margin="5dp" />
<TextView
android:layout_width="200dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/buckysText3"
android:layout_margin="5dp" />
activity_main2.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" tools:context=".Main2Activity">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/buckysListView2"></ListView>
cart.java
public class Cart {
private String itemname,price;
public Cart(String itemname,String price) {
this.setItemname(itemname);
this.setPrice(price);
}
public Cart() {}
public void setItemname(String itemname) {
this.itemname = itemname;
}
public void setPrice(String price) {
this.price = price;
}
public String getItemname() {
return itemname;
}
public String getPrice() {
return price;
}}
You use standard ArrayAdapter instead of that one created by you. It should be
CustomAdapter2<Cart> buckysAdapter = new CustomAdapter2<Cart>(this, carts);
And array adapter itself should be modified:
public class CustomAdapter2 extends ArrayAdapter<Cart> {
private final List<Object> foods;
public CustomAdapter2(Context context, List<Cart> foods) {
super(context, 0);
this.foods = foods;
}
#Override
public int getCount() {
return foods.size();
}
#Override
public Cart getItem(int position) {
return foods.get(position);
}
//your getView
}
I want to make a ListView inside a RecyclerView that should display some data in a list form. I currently have a basic Adapter and RecyclerView with no ListView inside of it, so can someone tell me how to modify my code to include a listview inside the RecyclerView?
Adapter:
public class RVAdapter extends RecyclerView.Adapter<RVAdapter.AdapterViewHolder> {
public static class AdapterViewHolder extends RecyclerView.ViewHolder {
TextView title;
TextView summary;
AdapterViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.recycler_list_title);
summary = (TextView) itemView.findViewById(R.id.recycler_list_summary);
}
}
List<Items> items;
public RVAdapter(List<Items> items){
this.items = items;
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
#Override
public AdapterViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_recycler, viewGroup, false);
AdapterViewHolder pvh = new AdapterViewHolder(v);
return pvh;
}
#Override
public void onBindViewHolder(AdapterViewHolder adapterViewHolder, int i) {
adapterViewHolder.title.setText(item.get(i).title);
adapterViewHolder.summary.setText(item.get(i).summary);
}
#Override
public int getItemCount() {
return item.size();
}
}
Items:
public class Items {
String title;
String summary;
public Items(String title, String summary) {
this.title = title;
this.summary = summary;
}
}
Layout:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:scrollbars="vertical"
android:layout_marginTop="0dp" />
</LinearLayout>
list_recycler:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:paddingRight="?android:attr/scrollbarSize">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:layout_marginEnd="6dp"
android:layout_marginTop="6dp"
android:layout_marginBottom="6dp">
<TextView
android:id="#+id/recycler_list_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/textColor"
android:textSize="16sp"
android:layout_alignParentLeft="true"/>
<TextView
android:id="#+id/recycler_list_summary"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/textColorSub"
android:textSize="14sp"
android:layout_alignParentRight="true" />
</RelativeLayout>
</LinearLayout>
How I'm creating the ListView:
private List item;
private RecyclerView rv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
rv = (RecyclerView) ((Activity) MainActivity.context).findViewById(R.id.recycler);
rv.setHasFixedSize(true);
rv.setLayoutManager(new LinearLayoutManager(this));
initializeData();
initializeAdapter();
}
private void initializeData(){
item = new ArrayList<>();
item.add(new Items("Title", "Summary"));
}
private void initializeAdapter() {
RVAdapter adapter = new RVAdapter(item);
rv.setAdapter(adapter);
}
}
ListView listview = (ListView) findViewById(R.id.listview);
ListView parentListView=(ListView)listview.getParent();
you can get parent listView by this way