I have tried some code to can click recyclerview item and get position, but I can't click the recyclerview item.. the data I get from url. So I wan't switch activity with get the item user click..
how I can fix that?
this code for adapter
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
Context context;
private static final String TAG = RecyclerViewAdapter.class.getSimpleName();
List<GetDataAdapter> getDataAdapter;
ImageLoader imageLoader1;
public RecyclerViewAdapter(List<GetDataAdapter> getDataAdapter, Context context) {
super();
this.getDataAdapter = getDataAdapter;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_items, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder Viewholder, int position) {
GetDataAdapter getDataAdapter1 = getDataAdapter.get(position);
imageLoader1 = ServerImageParseAdapter.getInstance(context).getImageLoader();
imageLoader1.get(getDataAdapter1.getImageServerUrl(),
ImageLoader.getImageListener(
Viewholder.networkImageView,//Server Image
R.mipmap.ic_launcher,//Before loading server image the default showing image.
android.R.drawable.ic_dialog_alert //Error image if requested image dose not found on server.
)
);
Viewholder.networkImageView.setImageUrl(getDataAdapter1.getImageServerUrl(), imageLoader1);
Viewholder.ImageTitleNameView.setText(getDataAdapter1.getImageTitleName());
}
#Override
public int getItemCount() {
return getDataAdapter.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
public TextView ImageTitleNameView;
public NetworkImageView networkImageView;
public ViewHolder(View itemView) {
super(itemView);
ImageTitleNameView = (TextView) itemView.findViewById(R.id.textView_item);
networkImageView = (NetworkImageView) itemView.findViewById(R.id.VollyNetworkImageView1);
}
}
}
and this code for mainactivity
public class MainActivity extends AppCompatActivity {
List<GetDataAdapter> GetDataAdapter1;
RecyclerView recyclerView;
RecyclerView.LayoutManager recyclerViewlayoutManager;
RecyclerView.Adapter recyclerViewadapter;
String GET_JSON_DATA_HTTP_URL = "http://androidblog.esy.es/ImageJsonData.php";
String JSON_IMAGE_TITLE_NAME = "image_title";
String JSON_IMAGE_URL = "image_url";
JsonArrayRequest jsonArrayRequest ;
RequestQueue requestQueue ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GetDataAdapter1 = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.recyclerview1);
recyclerView.setHasFixedSize(true);
recyclerViewlayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(recyclerViewlayoutManager);
JSON_DATA_WEB_CALL();
}
public void JSON_DATA_WEB_CALL(){
jsonArrayRequest = new JsonArrayRequest(GET_JSON_DATA_HTTP_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JSON_PARSE_DATA_AFTER_WEBCALL(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array){
for(int i = 0; i<array.length(); i++) {
GetDataAdapter GetDataAdapter2 = new GetDataAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataAdapter2.setImageTitleNamee(json.getString(JSON_IMAGE_TITLE_NAME));
GetDataAdapter2.setImageServerUrl(json.getString(JSON_IMAGE_URL));
} catch (JSONException e) {
e.printStackTrace();
}
GetDataAdapter1.add(GetDataAdapter2);
}
recyclerViewadapter = new RecyclerViewAdapter(GetDataAdapter1, this);
recyclerView.setAdapter(recyclerViewadapter);
}
}
getdataadapter
public class GetDataAdapter {
public String ImageServerUrl;
public String ImageTitleName;
public String getImageServerUrl() {
return ImageServerUrl;
}
public void setImageServerUrl(String imageServerUrl) {
this.ImageServerUrl = imageServerUrl;
}
public String getImageTitleName() {
return ImageTitleName;
}
public void setImageTitleNamee(String Imagetitlename) {
this.ImageTitleName = Imagetitlename;
}
}
You need to set onClickListener to your item view. You can do by following below steps:
Set onCLickListener to root view of your list item.
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_items, parent, false);
Add below code in onCreateViewHolder:
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Add your logic here
}
});
You can add listener while onBindViewHolder:
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Add your logic here
}
});
Thanks.
Put a listener on your recycler item view and then in onclick, start intent to open new activity. Pass the data object you want to pass with the intent.
//make sure your model class GetDataAdapter implements Parcelable
holder.itemView.setOnclickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(this, ActivityToOpen.class);
intent.putExtra("key",Your Object to pass);// getDataAdapter1 in your case
context.startActivity(intent);
}
});
then in your Startted activity receive your object like this
YourObject obj = getIntent().getParcelableExtra("key");
//Your case
GetDataAdapter obj = getIntent().getParcelableExtra("key");
Related
I just want to create a list that will show currently selected item text when I click "Selanjutnya" button, but I don't know how to do that.
So when I click "Selanjutnya", it will show 22, 23. Currently, I use Big Nerd Ranch multi-select to make multi-selection work.
implementation 'com.bignerdranch.android:recyclerview-multiselect:+'
And here is my Codes.
Adapter
public class KetuaAbsenAdapter extends RecyclerView.Adapter<KetuaAbsenAdapter.ViewHolder> {
private List<KetuaAbsenList> listItems;
private Context context;
private MultiSelector mMultiSelector = new MultiSelector();
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.absen_list, parent, false);
return new ViewHolder(v);
}
public KetuaAbsenAdapter(List<KetuaAbsenList> listItems, Context context) {
this.listItems = listItems;
this.context = context;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
final KetuaAbsenList listItem = listItems.get(position);
holder.textViewMuridno.setText(listItem.getMuridno());
holder.textViewMuridnama.setText(listItem.getMuridnama());
}
#Override
public int getItemCount() {
return listItems.size();
}
public class ViewHolder extends SwappingHolder implements View.OnClickListener {
public TextView textViewMuridno;
public TextView textViewMuridnama;
public TextView textViewMuridkelas;
public LinearLayout list_item_linear;
public ViewHolder(View itemView) {
super(itemView, mMultiSelector);
textViewMuridno = (TextView) itemView.findViewById(R.id.muridno);
textViewMuridnama = (TextView) itemView.findViewById(R.id.muridnama);
textViewMuridkelas = (TextView) itemView.findViewById(R.id.muridkelas);
list_item_linear = (LinearLayout) itemView.findViewById(R.id.list_item_linear);
list_item_linear.setOnClickListener(this);
itemView.setOnClickListener(this);
mMultiSelector.setSelectable(true);
}
#Override
public void onClick(View v) {
if (mMultiSelector.tapSelection(this)) {
Toast.makeText(context, "terpilih", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "tidak terpilih", Toast.LENGTH_LONG).show();
}
}
}
}
List Class
public class KetuaDaftarAbsen extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private List<KetuaAbsenList> listItems;
EditText YangTidakHadir;
Button KetuaLanjut;
Dialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ketua_daftar_absen);
YangTidakHadir = (EditText)findViewById(R.id.YangTidakHadir);
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
listItems = new ArrayList<>();
loadRecyclerViewData();
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("custom-message"));
}
public void loadRecyclerViewData(){
final String url = "https://gameblong.com/raset/daftar_absen.php";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
try {
JSONObject jsonObject = new JSONObject(s);
String status = jsonObject.getString("status");
if(status.equals("sukses")){
JSONArray array = jsonObject.getJSONArray("semua");
for (int i = 0; i < array.length(); i++) {
JSONObject o = array.getJSONObject(i);
KetuaAbsenList item = new KetuaAbsenList(
o.getString("murid_no"),
o.getString("murid_nama"),
o.getString("murid_kelas")
);
listItems.add(item);
}
} else {
}
adapter = new KetuaAbsenAdapter(listItems, getApplicationContext());
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
return params;
}
};
Volley.newRequestQueue(this).add(stringRequest);
}
public BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(final Context context, Intent intent) {
final String muno = intent.getStringExtra("muridnomor");
KetuaLanjut = (Button)findViewById(R.id.KetuaLanjut);
KetuaLanjut.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(context, muno, Toast.LENGTH_LONG).show();
}
});
}
};
}
I can use mMultiSelector.getSelectedPositions(); on my Adapter, but only this only gives current selected position (like 0, 1),
You can create an Interface that you add to your adapter and a listener for it.
public interface OnAdapterItemClicked {
// you can name it what ever you need add pass more parameters
void itemClicked(String text);
}
then in your adapter, you initialise it and add the listener on the click event,
private OnAdapterItemClicked mListener = null;
...
#Override
public void onBindViewHolder(#NonNull YourAdapter.ViewHolder holder,
int position) {
...
holder.YourBtn.setOnClickListener(....{
mListener.itemClicked("string you need to pass")
});
...
}
...
public void setOnItemClickListener(OnAdapterItemClicked listener) {
this.mListener = listener;
}
finally in you activity/fragment you add a listener on the recyclerview
rv.setOnItemClickListener(new OnAdapterItemClicked () {
#Override
public void itemClicked(String text) {
Log.d(TAG, "itemClicked: "+text);
}
});
In your adapter, you can add onClickListener like this
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.absen_list, parent, false);
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//your logic goes here
}
});
return new ViewHolder(v);
}
The title of the question doesnt fully explain my problem so allow me to elaborate. I have an app that parses JSON data from the Google Civic API into a recyclerview. One particular field is a TextView that stores a PDF url in a string. How do I set the TextView so it is clickable and opens the PDF preferably in app. I've looked up solutions and I've tried using WebView and PDFReader amongst others, but I couldnt find any solutions that mentioned how to do this from a recyclerview, so I'm not sure where to place this code. Since I am clicking on an item in the recyclerView, I thought I might need to add the code in the recyclerview adapter instead of the main class.
Here is the code for the main class: This class handles the JSON parsing
public class VoterInformation extends AppCompatActivity {
private static final String url = "https://www.googleapis.com/civicinfo/v2/voterinfo?address=2613+Irvington+Ave+San+Bernardino+CA+92407&electionId=2000&officialOnly=false&returnAllAvailableData=false&fields=contests(referendumBallotResponses%2CreferendumBrief%2CreferendumConStatement%2CreferendumEffectOfAbstain%2CreferendumPassageThreshold%2CreferendumProStatement%2CreferendumSubtitle%2CreferendumText%2CreferendumTitle%2CreferendumUrl)&key=AIzaSyB1B5mEKHK8PHDiNcGQ5ZU3fPIH9KWxAcQ";
private TextView refTitle, refSub, refUrl;
private LinearLayoutManager linearLayoutManager;
private List<Refs> refList;
private RecyclerView myrv;
private RecyclerView.Adapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_voter_information);
refTitle = findViewById(R.id.ref_title); //Initialize TextViews
refSub = findViewById(R.id.ref_sub);
myrv = findViewById(R.id.ref_rv); //Initialize recycler view
refList = new ArrayList<>();
adapter = new RefRvAdapter(refList, getApplicationContext());
linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
myrv.setHasFixedSize(true);
myrv.setLayoutManager(linearLayoutManager);
myrv.setAdapter(adapter);
TextView pdf_url = findViewById(R.id.ref_url);
pdf_url.setClickable(true);
pdf_url.setMovementMethod(LinkMovementMethod.getInstance());
getData();
}
private void getData(){
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try{
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray("contests");
String pdf_url = array.getJSONObject(0).getString("referendumUrl") ;
for(int i = 0; i < array.length(); i++){
JSONObject jo = array.getJSONObject(i);
Refs refs = new Refs(jo.getString("referendumTitle"),
jo.getString("referendumSubtitle"),
jo.getString("referendumUrl"));
refList.add(refs);
}
adapter = new RefRvAdapter(refList, getApplicationContext());
myrv.setAdapter(adapter);
} catch(JSONException e){
e.printStackTrace();
}
}
}, new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error){
Log.e("Volley", error.toString());
progressDialog.dismiss();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
Here is my code for the adapter class:
public class RefRvAdapter extends RecyclerView.Adapter<RefRvAdapter.MyViewHolder>{
private Context context;
private List<Refs> refsList;
public RefRvAdapter(){}
public RefRvAdapter(List<Refs> refList, Context context){
this.refsList = refList;
this.context = context;
}
#NonNull
#Override
public RefRvAdapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view;
LayoutInflater mInflater = LayoutInflater.from(context);
view = mInflater.inflate(R.layout.ref_card, viewGroup, false);
final MyViewHolder viewHolder = new MyViewHolder(view);
viewHolder.view_containers.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent (context, SingleReferendum.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("referendumTitle", refsList.get(viewHolder.getAdapterPosition()).getRefTitle());
i.putExtra("referendumSubtitle", refsList.get(viewHolder.getAdapterPosition()).getRefSub());
i.putExtra("referendumUrl", refsList.get(viewHolder.getAdapterPosition()).getRefUrl());
context.startActivity(i);
}
});
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RefRvAdapter.MyViewHolder myViewHolder, int i) {
myViewHolder.refTitle.setText(refsList.get(i).getRefTitle());
myViewHolder.refSub.setText(refsList.get(i).getRefSub());
myViewHolder.refUrl.setText(refsList.get(i).getRefUrl());
}
#Override
public int getItemCount() {
return refsList.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder{
TextView refTitle, refSub, refUrl;
LinearLayout view_containers;
public MyViewHolder(View itemView){
super(itemView);
refTitle = itemView.findViewById(R.id.ref_title);
refSub = itemView.findViewById(R.id.ref_sub);
refUrl = itemView.findViewById(R.id.ref_url);
view_containers = itemView.findViewById(R.id.view_container_ref);
}
}
}
The app parses all the data just fine. I just want to make the url clickable. When the user clicks it, the pdf opens. Do I add the code in the RecyclerView adapter class, or in the main activity?
ANSWER: Edit the onBindViewHolder method like so.
#Override
public void onBindViewHolder(#NonNull final RefRvAdapter.MyViewHolder myViewHolder, int i) {
myViewHolder.refTitle.setText(refsList.get(i).getRefTitle());
myViewHolder.refSub.setText(refsList.get(i).getRefSub());
myViewHolder.refUrl.setText(refsList.get(i).getRefUrl());
myViewHolder.view_containers.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent (context, SingleReferendum.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("referendumTitle", refsList.get(myViewHolder.getAdapterPosition()).getRefTitle());
i.putExtra("referendumSubtitle", refsList.get(myViewHolder.getAdapterPosition()).getRefSub());
i.putExtra("referendumUrl", refsList.get(myViewHolder.getAdapterPosition()).getRefUrl());
context.startActivity(i);
}
});
myViewHolder.refUrl.setOnClickListener(new View.OnClickListener(){
#Override //handle pdf clicks
public void onClick(View view) {
String refUrl = refsList.get(myViewHolder.getAdapterPosition()).getRefUrl();
Intent intent = new Intent (Intent.ACTION_VIEW, Uri.parse(refUrl));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
}
If I didn't misunderstand what you mean,just modify methods:onCreateViewHolder and onBindViewHolder to:
#NonNull
#Override
public RefRvAdapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view;
LayoutInflater mInflater = LayoutInflater.from(context);
view = mInflater.inflate(R.layout.ref_card, viewGroup, false);
final MyViewHolder viewHolder = new MyViewHolder(view);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RefRvAdapter.MyViewHolder myViewHolder, int i) {
myViewHolder.refTitle.setText(refsList.get(i).getRefTitle());
myViewHolder.refSub.setText(refsList.get(i).getRefSub());
myViewHolder.refUrl.setText(refsList.get(i).getRefUrl());
myViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent (context, SingleReferendum.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("referendumTitle", refsList.get(myViewHolder.getAdapterPosition()).getRefTitle());
i.putExtra("referendumSubtitle", refsList.get(myViewHolder.getAdapterPosition()).getRefSub());
i.putExtra("referendumUrl", refsList.get(myViewHolder.getAdapterPosition()).getRefUrl());
context.startActivity(i);
}
}
myViewHolder.refUrl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String refUrl = refsList.get(myViewHolder.getAdapterPosition()).getRefUrl();
//open pdf here.
}
});
}
Try it and feedback if it's OK.
Hi I wanna set my recycleview clickable . for example when click on recycleview's each view toast its parameters (like its name) . please don't rank negative I'm a newbie.
this is my mainclass to show recycleview
public class HomeFragment2 extends Fragment {
List<GetDataAdapter> GetDataAdapter1;
RecyclerView recyclerView;
RecyclerView.LayoutManager recyclerViewlayoutManager;
RecyclerView.Adapter recyclerViewadapter;
ProgressBar progressBar;
View view ;
int RecyclerViewItemPosition ;
ArrayList<String> ImageTitleNameArrayListForClick;
String ID = "id";
String SECTION = "section";
String TIME = "time";
String NAME = "name";
Button button;
JsonArrayRequest jsonArrayRequest ;
RequestQueue requestQueue ;
public static HomeFragment2 newInstance() {
return new HomeFragment2();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_home2, container, false);
GetDataAdapter1 = new ArrayList<>();
recyclerView =v.findViewById(R.id.recyclerView1);
progressBar =v.findViewById(R.id.progressBar1);
button =v.findViewById(R.id.button);
recyclerView.setHasFixedSize(true);
recyclerViewlayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(recyclerViewlayoutManager);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressBar.setVisibility(View.VISIBLE);
JSON_DATA_WEB_CALL();
}
});
return v;
}
public void JSON_DATA_WEB_CALL(){
jsonArrayRequest = new JsonArrayRequest(URLS.recycle_fetch,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
progressBar.setVisibility(View.GONE);
JSON_PARSE_DATA_AFTER_WEBCALL(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(jsonArrayRequest);
}
public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array){
for(int i = 0; i<array.length(); i++) {
GetDataAdapter GetDataAdapter2 = new GetDataAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataAdapter2.setId(json.getInt(ID));
GetDataAdapter2.setName(json.getString(SECTION));
GetDataAdapter2.setSubject(json.getString(TIME));
GetDataAdapter2.setPhone_number(json.getString(NAME));
// Adding image title name in array to display on RecyclerView click event.
} catch (JSONException e) {
e.printStackTrace();
}
GetDataAdapter1.add(GetDataAdapter2);
}
recyclerViewadapter = new RecyclerViewAdapter(GetDataAdapter1, getActivity());
recyclerView.setAdapter(recyclerViewadapter);
}
}
and my adapter
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
Context context;
List<GetDataAdapter> getDataAdapter;
public RecyclerViewAdapter(List<GetDataAdapter> getDataAdapter, Context context){
super();
this.getDataAdapter = getDataAdapter;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview, parent, false);
cardView = (CardView) view.findViewById(R.id.mainCard);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
GetDataAdapter getDataAdapter1 = getDataAdapter.get(position);
holder.Id.setText(getDataAdapter1.getName());
holder.Section.setText(String.valueOf(getDataAdapter1.getId()));
holder.Time.setText(getDataAdapter1.getPhone_number());
holder.Name.setText(getDataAdapter1.getSubject());
cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do something
}
});
}
#Override
public int getItemCount() {
return getDataAdapter.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
public TextView Id;
public TextView Section;
public TextView Time;
public TextView Name;
public ViewHolder(View itemView) {
super(itemView);
Id =itemView.findViewById(R.id.textView2);
Section =itemView.findViewById(R.id.textView4);
Time =itemView.findViewById(R.id.textView6);
Name =itemView.findViewById(R.id.textView8);
}
}
}
any body can help me? i wanna get cardview's parameters when click each of them .
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
Context context;
List<GetDataAdapter> getDataAdapter;
public RecyclerViewAdapter(List<GetDataAdapter> getDataAdapter, Context context){
super();
this.getDataAdapter = getDataAdapter;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview, parent, false);
//////////////////////////////////here you define your layout you wanna be clicked/////////////////////////
cardView = (CardView) view.findViewById(R.id.mainCard);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
GetDataAdapter getDataAdapter1 = getDataAdapter.get(position);
holder.Id.setText(getDataAdapter1.getName());
holder.Section.setText(String.valueOf(getDataAdapter1.getId()));
holder.Time.setText(getDataAdapter1.getPhone_number());
holder.Name.setText(getDataAdapter1.getSubject());
///////////////////////////////// and here you add your on click listener////////////////////////////////
cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do something
}
});
}
#Override
public int getItemCount() {
return getDataAdapter.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
public TextView Id;
public TextView Section;
public TextView Time;
public TextView Name;
public ViewHolder(View itemView) {
super(itemView);
Id =itemView.findViewById(R.id.textView2);
Section =itemView.findViewById(R.id.textView4);
Time =itemView.findViewById(R.id.textView6);
Name =itemView.findViewById(R.id.textView8);
}
}
}
My recyclerview is not populating inside fragment. I am getting proper response from volley. I have parsed the JSON in arraylist in proper format only problem is that recyclerview is not populating.
MyFragment.java
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_undekha_tadka, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
myVolleyOperation(view);
return view;
}
private void myVolleyOperation(View v) {
volleySingleton = VolleySingleton.getInstance();
requestQueue = volleySingleton.getRequestQueue();
String url = "http://abcd.com/undekha.html";
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
jsonParsing(response);
Toast.makeText(getContext(), response, Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(), "ERROR\n" + error.toString(), Toast.LENGTH_SHORT).show();
}
});
requestQueue.add(stringRequest);
recyclerViewAdapter = new RecyclerViewAdapter(undekhaList, v.getContext());
layoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(recyclerViewAdapter);
}
RecyclerViewAdapter.java
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.RecyclerViewHolder> {
ArrayList<UndekhaModel> myArrayList = new ArrayList<>();
Context context;
VolleySingleton volleySingleton;
ImageLoader imageLoader;
public RecyclerViewAdapter(ArrayList<UndekhaModel> myArrayList, Context context) {
this.myArrayList = myArrayList;
this.context = context;
volleySingleton = VolleySingleton.getInstance();
imageLoader = volleySingleton.getImageLoader();
}
#Override
public RecyclerViewAdapter.RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_row, parent, false);
RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(view, context, myArrayList);
return recyclerViewHolder;
}
#Override
public void onBindViewHolder(final RecyclerViewAdapter.RecyclerViewHolder holder, int position) {
UndekhaModel undekhaModel = myArrayList.get(position);
holder.title.setText(undekhaModel.getTitle());
String loadUrl = "http://img.youtube.com/vi/" + undekhaModel.getId() + "/0.jpg";
if (loadUrl!=null){
imageLoader.get(loadUrl, new ImageLoader.ImageListener() {
#Override
public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
holder.thumbnail.setImageBitmap(response.getBitmap());
}
#Override
public void onErrorResponse(VolleyError error) {
holder.thumbnail.setImageResource(R.mipmap.ic_launcher);
}
});
}
}
#Override
public int getItemCount() {
return myArrayList.size();
}
public static class RecyclerViewHolder extends RecyclerView.ViewHolder {
TextView title;
ImageView thumbnail;
ArrayList<UndekhaModel> modelArrayList = new ArrayList<>();
Context context;
public RecyclerViewHolder(View itemView, final Context ctx, final ArrayList<UndekhaModel> modelArrayList) {
super(itemView);
this.context = ctx;
this.modelArrayList = modelArrayList;
title = (TextView) itemView.findViewById(R.id.tvTitle);
thumbnail = (ImageView) itemView.findViewById(R.id.ivShow);
}
}
}
Your method jsonParsing() needs to populate data for your RecyclerViewAdapter, needs to notify of the update and the adapter needs to return the correct count of items it is managing. Right now its getItemCount() is always returning 0, so the RecyclerView does not think there is anything to show.
Same issue than here
https://stackoverflow.com/a/35802948/2144418
Try setting the adapter before the layout manager
Change the last two lines on myVolleyOperation to this
recyclerView.setAdapter(recyclerViewAdapter);
recyclerView.setLayoutManager(layoutManager);
I am using RecyclerView to display my products, problem is when if I select the first products and scroll down to the end of list I see different products selected and when i scroll back to top of list the first item is not selected.
My Adapter
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyViewHolder> {
String u = "http://192.185.52.231/~sabby070/hyype/";
Context context1;
private java.util.List<ProductDetails> List;
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.view_list, parent, false);
return new MyViewHolder(itemView);
}
public RecyclerAdapter(List<ProductDetails> DataList, FragmentActivity activity) {
this.List = DataList;
context1 = activity;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView Likecount;
public ImageView Image;
public ImageView Imagelike, ImageUnlike;
public MyViewHolder(View view) {
super(view);
Likecount = (TextView) view.findViewById(R.id.textView_itemPrice);
Image = (ImageView) view.findViewById(R.id.imageView_imgtosold);
Imagelike = (ImageView)view.findViewById(R.id.Like_Button);
ImageUnlike = (ImageView)view.findViewById(R.id.UnLike_Button);
}
}
#Override
public void onBindViewHolder(final RecyclerAdapter.MyViewHolder holder, final int position) {
final ProductDetails detail = List.get(position);
holder.Likecount.setText(detail.getLikeCount());
Glide.with(context1).load(u+detail.getImage()).override(600, 200).diskCacheStrategy(DiskCacheStrategy.ALL).into(holder.Image);
holder.Image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context1, ""+position, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context1, Buy_Product.class);
intent.putExtra("Product Name",detail.getLikeCount());
intent.putExtra("Product Image",detail.getImage());
context1.startActivity(intent);
}
});
holder.Imagelike.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (holder.Imagelike.getVisibility()==View.VISIBLE)
{
holder.Imagelike.setVisibility(View.GONE);
holder.ImageUnlike.setVisibility(View.VISIBLE);
}
}
});
holder.ImageUnlike.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (holder.ImageUnlike.getVisibility()==View.VISIBLE)
{
holder.Imagelike.setVisibility(View.VISIBLE);
holder.ImageUnlike.setVisibility(View.GONE);
}
}
});
}
#Override
public int getItemCount() {
return List.size();
}
}
My class
public class Men_Fragment extends Fragment {
static String URL = "http://192.185.52.231/~sabby070/hyype/index.php?action=timeline&user_id=53&post_category=timeline";
private List<ProductDetails> DataList = new ArrayList<>();
private RecyclerView recyclerView;
private RecyclerAdapter rAdapter;
String img;
String a;
Boolean list[];
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_men_, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.men_recycler_view);
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(response);
for (int i = 0; i < response.length(); i++) {
JSONObject obj = jsonObject.getJSONObject(String.valueOf(i));
a = obj.getString("like_count");
img = obj.getString("video_thumb");
final ProductDetails details = new ProductDetails(a, img);
DataList.add(details);
rAdapter = new RecyclerAdapter(DataList, getActivity());
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 2);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(rAdapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "" + error, Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
return view;
}
}
You have to take List(with boolean) and store selected values in that list and then use those values in onBindView()
In your ProductDetails class add a field boolean selected;
In your onClick() add List.get(position).setSelected(!List.get(position).isSelected()); to check/uncheck as needed.
Finaly in your onBindViewHolder(...) add
if(List.get(position).isSelected()){
holder.Imagelike.setVisibility(View.VISIBLE);
}else{
holder.ImageUnlike.setVisibility(View.GONE);
}