how to sent json value to module? - android

i responsed json object from api and i tried to send the response to the module using setter then to the Recyclerview adapter but its not working
This is my fragment
public class ListViewActivityFragment extends Fragment {
List<AppShowModule> appShowModule;
RecyclerView AppRecyclerView;
RecyclerView.LayoutManager AppRecyclerViewlayoutManager;
RecyclerView.Adapter AppRecyclerViewadapter;
String jsonUrl = "https://itunes.apple.com/jo/rss/topfreeapplications/limit=50/json";
TextView text;
Context context;
RequestQueue requestQueue;
public ListViewActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_list_view, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
appShowModule = new ArrayList<>();
AppRecyclerView = (RecyclerView) getView().findViewById( R.id.AppRecyclerView );
AppRecyclerView.setHasFixedSize( true );
AppRecyclerView.setLayoutManager( AppRecyclerViewlayoutManager );
JsonAppShowData();}
public void JsonAppShowData() {
final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest( jsonUrl, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONObject("feed").getJSONArray( "entry" );
AppShowModule appShowModule111 = new AppShowModule();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json1 = jsonArray.getJSONObject( i ).getJSONObject("im:name");
String name = response.getJSONObject("feed").getJSONArray("entry").getJSONObject(i).getJSONObject("im:name").getString("label").toString();
appShowModule111.setAppName(name);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e( "LOG", error.toString() );
}
} );
requestQueue = Volley.newRequestQueue( getContext() );
requestQueue.add(jsonObjectRequest);
AppRecyclerView.setLayoutManager(new LinearLayoutManager(context));
AppRecyclerViewadapter = new ListViewAdapter(appShowModule,getContext() );
AppRecyclerView.setAdapter(AppRecyclerViewadapter);
}
}
And this is my adapter
public class ListViewAdapter extends RecyclerView.Adapter<ListViewAdapter.ViewHolder> {
Context context;
List<AppShowModule> getDataAdapter;
public ListViewAdapter(List<AppShowModule> 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.appitem, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position)
{
final AppShowModule getDataAdapter1 = getDataAdapter.get( position );
holder.NameTextView.setText( getDataAdapter1.getAppName() );
Picasso.with( context ).load( getDataAdapter1.getAppImageUrl() ).into( holder.imgPost );
}
#Override
public int getItemCount() {
return getDataAdapter.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
public TextView NameTextView;
public ImageView imgPost;
LinearLayout lnrLayout;
public ViewHolder(View itemView) {
super(itemView);
NameTextView = (TextView) itemView.findViewById(R.id.appName);
imgPost = (ImageView) itemView.findViewById(R.id.appImage);
lnrLayout = (LinearLayout)itemView.findViewById(R.id.lnrLayout);
}
}
}
And this is my module
public class AppShowModule
{
private String appName;
private String appImageUrl;
public String getAppName() {
return appName;}
public void setAppName(String appName) {
this.appName = appName;}
public String getAppImageUrl() {
return appImageUrl;}
public void setAppImageUrl(String appImageUrl) {
this.appImageUrl = appImageUrl;}
}

I think you should not initialize your adapter when you get a response from the web service. Do it on activity create and when you get your data, update the adapter.

Related

why recycler view not show when call from API

I want to show information that call from API to recycler view in fragment, but the recycler view doesnt show the information. The Api show GET method and need to display the list in Recycler View.
This is my Model
public class PhoneModel {
public PhoneModel() {
}
private int amount;
private String amount_display;
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
public String getAmount_display() {
return amount_display;
}
public void setAmount_display(String amount_display) {
this.amount_display = amount_display;
}
}
This is my Adapter. i just want to show one information only in Recycler View.
public class PhoneAdapter extends RecyclerView.Adapter<PhoneAdapter.PhoneViewHolder> {
private ArrayList<PhoneModel> listItems;
private Context context;
LayoutInflater inflater;
public PhoneAdapter(Context context) {
this.listItems = new ArrayList<>();
this.context = context;
inflater = LayoutInflater.from(context);
}
#Override
public PhoneViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = inflater.from(parent.getContext())
.inflate(R.layout.view_holder_phone,parent,false);
return new PhoneViewHolder(v);
}
#Override
public void onBindViewHolder(PhoneViewHolder holder, int position) {
holder.test.setText(listItems.get(position).getAmount_display());
}
#Override
public int getItemCount() {
return listItems.size();
}
public void add(PhoneModel model) {
listItems.add(model);
notifyDataSetChanged();
}
public void clear() {
listItems.clear();
notifyDataSetChanged();
}
public class PhoneViewHolder extends RecyclerView.ViewHolder {
private TextView test;
private TextView currentBal;
public PhoneViewHolder(View itemView) {
super(itemView);
test = itemView.findViewById(R.id.tv_deposit);
currentBal = itemView.findViewById(R.id.tv_current_bal);
}
}
}
This is my Activity which i connect with Phone Model and Phone Adapter.
public class HistoryFragment extends Fragment {
private final static String TAG = HistoryFragment.class.getSimpleName();
private PhoneAdapter phoneAdapter;
private RecyclerView recyclerView;
public HistoryFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_history, container, false);
recyclerView = view.findViewById(R.id.recycler_history);
LinearLayoutManager mLinearLayoutManager = new LinearLayoutManager(getActivity(),
LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(mLinearLayoutManager);
phoneAdapter = new PhoneAdapter(getContext());
recyclerView.setAdapter(phoneAdapter);
phoneHistory();
return view;
}
private void phoneHistory(){
StringRequest request = new StringRequest(
Request.Method.GET,
ServerApi.URL_PHONE,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Gson gson = new GsonBuilder().create();
JSONObject jsonObject = null;
if(response != null) {
try {
jsonObject = new JSONObject(response);
PhoneModel phoneModel = gson.fromJson(jsonObject.getJSONObject("value").toString(), PhoneModel.class);
phoneAdapter.add(phoneModel);
} catch (JSONException e) {
Log.d(TAG, e.getLocalizedMessage());
}
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), error.getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
}
) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/x-www-form-urlencoded");
return headers;
}
};
Volley.newRequestQueue(getContext()).add(request);
}
}
Try this
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_history, container, false);
recyclerView = view.findViewById(R.id.recycler_history);
LinearLayoutManager mLinearLayoutManager = new
LinearLayoutManager(getActivity(),
LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(mLinearLayoutManager);
phoneHistory();
phoneAdapter = new PhoneAdapter(getContext());
recyclerView.setAdapter(phoneAdapter);
return view;
}
You getting empty data because in adapter constructor you creating new arraylist().
Change this:
public PhoneAdapter(Context context) {
this.listItems = new ArrayList<>();
this.context = context;
inflater = LayoutInflater.from(context);
}
To
public PhoneAdapter(Context context,Arraylist list) {
this.listItems = list;
this.context = context;
inflater = LayoutInflater.from(context);
}
also change in fragment:
phoneAdapter = new PhoneAdapter(getContext());
recyclerView.setAdapter(phoneAdapter,list);
and in phoneHistory() method
if(response != null) {
try {
jsonObject = new JSONObject(response);
PhoneModel phoneModel = gson.fromJson(jsonObject.getJSONObject("value").toString(), PhoneModel.class);
phoneModel .add(phoneModel);
list.add(phoneModel )
phoneAdapter.notifyDataSetChanged()
} catch (JSONException e) {
Log.d(TAG, e.getLocalizedMessage());
}
}
Hope it will help you!!

set onclick for recycleview each view and toast its parameter

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);
}
}
}

error when passing list of image to Picasso

I am parsing a list of image from json data and i need to add the image to Picasso then display it based on the position where the user has clicked but I have a this error:
FATAL EXCEPTION: main
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)
at com.example.moayed.appshow.Adapters.ImageListAdapter.onBindViewHolder(ImageListAdapter.java:41)
at com.example.moayed.appshow.Adapters.ImageListAdapter.onBindViewHolder(ImageListAdapter.java:18)
Class
public class ImageListFragment extends Fragment {
List<AppShowModule> appShowModules;
List<AppShowModule> imagesModule;
RecyclerView AppRecyclerView;
RecyclerView.Adapter imageRecyclerViewadapter;
List<String> imageUrls;
String feedKey = "feed";
String entryKey = "entry";
String imageKey = "im:image";
String labelKey = "label";
String jsonUrl = "https://itunes.apple.com/jo/rss/topfreeapplications/limit=50/json";
RequestQueue requestQueue;
private RecyclerView.LayoutManager mLayoutManager;
public ImageListFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_image_list, container, false);
}
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
AppRecyclerView = (RecyclerView) getView().findViewById(R.id.imageRecyclerView);
imagesModule = new ArrayList<>();
appShowModules = new ArrayList<>();
imageUrls = new ArrayList<>();
JsonAppShowData();
}
public void JsonAppShowData() {
final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest( jsonUrl, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) { try {
JSONArray jsonArray = response.getJSONObject(feedKey).getJSONArray( entryKey );
AppShowModule appShowModule = new AppShowModule();
int x = appShowModule.getId();
for (int i = 0 ; i<jsonArray.length() ;i++)
{
JSONArray imageArray = response.getJSONObject(feedKey).getJSONArray(entryKey).getJSONObject(x).getJSONArray(imageKey);
for (int j = 0; j < imageArray.length(); j++) {
String image = imageArray.getJSONObject(x).getString(labelKey).toString();
imageUrls.add(image);
appShowModule.setAllimage(imageUrls);
appShowModules.add(appShowModule);
}}
imageRecyclerViewadapter = new ImageListAdapter(appShowModules, getContext(), imageUrls);
AppRecyclerView.setAdapter(imageRecyclerViewadapter);
} catch (JSONException e) {
e.printStackTrace();
}}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e( "LOG", error.toString() );
}
} );
requestQueue = Volley.newRequestQueue( getContext() );
requestQueue.add(jsonObjectRequest);
mLayoutManager = new GridLayoutManager( getContext().getApplicationContext(),3);
AppRecyclerView.setLayoutManager(mLayoutManager); }}
Adapter
public class ImageListAdapter extends RecyclerView.Adapter<ImageListAdapter.ViewHolder> {
List<AppShowModule> appShowModules;
List<String> imageUrl;
AppShowModule appShowModule;
Context context;
public ImageListAdapter(List<AppShowModule> appShowModules, Context context ,List<String>imageUrls
){
super();
this.imageUrl =imageUrls;
this.appShowModules = appShowModules;
this.context = context;}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from( parent.getContext() ).inflate( R.layout.imagelayout, parent,false );
ViewHolder viewHolder = new ViewHolder( v );
return viewHolder;}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
AppShowModule appShowModule = new AppShowModule();
Picasso.with(context).load(appShowModule.getAllimage().get(position)).into(holde r.appImage);
}
public int getItemCount() {
return imageUrl.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
public ImageView appImage;
public ViewHolder(View itemView) {
super(itemView);
appImage = (ImageView) itemView.findViewById( R.id.appImage);
}}}
The issue is in your onBinderView method where you are initializing AppShowModule by creating new instance and then after you are trying to access data from it which is already declared as new and is empty already.
public void onBindViewHolder(ViewHolder holder, int position) {
AppShowModule appShowModule = new AppShowModule();
Picasso.with(context).load(appShowModule.getAllimage().get(position)).into(holde r.appImage);
}
Change the above code as below:
public void onBindViewHolder(ViewHolder holder, int position) {
AppShowModule appShowModule = appShowModules.get(position);
//Get the position from the list of your `appShowModules` and then try to access image from `AppShowModule`.
Picasso.with(context).load(appShowModule.getAllimage().get(position)).into(holde r.appImage);
}
Hope this will help you.
Let me know if any query.

Android Recycler View

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);
}

I need to show some details from my web service to recyclerview but Its not work

This is my Fragment class in here I can't create instance of Person class. While try am to create instance of Person class, showing error as Person(String,String) in Person can not be applied to zero.
public class MainActivityFragment extends Fragment {
private final List<Person> mPersonList = new ArrayList<>();
public MainActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
Context context = getActivity();
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
LinearLayoutManager layoutManager = new LinearLayoutManager(context);
recyclerView.setLayoutManager(layoutManager);
final RVAdapter rvAdapter = new RVAdapter(mPersonList);
recyclerView.setAdapter(rvAdapter);
RequestQueue requestQueue = Volley.newRequestQueue(context);
String url = "http://192.16.1.100/api/persons";
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = response.getJSONObject(i);
Person person=new Person();
person.phone_name = jsonObject.getString("name");
person.phone_price = jsonObject.getString("dddd");
mPersonList.add(i, person);
}
rvAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
}
});
requestQueue.add(jsonArrayRequest);
return view;
} }
My Person class
class Person {
public String phone_name;
public String phone_price;
Person(String phone_name, String phone_price) {
this.phone_name = phone_name;
this.phone_price = phone_price;
} }
My Adapter class is
public class RVAdapter extends
RecyclerView.Adapter<RVAdapter.PersonViewHolder> {
List<Person> persons;
RVAdapter(List<Person> persons) {
this.persons = persons;
}
#Override
public PersonViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview,
parent, false);
PersonViewHolder pvh = new PersonViewHolder(v);
return pvh;
}
#Override
public void onBindViewHolder(PersonViewHolder holder, int position) {
holder.phoneName.setText(persons.get(position).phone_name);
holder.phonePrice.setText(persons.get(position).phone_price);
}
#Override
public int getItemCount() {
if (persons != null) {
return persons.size();
}
return 0;
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
public static class PersonViewHolder extends RecyclerView.ViewHolder {
CardView cv;
TextView phoneName;
TextView phonePrice;
PersonViewHolder(View itemView) {
super(itemView);
cv = (CardView) itemView.findViewById(R.id.card_view);
phoneName = (TextView) itemView.findViewById(R.id.phone_name);
phonePrice = (TextView) itemView.findViewById(R.id.phone_price);
}
} }
please try to change the following things
String phone_name = jsonObject.getString("name"
String phone_price = jsonObject.getString("dddd");
Person person=new Person(phone_name,phone_price);

Categories

Resources