How to make a specific item respond to click in recyclerView - android

i have a news app which i want when the news item (cardview) is clicked on, it should open another activity. unfortunately, nothing happens when the news item in the card view is clicked on, only when the background (recycler layout) is clicked on then the activity comes up.
i want when the news item on the cardview is clicked on, an activity should open and not when the background is clicked.
newsAdapter.java
package wami.ikechukwu.kanu;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
public class newsAdapter extends RecyclerView.Adapter<newsAdapter.viewHolder> {
private ArrayList<dataModel> mDataModel;
private Context context;
private onclicklistener clicklistener;
public newsAdapter(Context context, ArrayList<dataModel> mDataModel, onclicklistener clicklistener) {
this.context = context;
this.mDataModel = mDataModel;
this.clicklistener = clicklistener;
}
#NonNull
#Override
public viewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view =
LayoutInflater.from(context).inflate(R.layout.recyclerview_layout,
viewGroup, false);
return new viewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final newsAdapter.viewHolder viewHolder, final int i) {
dataModel dataModel = mDataModel.get(i);
viewHolder.mTextView.setText(dataModel.getTitle());
viewHolder.mTextDescrip.setText(dataModel.getDescrip());
Glide.with(context).load(dataModel.getImage()).into(viewHolder.mImageView);
}
#Override
public int getItemCount() {
return mDataModel.size();
}
public interface onclicklistener {
void onItemClick(int position);
}
public class viewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView mTextView;
public ImageView mImageView;
public TextView mTextDescrip;
public viewHolder(#NonNull View itemView) {
super(itemView);
mTextView = itemView.findViewById(R.id.layout_text);
mImageView = itemView.findViewById(R.id.layout_image);
mTextDescrip = itemView.findViewById(R.id.layout_descrip);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int adapterposition = getAdapterPosition();
clicklistener.onItemClick(adapterposition);
}
}
}
MainActivity.java
package wami.ikechukwu.kanu;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import dmax.dialog.SpotsDialog;
public class MainActivity extends AppCompatActivity implements newsAdapter.onclicklistener {
private final String KEY_AUTHOR = "author";
private final String KEY_TITLE = "title";
private final String KEY_DESCRIPTION = "description";
private final String KEY_URL = "url";
private final String KEY_URL_TO_IMAGE = "urlToImage";
private final String KEY_PUBLISHED_AT = "publishedAt";
//this string is appended to the url
String urlLink = "buhari";
ArrayList<dataModel> list;
private RecyclerView recyclerView;
private newsAdapter mAdapter;
private RecyclerView.LayoutManager mLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_main);
list = new ArrayList<>();
recyclerView = findViewById(R.id.recyclerView);
mAdapter = new newsAdapter(getApplicationContext(), list, this);
mLayout = new LinearLayoutManager(this);
recyclerView.setLayoutManager(mLayout);
recyclerView.setAdapter(mAdapter);
jsonParser();
}
private void jsonParser() {
final AlertDialog progressDialog = new SpotsDialog(this, R.style.customProgressDialog);
progressDialog.show();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, "https://newsapi.org/v2/everything?q=" + urlLink + "&language=en&sortBy=publishedAt&pageSize=100&apiKey=655446a36e784e79b2b62adcad45be09", null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("articles");
//Using a for loop to get the object (data) in the JSON
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
dataModel dataModel = new dataModel();
dataModel.setTitle(jsonObject.getString(KEY_TITLE));
dataModel.setImage(jsonObject.getString(KEY_URL_TO_IMAGE));
dataModel.setDescrip(jsonObject.getString(KEY_DESCRIPTION));
list.add(dataModel);
}
} catch (JSONException e) {
e.printStackTrace();
}
mAdapter.notifyDataSetChanged();
progressDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", error.toString());
progressDialog.dismiss();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonObjectRequest);
}
#Override
public void onItemClick(int position) {
Toast.makeText(this, "it worked " + position, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(this, news_detail.class);
startActivity(intent);
}
}
recyclerview_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
android:id="#+id/recyclerviewlayout"
android:layout_width="match_parent"
android:layout_height="250dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="10dp"
android:layout_marginRight="5dp"
android:clickable="true"
android:focusable="true"
app:cardCornerRadius="5dp"
app:cardElevation="10dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="250dp"
android:orientation="vertical">
<TextView
android:id="#+id/layout_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FFFF"
android:ellipsize="end"
android:maxLines="1"
android:padding="5dp"
android:textColor="#F000"
android:textSize="17sp"
android:textStyle="bold" />
<ImageView
android:id="#+id/layout_image"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:contentDescription="#string/Recyclerview_ImageContent"
android:scaleType="centerCrop" />
<TextView
android:id="#+id/layout_descrip"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FFFF"
android:ellipsize="end"
android:maxLines="3"
android:padding="5dp"
android:textColor="#F000"
android:textSize="15sp" />
<View
android:layout_width="match_parent"
android:layout_height="2dp"
android:background="#color/colorPrimaryDark" />
</LinearLayout>
</android.support.v7.widget.CardView>
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">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical">
</android.support.v7.widget.RecyclerView>

In order to set onclick listener in recycler view, you have to follow as below
inner class ViewHolderItem(itemView: View) : RecyclerView.ViewHolder(itemView) {
init {
itemView.setOnClickListener {
clicklistener.onItemClick(adapterposition)
}
}
}
OnclickListener will work in Init block

I think should add setOnClickListener method in an onBindViewHolder
And in that you should call another activity with passing your parameter.
Example :- (in onBindViewHolder)
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// call activity.
Intent intent = new Intent(activity, anotherActivityname.class);
// For passing values
intent.putExtra(key,value);
startActivity(intent);
}
});

You have to modify your viewHolder in newsAdapter like following.
public class viewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView mTextView;
public ImageView mImageView;
public TextView mTextDescrip;
public CardView yourCardView;
public viewHolder(#NonNull View itemView) {
super(itemView);
mTextView = itemView.findViewById(R.id.layout_text);
mImageView = itemView.findViewById(R.id.layout_image);
mTextDescrip = itemView.findViewById(R.id.layout_descrip);
yourCardView= itemView.findViewById(R.id.recyclerviewlayout);
// here you set on click listerner to your cardview.
yourCardView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int adapterposition = getAdapterPosition();
clicklistener.onItemClick(adapterposition);
}
}
Hope it helps you.

How to make a specific item respond to click in recyclerView?
So for this make your card view clickable false and make your new item(View inside cardview) clickable true:
<Cardview..
android:clickable="false">
...............
......
<View..
android:clickable="true"/>
</Cardview>

Related

ViewPager2 Adapter is being called Twice

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

RecylerView does not list items in order when added dynamicly after 3rd item added

I have a button that says ADD ITEM.
Below there is a RECYCLERVIEW.
When you click on ADD ITEM it adds an EDITVIEW to the recycler view. You type text in it, and then click on ADD ITEM again and it adds another EDITVIEW to the recyler view.
Everything is in the right order.
When you click on ADD ITEM for the 4th time, instead of adding at the 4th position, it adds at the 1st position and moves the previous 3 items down 1.
What could be causing this?
Main Activity
package com.app.bowling.animalsrecycler;
import android.app.Activity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import java.util.ArrayList;
import static java.sql.Types.NULL;
public class MainActivity extends Activity implements RemoveClickListner{
private RecyclerView mRecyclerView;
private RecyclerAdapter mRecyclerAdapter;
private RecyclerView.LayoutManager mLayoutManager;
Button btnAddItem;
ArrayList<RecyclerData> myList = new ArrayList<>();
EditText etTitle;
String title = "";
ImageView crossImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerAdapter = new RecyclerAdapter(myList,this);
mRecyclerView.setLayoutManager(new GridLayoutManager(this,2));
mRecyclerView.setAdapter(mRecyclerAdapter);
etTitle = (EditText) findViewById(R.id.etTitle);
if (mRecyclerAdapter.getItemCount() == 0 || mRecyclerAdapter.getItemCount() == NULL){
Toast.makeText(getApplicationContext(),"ZERO ITEMS LISTED",Toast.LENGTH_SHORT).show();
}
btnAddItem = (Button) findViewById(R.id.btnAddItem);
btnAddItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
title = etTitle.getText().toString();
// if (title.matches("")) {
// Toast.makeText(v.getContext(), "You did not enter a Title", Toast.LENGTH_SHORT).show();
// return;
// }
RecyclerData mLog = new RecyclerData();
// mLog.setTitle(title);
myList.add(mLog);
mRecyclerAdapter.notifyData(myList);
etTitle.setText("");
if (mRecyclerAdapter.getItemCount() > 0) {
Toast.makeText(v.getContext(), mRecyclerAdapter.getItemCount() + " Items Displayed", Toast.LENGTH_SHORT).show();
return;
}
}
});
}
#Override
public void OnRemoveClick(int index) {
myList.remove(index);
mRecyclerAdapter.notifyData(myList);
}
}
RecyclerAdapter
package com.app.bowling.animalsrecycler;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.RecyclerItemViewHolder> {
private ArrayList<RecyclerData> myList;
int mLastPosition = 0;
private RemoveClickListner mListner;
public RecyclerAdapter(ArrayList<RecyclerData> myList,RemoveClickListner listner) {
this.myList = myList;
mListner=listner;
}
public RecyclerItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_item, parent, false);
RecyclerItemViewHolder holder = new RecyclerItemViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(RecyclerItemViewHolder holder, final int position) {
Log.d("onBindViewHolder ", myList.size() + "");
mLastPosition = position;
holder.crossImage.setImageResource(R.drawable.ic_add_circle_black_24dp);
holder.etTitleTextView.setHint("Enter Player " + (position + 1));
holder.etTitleTextView.requestFocus();
}
#Override
public int getItemCount() {
return(null != myList?myList.size():0);
}
public void notifyData(ArrayList<RecyclerData> myList) {
Log.d("notifyData ", myList.size() + "");
this.myList = myList;
notifyDataSetChanged();
}
public class RecyclerItemViewHolder extends RecyclerView.ViewHolder {
private final TextView etTitleTextView;
private ConstraintLayout mainLayout;
public ImageView crossImage;
public RecyclerItemViewHolder(final View parent) {
super(parent);
etTitleTextView = parent.findViewById(R.id.txtTitle);
etTitleTextView.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
myList.get(getAdapterPosition()).setTitle(etTitleTextView.getText().toString());
}
#Override
public void afterTextChanged(Editable s) {
}
});
crossImage = (ImageView) parent.findViewById(R.id.crossImage);
mainLayout = (ConstraintLayout) parent.findViewById(R.id.mainLayout);
mainLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(itemView.getContext(), "Position:" + Integer.toString(getPosition()), Toast.LENGTH_SHORT).show();
}
});
crossImage.setOnClickListener(new AdapterView.OnClickListener() {
#Override
public void onClick(View view) {
mListner.OnRemoveClick(getAdapterPosition()
);
}
});
}
}
RecyclerData
package com.app.bowling.animalsrecycler;
import android.support.v7.widget.RecyclerView;
import android.widget.ImageView;
public class RecyclerData {
String title;
RecyclerView data;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public void setCrossImage(ImageView crossImage){
setCrossImage(crossImage);
}
}
RemoveClickLstner
package com.app.bowling.animalsrecycler;
public interface RemoveClickListner {
void OnRemoveClick(int index);
}
Activity_Main
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:padding="16dp"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Title"
android:id="#+id/etTitle" />
<Button
android:id="#+id/btnAddItem"
android:text="Add Item"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#dbfffe" />
</LinearLayout>
RecyclerView_Item
<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:orientation="horizontal"
android:layout_width="match_parent"
android:layout_margin="8dp"
android:id="#+id/cardview"
android:layout_height="112dp">
<android.support.constraint.ConstraintLayout
android:id="#+id/mainLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<EditText
android:id="#+id/txtTitle"
android:maxLines="1"
android:inputType="text"
android:maxLength="15"
android:layout_width="273dp"
android:layout_height="56dp"
android:layout_marginEnd="122dp"
android:layout_marginBottom="56dp"
android:padding="12dp"
android:textColor="#android:color/black"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:layout_conversion_absoluteHeight="0dp"
tools:layout_conversion_absoluteWidth="0dp"
tools:layout_conversion_wrapHeight="0"
tools:layout_conversion_wrapWidth="0" />
<ImageView
android:id="#+id/crossImage"
android:layout_width="136dp"
android:layout_height="112dp"
android:layout_marginStart="273dp"
android:background="#drawable/ic_add_circle_black_24dp"
android:paddingLeft="10dp"
android:visibility="visible"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:layout_conversion_absoluteHeight="0dp"
tools:layout_conversion_absoluteWidth="0dp"
tools:layout_conversion_wrapHeight="0"
tools:layout_conversion_wrapWidth="0" />
</android.support.constraint.ConstraintLayout>
</LinearLayout>
Just try to replace your below snippet
myList.add(mLog);
mRecyclerAdapter.notifyData(myList);
etTitle.setText("");
Add this:
myList.add(mLog);
mRecyclerAdapter.addAll(myList);
mRecyclerAdapter.notifyDataSetChanged();
etTitle.setText("");
I would like to see your layout activity_main and recycler_view item because I have tried implementing your code with few twist and the code is working well please check the code below
https://github.com/muchbeer/StackOverflowRecyclerView
Please find the below Screen Shot
Kindy let me if this was your intended application

Expandable layout Expands upwards instead of downwards

When i try to put my Expandable layout to the bottom of my cardview using
android:layout_gravity="bottom" it goes to the bottom but expands upwards
After clicking the relative layout "button"
I am getting data from arraylist passing it to the recyclerview and cardview
i don't know if it's because of the Adapter animation settings or just fomr the xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:animateLayoutChanges="true"
android:orientation="vertical">
<android.support.v7.widget.CardView
android:layout_gravity="top"
android:id="#+id/cardview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginEnd="8dp"
android:layout_marginBottom="551dp"
android:animateLayoutChanges="true"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<LinearLayout
android:id="#+id/holderimg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:layout_marginBottom="15dp"
android:orientation="horizontal">
<ImageView
android:id="#+id/imageView5"
android:layout_width="68dp"
android:layout_height="62dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="10dp"
app:srcCompat="#drawable/s1960678" />
<TextView
android:id="#+id/nameArray"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="10dp"
android:fontFamily="serif"
android:includeFontPadding="false"
android:text="TextView"
android:textSize="14sp"
android:textStyle="bold" />
<RelativeLayout
android:id="#+id/button"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_alignParentRight="true"
android:layout_gravity="right"
android:layout_marginTop="30dp"
android:layout_marginRight="10dp"
android:background="#drawable/ic_arrow_drop_down_black_24dp"
android:foregroundGravity="right"
android:gravity="right|center_horizontal"
android:orientation="vertical">
<View
android:id="#+id/view2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true" />
</RelativeLayout>
</LinearLayout>
</LinearLayout>
<com.github.aakira.expandablelayout.ExpandableLinearLayout
android:id="#+id/expandableLayout"
android:layout_width="match_parent"
android:layout_height="72dp"
android:layout_alignParentBottom="true"
android:layout_gravity="bottom"
android:foregroundGravity="bottom"
android:gravity="top"
android:orientation="vertical"
app:ael_duration="400"
app:ael_expanded="false">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<Button
android:id="#+id/button3"
android:layout_width="199dp"
android:layout_height="wrap_content"
android:text="Button"
tools:text="Download .PDF" />
<Button
android:id="#+id/button5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button"
tools:text="View PDF" />
</LinearLayout>
</com.github.aakira.expandablelayout.ExpandableLinearLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>
and here's the activity it gets data from , it's xml has only recyclerview
package com.example.imc.PDF;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.example.imc.MainAdapter;
import com.example.imc.MySingleton;
import com.example.imc.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class Resultsdwldview extends AppCompatActivity {
public RequestQueue requestQueue;
TextView MedicalText,PhoneText,AddressText,EmailText,result,resultArray;
EditText id;
Button getidbtn;
List<ArrayList<String>> Tests = new ArrayList<>();
ArrayList<String> urlArray = new ArrayList<String>();
ArrayList<String> nameArray = new ArrayList<String>();
ArrayList<String> IdfromjsonArray = new ArrayList<String>();
ArrayList<String> Patient_ID_Array = new ArrayList<String>();
RecyclerView mRecyclerView;
RecyclerView.LayoutManager mLayoutManager;
RecyclerView.Adapter mAdapter;
WebView webView;
String PDFurl;
String idvalue;
String url = "https://docs.google.com/viewer?url=http://www.adobe.com/devnet/acrobat/pdfs/pdf_open_parameters.pdf";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_resultsdwldview);
MedicalText = findViewById(R.id.MedicalText);
PhoneText = findViewById(R.id.PhoneText);
AddressText = findViewById(R.id.AddressText);
EmailText = findViewById(R.id.EmailText);
// webView = findViewById(R.id.webview); //WEBVIEW
// webView.requestFocus();
// webView.getSettings().setJavaScriptEnabled(true);
// webView.loadUrl(url);
mRecyclerView = findViewById(R.id.recyvlerView);
// id = findViewById(R.id.getid);
// getidbtn =(Button) findViewById(R.id.send);
mLayoutManager = new LinearLayoutManager(this);
jsonParse();
/*
getidbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//idvalue = id.getEditableText().toString();
jsonParse();
}
});*/
}
public void jsonParse() {
String URL="http://ashaaban-001-site1.btempurl.com/api/patients/"+4;
//String URL="http://ashaaban-001-site1.btempurl.com/api/patients/"+idvalue;
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, URL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("Tests");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject arraydata = jsonArray.getJSONObject(i);
// Tests.add(jsonObject.getString(String.valueOf(i)));
String urlName = arraydata.getString("urlName");
String Name =arraydata.getString("Name");
String Idfromjson =arraydata.getString("Id");
String P_ID_Array =arraydata.getString("patients_Id");
urlArray.add(urlName);
nameArray.add(Name);
IdfromjsonArray.add(Idfromjson);
Patient_ID_Array.add(P_ID_Array);
Tests.add(urlArray);
Tests.add(nameArray);
Tests.add(IdfromjsonArray);
Tests.add(Patient_ID_Array);
// resultArray.append("urlName = " +urlName+" \n\n Name"+Name);
}
//resultArray.append(Tests+" , \n ");
// mRecyclerView.setHasFixedSize(true);
} catch (JSONException e) {
e.printStackTrace();
}
try {
Integer P_MedicalNumber = response.getInt("MedicalNumber");
Integer P_id = response.getInt("Id");
String P_Username = response.getString("UserName");
Integer P_PhoneNumber = response.getInt("phoneNumber");
String P_Address = response.getString("Address");
String P_Email = response.getString("Email");
//result.append("Medical Number : "+P_MedicalNumber+" \n id :"+P_id+"UserName"+P_Username);
} catch (JSONException e) {
e.printStackTrace();
}
mAdapter = new MainAdapter(Tests,nameArray);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setAdapter(mAdapter);
mAdapter.notifyItemRangeInserted(0, Tests.size());
// webView.loadUrl(PDFurl);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),"error",Toast.LENGTH_SHORT).show();
}
});
// requestQueue.add(request);
MySingleton.getInstance(Resultsdwldview.this).addToReqeustQueue(jsonObjectRequest);
}
}
Adapter
package com.example.imc;
import android.animation.ObjectAnimator;
import android.content.ClipData;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.github.aakira.expandablelayout.ExpandableLayout;
import com.github.aakira.expandablelayout.ExpandableLayoutListenerAdapter;
import com.github.aakira.expandablelayout.ExpandableLinearLayout;
import com.github.aakira.expandablelayout.Utils;
import java.util.ArrayList;
import java.util.List;
public class MainAdapter extends RecyclerView.Adapter<MainAdapter.ViewHolder> {
List<ArrayList<String>> Tests;
ArrayList<String> urlArray;
ArrayList<String> nameArray;
ArrayList<String> IdfromjsonArray ;
ArrayList<String> Patient_ID_Array;
SparseBooleanArray expandState =new SparseBooleanArray();
public MainAdapter(List<ArrayList<String>> tests, ArrayList<String> urlArray, ArrayList<String> nameArray,
ArrayList<String> idfromjsonArray, ArrayList<String> patient_ID_Array) {
Tests = tests;
this.urlArray = urlArray;
this.nameArray = nameArray;
IdfromjsonArray = idfromjsonArray;
Patient_ID_Array = patient_ID_Array;
}
public MainAdapter(List<ArrayList<String>> tests, ArrayList<String> nameArray) {
Tests = tests;
this.nameArray = nameArray;
}
#NonNull
#Override
//Initialize the viewholder
public MainAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row,viewGroup,false);
return new ViewHolder(view);
}
/***************////////////////onBind Holds values to pass it to the viewholder///////////////////*******************
/***************////////////////
// This method is called for each ViewHolder to
// bind it to the adapter
// . This is where we will// pass our data to our ViewHolder///////////////////*******************
#Override
public void onBindViewHolder(#NonNull final MainAdapter.ViewHolder holder, final int i) {
// holder.URLName.setText( urlArray.get(i));
holder.mFullname.setText( nameArray.get(i));
holder.expandableLayout.setInRecyclerView(true);
holder.expandableLayout.setExpanded(expandState.get(i));
holder.expandableLayout.setListener(new ExpandableLayoutListenerAdapter() {
#Override
public void onPreOpen() {
changeRotate(holder.button,180f,0f).start();
expandState.put(i,true);
}
#Override
public void onPreClose() {
changeRotate(holder.button,0f,180f).start();
expandState.put(i,false);
}
});
holder.button.setRotation(expandState.get(i)?0f:180f);
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Expandable child item
holder.expandableLayout.toggle();
}
});
}
private ObjectAnimator changeRotate(RelativeLayout button, float to, float from) {
ObjectAnimator animator = ObjectAnimator.ofFloat(button,"rotation",from,to);
animator.setDuration(200);
animator.setInterpolator(Utils.createInterpolator(Utils.LINEAR_INTERPOLATOR));
return animator;
}
#Override
public int getItemCount() {
return nameArray.size();
}
/***************////////////////VIEWHOLDER///////////////////*******************
public class ViewHolder extends RecyclerView.ViewHolder {
// public TextView URLName;
public TextView mFullname;
public RelativeLayout button;
public ExpandableLinearLayout expandableLayout;
public ViewHolder(#NonNull View itemView) {
super(itemView);
mFullname=itemView.findViewById(R.id.nameArray);
//URLName=itemView.findViewById(R.id.URLName);
button=itemView.findViewById(R.id.button);
expandableLayout=itemView.findViewById(R.id.expandableLayout);
}
}
}

Items in the RecyclerView are not showing

List_items are not showing in the RecyclerView.
Have tried changing the layout height and other answers.
The list_items should contain
-item_name
-item_quantity
-date
So basically after entering the respective dataset in an AlertDialog and after clicking the save button, the ListActivity will show up. But a Blank Screen is showing up not containing the list_items within the CardView.
Here's the ListActivity
package com.example.akash.distributedapp.DatabaseApp.Activities;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import com.example.akash.distributedapp.DatabaseApp.Data.DatabaseHandler;
import com.example.akash.distributedapp.DatabaseApp.Model.Grocery;
import com.example.akash.distributedapp.DatabaseApp.UI.RecyclerViewAdapter;
import com.example.akash.distributedapp.R;
import java.util.ArrayList;
import java.util.List;
public class ListActivity extends AppCompatActivity {
private DatabaseHandler db;
private RecyclerView recyclerView;
private List<Grocery> groceryList;
private List<Grocery> listItems;
private RecyclerViewAdapter recyclerViewAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
db = new DatabaseHandler(this);
recyclerView = findViewById(R.id.recyclerViewID);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
groceryList = new ArrayList<>();
listItems = new ArrayList<>();
//get items from database
groceryList = db.getAllGroceries();
for(Grocery c : groceryList){
Grocery grocery = new Grocery();
grocery.setName(c.getName());
grocery.setQuantity("Qty:" + c.getQuantity());
grocery.setId(c.getId());
grocery.setDateItemAdded("Added on: " + c.getDateItemAdded());
listItems.add(grocery);
}
recyclerViewAdapter = new RecyclerViewAdapter(this, listItems);
recyclerView.setAdapter(recyclerViewAdapter);
recyclerViewAdapter.notifyDataSetChanged();
}
}
Here's the adapter class
package com.example.akash.distributedapp.DatabaseApp.UI;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import com.example.akash.distributedapp.DatabaseApp.Model.Grocery;
import com.example.akash.distributedapp.R;
import java.util.List;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>{
private Context context;
private List<Grocery> groceryItems;
public RecyclerViewAdapter(Context context, List<Grocery> groceryItems) {
this.context = context;
this.groceryItems = groceryItems;
}
#NonNull
#Override
public RecyclerViewAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_row, parent, false);
return new ViewHolder(view, context);
}
#Override
public void onBindViewHolder(#NonNull RecyclerViewAdapter.ViewHolder holder, int position) {
Grocery grocery = groceryItems.get(position);
holder.groceryItemName.setText(grocery.getName());
holder.quantity.setText(grocery.getQuantity());
holder.quantity.setText(grocery.getDateItemAdded());
}
#Override
public int getItemCount() {
return groceryItems.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView groceryItemName;
public TextView quantity;
public TextView dateAdded;
public Button editBtn;
public Button deleteBtn;
public int id;
public ViewHolder(View itemView, Context ctx) {
super(itemView);
context = ctx;
groceryItemName = itemView.findViewById(R.id.tv_item);
quantity = itemView.findViewById(R.id.tv_qty);
dateAdded = itemView.findViewById(R.id.tv_date);
editBtn = itemView.findViewById(R.id.btn_edit);
deleteBtn = itemView.findViewById(R.id.btn_delete);
editBtn.setOnClickListener(this);
deleteBtn.setOnClickListener(this);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//opens new activity
}
});
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_edit:
break;
case R.id.btn_delete:
break;
}
}
}
}
Here is my XML file :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="125dp"
android:padding="5dp">
<android.support.v7.widget.CardView
android:id="#+id/cardView"
android:background="#color/colorAccent"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<RelativeLayout
android:padding="15dp"
android:background="#color/colorAccent"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/tv_item"
android:text="Grocery name"
android:textSize="18sp"
android:textStyle="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/tv_qty"
android:layout_below="#+id/tv_item"
android:text="Quantity"
android:paddingTop="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/tv_date"
android:paddingTop="5dp"
android:text="Date"
android:layout_below="#+id/tv_qty"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TableRow
android:layout_alignParentRight="true"
android:layout_marginTop="15dp"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<Button
android:id="#+id/btn_edit"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginRight="15dp"
android:background="#android:drawable/ic_menu_edit"/>
<Button
android:id="#+id/btn_delete"
android:layout_width="30dp"
android:layout_height="30dp"
android:background="#android:drawable/ic_delete"/>
</TableRow>
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>

Error: incompatible types: View cannot be converted to RecyclerView

I'm new to android programming. I'm trying to make a single page app with a list of videos which I can scroll and do so, I am using RecyclerView. In my activity, it says a view cannot be converted to RecyclerView and as far as I know, RecyclerView does not have any widgets. What should I do? I will attach my code.
My activity:
package com.arvindsudheer.youtubeplayertesting;
import android.app.Activity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
/**
* Created by ArvindSudheer on 6/10/2017.
*/
class RecyclerView {
public LinearLayoutManager layoutManager;
public MyAdapter adapter;
public boolean hasFixedSize;
private void setLayoutManager(LinearLayoutManager layoutManager) {
this.layoutManager = layoutManager;
}
private void setAdapter(MyAdapter adapter) {
this.adapter = adapter;
}
private void setHasFixedSize(boolean hasFixedSize) {
this.hasFixedSize = hasFixedSize;
}
/**
* Created by ArvindSudheer on 6/9/2017.
*/
public class MyActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.childview1);
RecyclerView recyclerView=(RecyclerView)findViewById(R.id.list);
recyclerView.setHasFixedSize(true);
//to use RecycleView, you need a layout manager. default is
LinearLayoutManager
LinearLayoutManager linearLayoutManager=new
LinearLayoutManager(this);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(linearLayoutManager);
MyAdapter adapter=new MyAdapter(MyActivity.this);
recyclerView.setAdapter(adapter);
}
}
}
MY Adapter:
package com.arvindsudheer.youtubeplayertesting;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
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.RelativeLayout;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubeStandalonePlayer;
import com.google.android.youtube.player.YouTubeThumbnailLoader;
import com.google.android.youtube.player.YouTubeThumbnailView;
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.VideoInfoHolder> {
//these ids are the unique id for each video
String[] VideoID = {"kN6lRqzmcOY", "MzmSFocMdJk", "L3LixkCN5tM","EuNaQCUjtCw","d-I2JSlEKtA","rwSf_12aMfE","13HIRNVFRlk","BH5_7IYvcVE","Lxc8-INx5G0","iwE8foegHkM","kCKUZdqo600","dr36AF4MqjY","IrMLXTw0528","gyxgVsXMYq0","71MTp2Ley3U","oeNRrGaGV20","loxMW2honqw","Sv63K3ESstA","7U8NzRAvy-I","2kdcR1QBqAI","n3w5c2VYcoU","2zA8W7h7ays","qfkbvujyPpc","JVF8pE1KxaA","f0bi0yl7uZU","5DbdWFAs8EI","5DbdWFAs8EI","2BFUvmCrn1o","yuYbVcoq9nk","lkFlQ5ECM8Q","JuYrl_49WA4","r3L87CUTxeU","RJMvq0pgvkg","9TuDEhfOLUc","HFTTDvuPMOs","fHRh1ksUOJg","OW7Gwuz8vTU","NitQnVpvzd4","-QOEEyuKPMY"};
Context ctx;
public MyAdapter(Context context) {
this.ctx = context;
}
#Override
public VideoInfoHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.my_list_view, parent, false);
return new VideoInfoHolder(itemView);
}
#Override
public void onBindViewHolder(final VideoInfoHolder holder, final int position) {
final YouTubeThumbnailLoader.OnThumbnailLoadedListener onThumbnailLoadedListener = new YouTubeThumbnailLoader.OnThumbnailLoadedListener(){
#Override
public void onThumbnailError(YouTubeThumbnailView youTubeThumbnailView, YouTubeThumbnailLoader.ErrorReason errorReason) {
}
#Override
public void onThumbnailLoaded(YouTubeThumbnailView youTubeThumbnailView, String s) {
youTubeThumbnailView.setVisibility(View.VISIBLE);
holder.relativeLayoutOverYouTubeThumbnailView.setVisibility(View.VISIBLE);
}
};
holder.youTubeThumbnailView.initialize(Resource.KEY, new YouTubeThumbnailView.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubeThumbnailView youTubeThumbnailView, YouTubeThumbnailLoader youTubeThumbnailLoader) {
youTubeThumbnailLoader.setVideo(VideoID[position]);
youTubeThumbnailLoader.setOnThumbnailLoadedListener(onThumbnailLoadedListener);
}
#Override
public void onInitializationFailure(YouTubeThumbnailView youTubeThumbnailView, YouTubeInitializationResult youTubeInitializationResult) {
//write something for failure
}
});
}
#Override
public int getItemCount() {
return VideoID.length;
}
public class VideoInfoHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
protected RelativeLayout relativeLayoutOverYouTubeThumbnailView;
YouTubeThumbnailView youTubeThumbnailView;
protected ImageView playButton;
public VideoInfoHolder(View itemView) {
super(itemView);
playButton=(ImageView)itemView.findViewById(R.id.btnYoutube_player);
playButton.setOnClickListener(this);
relativeLayoutOverYouTubeThumbnailView = (RelativeLayout) itemView.findViewById(R.id.relativeLayout_over_youtube_thumbnail);
youTubeThumbnailView = (YouTubeThumbnailView) itemView.findViewById(R.id.youtube_thumbnail);
}
#Override
public void onClick(View v) {
Intent intent = YouTubeStandalonePlayer.createVideoIntent((Activity) ctx, Resource.KEY, VideoID[getLayoutPosition()]);
ctx.startActivity(intent);
}
}
private class Resource {
public static final String KEY = "AIzaSyDOv0yWBimW8L8zIiYfTDYH9_9jFpZWgEw";
}
}
layout for each item :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/parent_relativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:foreground="#drawable/image_ripple"
card_view:cardCornerRadius="5dp"
card_view:cardElevation="0dp"
android:layout_marginTop="10dp"
card_view:cardBackgroundColor="#android:color/black"
card_view:cardPreventCornerOverlap="false"
card_view:cardUseCompatPadding="true">
<com.google.android.youtube.player.YouTubeThumbnailView
android:id="#+id/youtube_thumbnail"
android:layout_width="match_parent"
android:layout_height="250dp"
android:scaleType="centerCrop"
android:visibility="visible"/>
<RelativeLayout android:id="#+id/relativeLayout_over_youtube_thumbnail"
android:layout_width="match_parent"
android:layout_height="250dp"
android:background="#color/color_background_transparent"
android:visibility="visible">
<ImageView android:id="#+id/btnYoutube_player"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="center"
android:src="#mipmap/ic_youtube_play_button"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>
Main Layout :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>

Categories

Resources