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.
Related
I'm trying to pass a couple of values from the activity "Example" to the other activity "MemberExample.class"
I know this seems like an easy question, that has been answered many times before, but as shown in the code below and I will try to explain, it doesn't seem to be as easy as it looks.
Below is the first activity code that I'm trying to pass but it gets the "mImagesUrl", "mName", "mParties" from a recycler view adapter. I'm not sure where in either class I am meant to put the "putIntent" and "getExtras" methods. Do I put them in the RecyclerView Adapter or the activity class?
Example.class
public class Example extends AppCompatActivity {
private ArrayList<String> mNames = new ArrayList<>();
private ArrayList<String> mParties = new ArrayList<>();
private ArrayList<String> mImageUrls = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.example);
getImages();
}
private void getImages() {
mImageUrls.add("https://data.oireachtas.ie/ie/oireachtas/member/id/Kathleen-Funchion.D.2016-10-03/image/large");
mNames.add("Kathleen Funchion");
mParties.add("Sinn Féin");
mImageUrls.add("https://data.oireachtas.ie/ie/oireachtas/member/id/John-Paul-Phelan.S.2002-09-12/image/large");
mNames.add("John Paul Phelan");
mParties.add("Fine Gael");
initExampleRV();
}
private void initExampleRV() {
LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
RecyclerView recyclerView = findViewById(R.id.rv_Example);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(this, MemberExample.class);
//?????????????????????
}
});
ClareMembersRecyclerView adapter = new ClareMembersRecyclerView(this, mNames, mParties, mImageUrls);
recyclerView.setAdapter(adapter);
}
}
Adapter.class
public class RecyclerView extends RecyclerView.Adapter<ClareMembersRecyclerView.ViewHolder>{
private static final String TAG = "ClareMembersRV";
//vars
private ArrayList<String> mNames = new ArrayList<>();
private ArrayList<String> mParties = new ArrayList<>();
private ArrayList<String> mImageUrls = new ArrayList<>();
private Context mContext;
public RecyclerView(Context context, ArrayList<String> names, ArrayList<String> parties, ArrayList<String> imageUrls){
mNames = names;
mParties = parties;
mImageUrls = imageUrls;
mContext = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
Log.d(TAG, "onCreateViewHolder: called.");
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_members_clare, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
Log.d(TAG, "onBindViewHolder: called.");
Glide.with(mContext)
.asBitmap()
.load(mImageUrls.get(position))
.into(holder.image);
holder.name.setText(mNames.get(position));
holder.party.setText(mParties.get(position));
holder.image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: clicked on an image" + mNames.get(position));
Toast.makeText(mContext, "Profile: " + mNames.get(position), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(mContext, MembersMapDetailed.class);
intent.putExtra(mNames.get(position),mParties,mImageUrls);
}
});
}
#Override
public int getItemCount() {
return mImageUrls.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
CircleImageView image;
TextView name;
TextView party;
public ViewHolder(View itemView) {
super(itemView);
image = itemView.findViewById(R.id.imgClareCircle);
name = itemView.findViewById(R.id.tvClareName);
party = itemView.findViewById(R.id.tvClareParty);
}
}
If you want to start a new activity and pass them these values wherever user click on recycle view, you can do it like this:
recyclerView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(this, MemberExample.class);
intent.putExtra("EXTRA_KEY_NAMES", mNames);
intent.putExtra("EXTRA_KEY_PARTIES", mParties);
intent.putExtra("EXTRA_KEY_IMAGES", mImageUrls);
startActivity(intent);
}
If you want to start a new activity and pass values, based on the item that the user clicked in the previous activity you can use onItemClickListener. I think that it is more useful and it is what you want to do, but maybe I am wrong.:
recyclerView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
Intent intent = new Intent(this, MemberExample.class);
intent.putExtra("EXTRA_KEY_NAME", mNames.get(position);
intent.putExtra("EXTRA_KEY_PARTY", mParties.get(position));
intent.putExtra("EXTRA_KEY_IMAGE", mImageUrls.get(position));
startActivity(intent);
}
To get these values from intent in your new activity you need to write this part of code in your MemberExample.class:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
Intent intent = getIntent();
ArrayList<String> mNames = intent.getStringArrayListExtra("EXTRA_KEY_NAMES");
ArrayList<String> mParties = intent.getStringArrayListExtra("EXTRA_KEY_PARTIES");
ArrayList<String> mImageUrls = intent.getStringArrayListExtra("EXTRA_KEY_IMAGES");
// Or in second proposed by me solution (with passing single item):
//String mName = intent.getStringExtra("EXTRA_KEY_NAME");
//String mParty = intent.getStringExtra("EXTRA_KEY_PARTY");
//String mImage = intent.getStringExtra("EXTRA_KEY_IMAGE");
}
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);
}
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");
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);
}
This is my code file.
public class FragmentOfferList extends ListFragment {
private RecyclerView recyclerView;
private String TAG = FragmentOfferList.class.getSimpleName();
private static final String endpoint = "http://example.com/offer/offers.json";
private List<Offer> offers = new ArrayList<>();
private ProgressDialog pDialog;
RecyclerView.Adapter adapter;
public FragmentOfferList() {
}
public static FragmentOfferList newInstance(int num) {
FragmentOfferList f = new FragmentOfferList();
// Supply num input as an argument.
Bundle args = new Bundle();
args.putInt("num", num);
f.setArguments(args);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pDialog = new ProgressDialog(getActivity());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.recycler_list, container, false);
recyclerView = (RecyclerView) v.findViewById(R.id.recycler_view);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
adapter = new MyAdapter(offers, getActivity());
recyclerView.setAdapter(adapter);
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
Offer offer = Utility.getOffers().get(position);
Intent intent = new Intent(getActivity(), ActivityProductList.class);
intent.putExtra("query", offer.getQuery());
startActivity(intent);
//startActivity(new Intent(getActivity(), ActivityProductList.class));
}
#Override
public void onLongClick(View view, int position) {
}
}));
if (Utility.getOffers().size() == 0){
fetchOffers();
}
else{
Utility.displayToast("here");
offers = Utility.getOffers();
adapter.notifyDataSetChanged();
}
return v;
}
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private List<Offer> offers;
private Context context;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title, year, offer;
ImageView imageView;
public MyViewHolder(View view) {
super(view);
imageView = (ImageView) view.findViewById(R.id.thumbnail);
title = (TextView) view.findViewById(R.id.title);
offer = (TextView) view.findViewById(R.id.offer);
}
}
public MyAdapter(List<Offer> offers, Context context) {
this.offers = offers;
this.context = context;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_offer, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Offer offer = offers.get(position);
holder.title.setText(offer.getName());
holder.offer.setText(offer.getOffer());
Glide.with(context).load(String.valueOf(offer.getUrl()))
.error(R.drawable.placeholder)
.thumbnail(0.5f)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(holder.imageView);
}
#Override
public int getItemCount() {
return offers.size();
}
}
private void fetchOffers() {
pDialog.setMessage("Downloading json...");
pDialog.show();
JsonArrayRequest req = new JsonArrayRequest(endpoint,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
pDialog.hide();
offers.clear();
for (int i = 0; i < response.length(); i++) {
try {
JSONObject object = response.getJSONObject(i);
Offer offer = new Offer();
offer.setOffer(object.getString("offer"));
offer.setName(object.getString("name"));
offer.setUrl(object.getString("url"));
offer.setQuery(object.getString("query"));
offers.add(offer);
} catch (JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
}
}
Utility.setOffers(offers);
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error: " + error.getMessage());
pDialog.hide();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
}
}
First time when Utility.getoffers().size() is 0, it fetches data, save it in Utility.setOffers(offers) and display on screen as expected. But next time (go back and to same activity), Utility.getoffers().size() is not 0 , i got data directly from Utility.getBrands().
After that i called adapter.notifyDataSetChaned(), but it is not working. Not working menas even though data sise is more than 0 but no data rendering on screen?
What is wrong here? am i missing anything?
You are not updating your offers list, but rather replacing it with another list that your adapter has no reference to. To fix this you can do the following:
offers.clear();
offers.addAll(Utility.getOffers());
adapter.notifyDataSetChanged();