Android Recyclerview Onclicklistener not working - android

I am working o a project where i have RecyclerView with list of items.And when i click on a item it should get the details of the item and start another activity and fill the Texview of the activity with the details.
I have implemented several methods for implementing onclicklistener on Recyclerview but nothing worked
The below one is the latest one i used.It dosent work too.
Thank you...
My InterFace :
public interface ItemClickListener
{
void onItemClick(View view,int position);
}
My Adapterclass :
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Collections;
import java.util.List;
/**
* Created by mrudu on 01-05-2016.
*/
public class mainrow_adapter extends RecyclerView.Adapter<mainrow_adapter.View_Holder>
{
List<Person_details> list = Collections.emptyList();
Context context;
public mainrow_adapter(List<Person_details> list, Context context) {
this.list = list;
this.context = context;
}
#Override
public mainrow_adapter.View_Holder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.main_rowlayout,parent,false);
View_Holder holder = new View_Holder(view);
return holder;
}
#Override
public void onBindViewHolder(mainrow_adapter.View_Holder holder, int position)
{
Person_details person_details = new Person_details();
holder.nametext.setText(list.get(position).getName());
holder.amounttext.setText(list.get(position).getAmount());
holder.setClickListener(new ItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Person_details selectedPerson = list.get(position);
String name = selectedPerson.getName();
Toast.makeText(context,name,Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return list.size();
}
public class View_Holder extends RecyclerView.ViewHolder implements View.OnClickListener
{
TextView nametext,amounttext;
private ItemClickListener clickListener;
public View_Holder(View itemView) {
super(itemView);
nametext = (TextView)itemView.findViewById(R.id.Name);
amounttext = (TextView)itemView.findViewById(R.id.Amount);
}
public void setClickListener(ItemClickListener itemClickListener)
{
clickListener = itemClickListener;
}
#Override
public void onClick(View view)
{
clickListener.onItemClick(view,getAdapterPosition());
}
}
}
Main activity :
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainList extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mainlist);
final Intent adnew = new Intent(this,Add_Person.class);
RecyclerView recyclerView = (RecyclerView)findViewById(R.id.recyclerview);
List<Person_details> list = filldata();
mainrow_adapter adapter = new mainrow_adapter(list,getApplication());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
RecyclerView.ItemAnimator animator = new DefaultItemAnimator();
animator.setAddDuration(1000);
animator.setRemoveDuration(1000);
recyclerView.setItemAnimator(animator);
FloatingActionButton floatingActionButton = (FloatingActionButton)findViewById(R.id.addnewfab);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainList.this, "Add new Log", Toast.LENGTH_SHORT).show();
startActivity(adnew);
}
});
}
public List<Person_details> filldata()
{
List<Person_details> data = new ArrayList<>();
data.add(new Person_details("Mrudhu","9959461221","Glp","2500"));
data.add(new Person_details("Ram","9959461221","Glp","2820"));
data.add(new Person_details("Syam","9959461221","Glp","8000"));
data.add(new Person_details("Shekar","9959461221","Glp","320"));
data.add(new Person_details("Sharif","9959461221","Glp","836"));
data.add(new Person_details("Rahul","9959461221","Glp","126"));
data.add(new Person_details("Rohith","9959461221","Glp","50"));
data.add(new Person_details("Manikanta","9959461221","Glp","55"));
data.add(new Person_details("Ramesh","9959461221","Glp","198"));
data.add(new Person_details("Ram","9959461221","Glp","162"));
return data;
}
}

You are not registering click listener. Register it in View_Holder constructor
itemView.setOnClickListener(this);
public View_Holder(View itemView) {
super(itemView);
nametext = (TextView)itemView.findViewById(R.id.Name);
amounttext = (TextView)itemView.findViewById(R.id.Amount);
itemView.setOnClickListener(this);
}

Related

How to get data from one RecyclerView and show it in another Activity's RecyclerView

I have an Android nested recycler view in which I am able to show the data now I want to show that data in another activity recycler view. How can I do that?
This is my nested list view:-
This is where I want to show data in list:-
Here's my code: my Main Activity:-
package com.saikari.vid.activities;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.saikari.vid.R;
import com.saikari.vid.adapters.VerticalRVAdapter;
import com.saikari.vid.models.HorizontalModel;
import com.saikari.vid.models.VerticalModel;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
private DatabaseReference dbCategories;
VerticalRVAdapter adapter;
RecyclerView verticalRecyclerView;
ArrayList<VerticalModel> mListData = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
verticalRecyclerView = findViewById(R.id.recycler_view);
verticalRecyclerView.setHasFixedSize(true);
setData();
}
private void setData() {
for (int i = 0; i<10; i++){
VerticalModel verticalModel = new VerticalModel();
verticalModel.setCat_title("Title: "+i);
ArrayList<HorizontalModel> arrayListHorizontal = new ArrayList<>();
for (int j = 0; j<10; j++){
HorizontalModel horizontalModel = new HorizontalModel();
horizontalModel.setVid_url("https://picsum.photos/seed/picsum/200/300");
horizontalModel.setVid_title("Name: "+j);
arrayListHorizontal.add(horizontalModel);
}
verticalModel.setVidArrayList(arrayListHorizontal);
mListData.add(verticalModel);
}
adapter.notifyDataSetChanged();
}
}
Vertical RecyclerView adapter class:-
public class VerticalRVAdapter extends RecyclerView.Adapter<VerticalRVAdapter.VerticalRVViewHolder> {
Context context;
ArrayList<VerticalModel> arrayList;
public VerticalRVAdapter(Context context, ArrayList<VerticalModel> arrayList){
this.arrayList = arrayList;
this.context = context;
}
#NonNull
#Override
public VerticalRVViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_vertical,parent,false);
return new VerticalRVViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull VerticalRVViewHolder holder, int position) {
final VerticalModel verticalModel = arrayList.get(position);
String title = verticalModel.getCat_title();
final ArrayList<HorizontalModel> singleItem = verticalModel.getVidArrayList();
holder.titleText.setText(title);
HorizontalRVAdapter horizontalRecyclerViewAdapter= new HorizontalRVAdapter(context,singleItem);
holder.recyclerView.setHasFixedSize(true);
holder.recyclerView.setLayoutManager(new LinearLayoutManager(context,LinearLayoutManager.HORIZONTAL,false));
holder.recyclerView.setAdapter(horizontalRecyclerViewAdapter);
holder.buttonMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, verticalModel.getCat_title(), Toast.LENGTH_SHORT).show();
Intent i = new Intent(context, VideoListActivity.class);
i.putExtra("catTitle", verticalModel.getCat_title());
context.startActivity(i);
}
});
}
#Override
public int getItemCount() {
return arrayList.size();
}
public class VerticalRVViewHolder extends RecyclerView.ViewHolder{
RecyclerView recyclerView;
TextView titleText;
TextView buttonMore;
public VerticalRVViewHolder(#NonNull View itemView) {
super(itemView);
recyclerView = itemView.findViewById(R.id.recycler_view1);
titleText = itemView.findViewById(R.id.titleText);
buttonMore = itemView.findViewById(R.id.btn_more);
}
}
}
Horizontal Recycler View Adapter class:-
public class HorizontalRVAdapter extends RecyclerView.Adapter<HorizontalRVAdapter.HorizontalRVViewHolder> {
Context context;
ArrayList<HorizontalModel> arrayList;
public HorizontalRVAdapter(Context context, ArrayList<HorizontalModel> arrayList) {
this.context = context;
this.arrayList = arrayList;
}
#NonNull
#Override
public HorizontalRVViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_horizontal,parent,false);
return new HorizontalRVViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final HorizontalRVViewHolder holder, int position) {
final HorizontalModel horizontalModel = arrayList.get(position);
holder.textViewTitle.setText(horizontalModel.getVid_title());
com.bumptech.glide.Glide.with(context).load(horizontalModel.getVid_url()).into(holder.imageViewThumb);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, horizontalModel.getVid_url(), Toast.LENGTH_SHORT).show();
Intent i = new Intent(context, YoutubePlayActivity.class);
i.putExtra("videoID", horizontalModel.getVid_url());
context.startActivity(i);
}
});
}
#Override
public int getItemCount() {
return arrayList.size();
}
public class HorizontalRVViewHolder extends RecyclerView.ViewHolder{
TextView textViewTitle;
ImageView imageViewThumb;
public HorizontalRVViewHolder(#NonNull View itemView) {
super(itemView);
textViewTitle = itemView.findViewById(R.id.textTitleHorizontal);
imageViewThumb = itemView.findViewById(R.id.ivThumb);
}
}
}
Data in list activity class (this is the activity where I need to show data):-
public class VideoListActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_list);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(getIntent().getStringExtra("catTitle"));
}
}
Implement Parcelable on HorizontalModel class. If you need help with that check here.
In VerticalRVAdapter inside onBindViewHolder method
holder.buttonMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, verticalModel.getCat_title(), Toast.LENGTH_SHORT).show();
Intent i = new Intent(context, VideoListActivity.class);
i.putExtra("catTitle", verticalModel.getCat_title());
// Put horizontal models in extra bundle
i.putParcelableArrayListExtra("horizontal_models", singleItem);
context.startActivity(i);
}
});
You can now get the bundled HorizontalModel list in VideoListActivity inside onCreate as
ArrayList<HorizontalModel> horizontalModels = getIntent().getParcelableArrayListExtra("horizontal_models");
You can use this list to populate the vertical list that you want to show.

RecyclerView And onClicklistener

I use this code in MainActivity But I can not access setOnMenuItemClickListener in MainActivity .
MainActivity class:
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.ImageView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
Toast toast ;
ImageView hahaha;
protected static int ss=77;
//recyclerview objects
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
public int xxx=222;
//model object for our list data
private List<MyList> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//initializing views
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
list = new ArrayList<>();
//loading list view item with this function
loadRecyclerViewItem();
}
private void loadRecyclerViewItem() {
//you can fetch the data from server or some apis
//for this tutorial I am adding some dummy data directly
for (int i = 1; i <= 7; i++) {
MyList myList = new MyList(
"Heading " + i,
"id = " + i,
"https://mediaresources.idiva.com/media//content/2014/May/diet_kids_health1.jpg",
"HHHHHH" + i
);
list.add(myList);
}
adapter = new CustomAdapter(list, this);
recyclerView.setAdapter(adapter);
}
}
and this is CustomAdaptor.class
import android.content.Context;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import java.util.List;
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {
private List<MyList> list;
private Context mCtx;
public CustomAdapter(List<MyList> list, Context mCtx) {
this.list = list;
this.mCtx = mCtx;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_items, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(final CustomAdapter.ViewHolder holder, final int position) {
MyList myList = list.get(position);
//loading the image
Glide.with(mCtx)
.load(myList.getUrl())
.into(holder.imageView);
holder.textViewHead.setText(myList.getHead());
holder.textViewDesc.setText(myList.getDesc());
//holder.textViewDesc.setText(myList.getIdofdata());
holder.buttonViewOption.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//creating a popup menu
PopupMenu popup = new PopupMenu(mCtx, holder.buttonViewOption);
//inflating menu from xml resource
popup.inflate(R.menu.options_menu);
//adding click listener
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu1:
//handle menu1 click
holder.textViewHead.setText("moshiri" + holder.textViewHead.getText() );
break;
case R.id.menu2:
//holder.textViewHead.setText("new" + holder.textViewDesc.getText() );
holder.textViewHead.setText("mohsen hi dear");
break;
case R.id.menu3:
holder.textViewHead.setText("##################" + list.indexOf(this));
holder.textViewDesc.setText("############" + list.indexOf(this));
//MainActivity me=new MainActivity();
MainActivity.ss=77;
removeItem(3);
break;
}
return false;
}
});
//displaying the popup
popup.show();
}
});
}
#Override
public int getItemCount() {
return list.size();
}
public void removeItem(int position) {
list.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, getItemCount() );
// notifyDataSetChanged();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView textViewHead;
public TextView textViewDesc;
public TextView buttonViewOption;
public ImageView imageView;
public ViewHolder(View itemView) {
super(itemView);
textViewHead = (TextView) itemView.findViewById(R.id.textViewHead);
textViewDesc = (TextView) itemView.findViewById(R.id.textViewDesc);
buttonViewOption = (TextView) itemView.findViewById(R.id.textViewOptions);
imageView = (ImageView) itemView.findViewById(R.id.imageView);
}
}
}
In CustomAdaptor I access onclick listener in menu and button but I can not manage menu and button in MainActivity. How can I use Listener in mainActivity or how can I send changes from CustomAdaptor to mainActivity?
Use interface for this purpose. In your CustomAdapter declare that interface and in ViewHolder override the click listener method and pass items from adapter you want. Currently I am passing position only you can pass anything here. I have make changes in your code just check below.
import android.content.Context;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import java.util.List;
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {
protected CustomClicklistener mListener;
private List<MyList> list;
private Context mCtx;
private CustomClicklistener clickListener;
public interface CustomClicklistener {
void onItemClick(int position);
}
public CustomAdapter(List<MyList> list, Context mCtx, CustomClicklistener
clickListener) {
this.list = list;
this.mCtx = mCtx;
this.clickListener = clickListener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_items, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(final CustomAdapter.ViewHolder holder, final int position) {
MyList myList = list.get(position);
//loading the image
Glide.with(mCtx)
.load(myList.getUrl())
.into(holder.imageView);
holder.textViewHead.setText(myList.getHead());
holder.textViewDesc.setText(myList.getDesc());
//holder.textViewDesc.setText(myList.getIdofdata());
holder.buttonViewOption.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//creating a popup menu
PopupMenu popup = new PopupMenu(mCtx, holder.buttonViewOption);
//inflating menu from xml resource
popup.inflate(R.menu.options_menu);
//adding click listener
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu1:
//handle menu1 click
holder.textViewHead.setText("moshiri" + holder.textViewHead.getText() );
break;
case R.id.menu2:
//holder.textViewHead.setText("new" + holder.textViewDesc.getText() );
holder.textViewHead.setText("mohsen hi dear");
break;
case R.id.menu3:
holder.textViewHead.setText("##################" + list.indexOf(this));
holder.textViewDesc.setText("############" + list.indexOf(this));
//MainActivity me=new MainActivity();
MainActivity.ss=77;
removeItem(3);
break;
}
return false;
}
});
//displaying the popup
popup.show();
}
});
}
#Override
public int getItemCount() {
return list.size();
}
public void removeItem(int position) {
list.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, getItemCount() );
// notifyDataSetChanged();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView textViewHead;
public TextView textViewDesc;
public TextView buttonViewOption;
public ImageView imageView;
public ViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
textViewHead = (TextView) itemView.findViewById(R.id.textViewHead);
textViewDesc = (TextView) itemView.findViewById(R.id.textViewDesc);
buttonViewOption = (TextView) itemView.findViewById(R.id.textViewOptions);
imageView = (ImageView) itemView.findViewById(R.id.imageView);
}
#Override
public void onClick(View view) {
if (mListener != null) {
mListener.onItemClick(getAdapterPosition());
notifyDataSetChanged();
}
}
}
}
In MainActivity you can get that clicklistener like below in oncCreate METHOD AT THE END
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.ImageView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
CustomAdapter.CustomClicklistener clickListener;
Toast toast ;
ImageView hahaha;
protected static int ss=77;
//recyclerview objects
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
public int xxx=222;
//model object for our list data
private List<MyList> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//initializing views
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
list = new ArrayList<>();
//loading list view item with this function
loadRecyclerViewItem();
clickListener = new CustomAdapter.CustomClicklistener() {
#Override
public void onItemClick(int position) {
// Do what you want here
Toast.makeText(MainActivity.this, "This ... " , Toast.LENGTH_LONG).show();
}
};
}
private void loadRecyclerViewItem() {
//you can fetch the data from server or some apis
//for this tutorial I am adding some dummy data directly
for (int i = 1; i <= 7; i++) {
MyList myList = new MyList(
"Heading " + i,
"id = " + i,
"https://media.alalamtv.net/news/image/855x495//2015/02/16/alalam_635596703961833722_25f_4x3.jpg",
"HHHHHH" + i
);
list.add(myList);
}
adapter = new CustomAdapter(list, this, clickListener);
recyclerView.setAdapter(adapter);
}
}
Create an interface in your CustomAdapter class like:
CustomAdapterListener customAdapterListener;
public interface CustomAdapterListener {
void onItemClick();
}
And then in your constructor :
public CustomAdapter(List<MyList> list, Context mCtx, CustomAdapterListener customAdapterListener) {
this.list = list;
this.mCtx = mCtx;
this.customAdapterListener= customAdapterListener;
}
and trigger interface method when click event occured:
holder.buttonViewOption.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
customAdapterListener.onItemClick();
});
And from your Activity; add your activity as listener like this :
adapter = new CustomAdapter(list, this, this);
Finally you have to implement your interface in your activity like :
public class MainActivity extends AppCompatActivity implements CustomAdapter.CustomAdapterListener
And click on red underlined text and press alt+enter, this will suggest you to implement interface methods, after confirm that warning you have onItemClick method in your activity. This method will trigger from adapter if click event is occured.

How to take reference of itemClick on recyclerview

Suppose I have a scrolling RecyclerView (where images scrolling Horizontally) after clicking any of images it will appear below the recyclerView.
Main Activity:
package com.aariyan.testm;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;`enter code here`
import com.daimajia.slider.library.Animations.DescriptionAnimation;
import com.daimajia.slider.library.Indicators.PagerIndicator;
import com.daimajia.slider.library.SliderLayout;`enter code here`
import com.daimajia.slider.library.SliderTypes.BaseSliderView;
import com.daimajia.slider.library.SliderTypes.TextSliderView;
import com.daimajia.slider.library.Tricks.ViewPagerEx;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
//implements BaseSliderView.OnSliderClickListener, ViewPagerEx.OnPageChangeListener
private SliderLayout mDemoSlider;
private ImageView imageView;
private String selectDrinkCategory;
private String drinks = "drinks";
//String i = "0";
int j;
RecyclerViewAdapter recyclerViewAdapter;
private int[] images = {R.drawable.a,
R.drawable.bb,
R.drawable.c,
R.drawable.d,
R.drawable.e,
R.drawable.d_2_1,
R.drawable.d_2_2,
R.drawable.d_2_3,
R.drawable.d_2_4
};
private ArrayList<Integer> inputImages = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//get Intent
Intent intent = getIntent();
if (getIntent() != null) {
selectDrinkCategory = intent.getStringExtra("drinks");
}
initUI();
initBitmapImages();
initRecyclerView();
Toast.makeText(this, "J: "+j, Toast.LENGTH_SHORT).show();
}
private void initRecyclerView() {
LinearLayoutManager manager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
RecyclerView recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(manager);
RecyclerViewAdapter adapter = new RecyclerViewAdapter(inputImages, this);
Toast.makeText(this, " Main Value j : " + adapter.index, Toast.LENGTH_SHORT).show();
imageView.setImageResource(images[j]);
recyclerView.setAdapter(adapter);
}
private void initBitmapImages() {
for (int i = 0; i < images.length; i++) {
// inputImages.add(String.valueOf(images[i]));
inputImages.add(images[i]);
}
}
private void initUI() {
//mDemoSlider = (SliderLayout) findViewById(R.id.slider);
imageView = findViewById(R.id.viewSingleImages);
//imageView.setImageResource((images[0]));
}
#Override
protected void onStop() {
// To prevent a memory leak on rotation, make sure to call stopAutoCycle() on the slider before activity or fragment is destroyed
super.onStop();
}
}
RecyclerView:
I have a scrolling RecyclerView (where images scrolling Horizontally) after clicking any of images it will appear below the
package com.aariyan.testm;
import android.content.Context;
import android.content.Intent;
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.Toast;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
private ArrayList<Integer> totalImages = new ArrayList<>();
private Context context;
//MainActivity mainActivity;
int index = 0;
public RecyclerViewAdapter(ArrayList<Integer> totalImages, Context context) {
this.totalImages = totalImages;
this.context = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.images, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder viewHolder, final int i) {
//index = 0;
Glide.with(context).asBitmap().load(totalImages.get(i)).into(viewHolder.singleImages);
viewHolder.setItemClickListener(new ItemClickListener() {
#Override
public void onClick(View view, int position, boolean isClicked) {
Toast.makeText(context, "TotalImages : "+totalImages.get(i), Toast.LENGTH_SHORT).show();
index = totalImages.get(i);
}
});
// viewHolder.singleImages.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// Toast.makeText(context, "" + viewHolder.getAdapterPosition(), Toast.LENGTH_SHORT).show();
// //viewHolder.imageView.setImageResource(totalImages.get(viewHolder.getAdapterPosition()));
// //index = viewHolder.getAdapterPosition();
// index = i;
// Toast.makeText(context, "Index : " + index, Toast.LENGTH_SHORT).show();
// }
// });
}
#Override
public int getItemCount() {
return totalImages.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public ImageView singleImages;
private ItemClickListener itemClickListener;
public ViewHolder(#NonNull View itemView) {
super(itemView);
singleImages = itemView.findViewById(R.id.imagesViewOnScroll);
itemView.setOnClickListener(this);
}
public void setItemClickListener (ItemClickListener itemClickListener) {
this.itemClickListener = itemClickListener;
}
#Override
public void onClick(View v) {
itemClickListener.onClick(v,getAdapterPosition(),false);
}
}
}
activity_main.xml : just have a recyclerView and image View
and images.xml : only a image view to set on RecyclerView
for get clicked item of recyckerview you have to use interface.
here is code sample:
first of all make one interface like below :
public interface ImageClickListener {
void onImageClick(String path);
}
now in your activity, make adapter's object like this
RecyclerViewAdapter adapter = new RecyclerViewAdapter(inputImages, this, new ImageClickListener() {
#Override
public void onImageClick(String path) {
Glide.with(context).load(path).into(imageView);
}
});
now create your adapter and make a constructor like this
public RecyclerViewAdapter(ArrayList<Integer> totalImages, Context context, ImageClickListener imageClickListener) {
this.totalImages = totalImages;
this.context = context;
this.imageClickListener = imageClickListener;
}
now you have an instance of interface in which you have one method, named onImageClick() in which you will pass the path of clicked image.
now on click of image do code like this:
viewHolder.singleImages.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
imageClickListener.onImageClick(totalImages.get(viewHolder.getAdapterPosition()));
}
});
now your method of interface will call & it will execute activity's image view to set the given path.
Enjoy codding :)

When I click on item in recyclerview, how can I retrieve data from firebase and show it in a list view in the next activity?

This is my recyclerview class where I have electrician, plumber, welder etc as my recyclerview items. I want whenever user click on any of these items the respective data that is retrieved from firebase should be shown in the next activity.
package com.example.hp.dc_project;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.CardView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
/** * Created by HP on 20-07-2018. */
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> {
private Context mContext;
private List<category> mdata;
public RecyclerViewAdapter(Context context, List<category> mdata) {
this.mContext = context;
this.mdata = mdata;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater mInflater = LayoutInflater.from(mContext);
View view = mInflater.inflate(R.layout.cardview_category,parent,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.tv.setText(mdata.get(position).getName());
holder.iv.setImageResource(mdata.get(position).getThumnail());
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(mContext.getApplicationContext(),available_worker.class);
mContext.startActivity(i);
}
});
}
#Override
public int getItemCount() {
return mdata.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView tv;
ImageView iv;
CardView cardView;
public MyViewHolder(View itemView) {
super(itemView);
tv = (TextView)itemView.findViewById(R.id.tv_category);
iv = (ImageView)itemView.findViewById(R.id.iv_category);
cardView = (CardView)itemView.findViewById(R.id.cardview);
}
}
}
This is the activity class where I want to display the listview containing the data that is retrieved from firebase after clicking on the recyclerview items:
package com.example.hp.dc_project;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class available_worker extends AppCompatActivity {
private ListView lv;
private FirebaseDatabase database;
private ArrayList<String>list;
private ArrayAdapter<String>adapter;
private Electrician elec;
// adapter = new ArrayAdapter<Electrician>(this,R.layout.list_of_work
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_available_worker);
lv = (ListView)findViewById(R.id.listView_workeravailable);
elec = new Electrician();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?>parent, View view, int position, long id) {
Intent i = new Intent(available_worker.this,WorkerProfile.class);
startActivity(i);
}
});
list = new ArrayList<>();
adapter = new ArrayAdapter<String>(this, R.layout.list_of_worker,R.id.employeeadd);
database = FirebaseDatabase.getInstance();
DatabaseReference rootref = database.getReference();
DatabaseReference electricianref = rootref.child("Employee").child("Electrician");
electricianref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String fName = ds.child("Fname").getValue(String.class);
String lName = ds.child("Lname").getValue(String.class);
String address = ds.child("Address").getValue(String.class);
list.add(fName);
list.add(lName);
list.add(address);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
In on click get your worker id and put in extra , in the next activity put value event listner and get the respective data but you have one thing is that you have to have the id or something which can uniquely identify the reference of firebase.
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(mContext.getApplicationContext(),available_worker.class);
i.putExtra("uid",workerid);
mContext.startActivity(i);
}
});
in the next activity
String s = getIntent().getStringExtra("uid");
firebaseref.child(s).addvalueEventListner(////) {//pupulate your list view}

RecyclerView Adapter List<E> get 0

I am new in android development. I am getting a problem, I have create simple application in which I have RecyclerView in MainActivity. I try to Drag and Drop position. But when I move from MainActivity to CompleteList_activity and come to again MainActivity and try to Drag and drop i got ArrayOutOfBound error because List value get 0 in
public void positionchange(int fromPosition, int toPosition) method.
MainActivity :
package com.example.marmeto.todolist;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
DBHelper db;
ImageButton btn_addtodolist,btn_completelist;
List<Model> todolist = new ArrayList<>();
List<Model> adapterList = new ArrayList<>();
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private ToDoList_Adapter adapter;
public static final int NEW_WORD_ACTIVITY_REQUEST_CODE = 1;
Model mToDOItemList = new Model();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new DBHelper(this);
recyclerView = (RecyclerView)findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
btn_addtodolist = (ImageButton) findViewById(R.id.btn_addtodolist);
btn_completelist = (ImageButton)findViewById(R.id.btn_completedlist);
btn_addtodolist.setOnClickListener(this);
btn_completelist.setOnClickListener(this);
getValue();
}
void getValue(){
todolist.clear();
todolist = db.getUserDetail();
Collections.sort(todolist, new Comparator<Model>() {
#Override public int compare(Model p1, Model p2) {
return p1.getPosition()- p2.getPosition(); // Ascending
}
});
adapter = new ToDoList_Adapter(todolist,getApplicationContext());
ItemTouchHelper.SimpleCallback callback=new SwipItem(adapter);
ItemTouchHelper helper=new ItemTouchHelper(callback);
helper.attachToRecyclerView(recyclerView);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.btn_addtodolist) {
Intent intent = new Intent(getApplicationContext(), AddToDoList_Activity.class);
startActivity(intent);
} else {
Intent intent = new Intent(getApplicationContext(),CompletedActivity.class);
startActivity(intent);
}
}
}
AdapterClass:
package com.example.marmeto.todolist;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Collections;import java.util.List;
public class ToDoList_Adapter extends RecyclerView.Adapter<ToDoList_Adapter.ViewHolder> {
List<Model> items;
private Context context;
public ToDoList_Adapter(List<Model> items, Context context) {
this.items = items;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.todolist_adapter, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
final Model itemlist = items.get(position);
holder.todoText.setText(itemlist.getPosition()+" "+itemlist.getTitle());
}
#Override
public int getItemCount() {
return items.size();
}
public void positionchange(int fromPosition, int toPosition)
{
try {
Collections.swap(items,fromPosition,toPosition);
DBHelper db = new DBHelper(context);
db.updateList(items);
}catch (Exception e)
{
e.printStackTrace();
}
this.notifyItemMoved(fromPosition,toPosition);
}
public void deletePlanet(int pos)
{
//GET ID
try {
Model p = items.get(pos);
int id = p.getId();
//DELETE FROM DB
DBHelper db = new DBHelper(context);
if (db.delete(id)) {
items.remove(pos);
db.updateList(items);
} else {
Toast.makeText(context, "Unable To Delete", Toast.LENGTH_SHORT).show();
}
this.notifyItemRemoved(pos);
}catch (Exception e){
e.printStackTrace();
}
}
class ViewHolder extends RecyclerView.ViewHolder {
public TextView todoText;
public Button btn_done;
public ViewHolder(final View itemView) {
super(itemView);
todoText = (TextView)itemView.findViewById(R.id.todoItem_text);
btn_done = (Button)itemView.findViewById(R.id.btn_done);
btn_done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DBHelper db = new DBHelper(context);
try {
Model p = items.get(getAdapterPosition());
db.updateData(p.getId());
items.remove(getAdapterPosition());
db.updateList(items);
}catch (Exception e){
e.printStackTrace();
}
notifyItemRemoved(getAdapterPosition());
}
});
}
}
}
Thanks in advance to help.
You call your getValue() and so you populate your data into onCreate. But when you pass to a new Activity and then you go back to the previous activity onCreate method is not called again.
Try calling your getValue() into your onResume method
Look at there Activity lifecycle

Categories

Resources