Showing Json response in `RecyclerView` using `CardView` in Android Studio in Java - android

I have to show my JSON response in a recycler view using card view with use of volley library .My JSON response is something like
{
"id": 87,
"parent_id": 0,
"shipping": {
"first_name": "JPbrajesh",
"last_name": "kumar",
},
"payment_method": "COD",
"line_items": [
{
"id": 16,
"name": "abc",
"price": 85
},
{
"id": 17,
"name": "zxc",
"price": 38
},
{
"id": 18,
"name": "asd",
"price": 136
}
],
"tax_lines": [],
"shipping_lines": [
{
"id": 19,
}
],
"fee_lines": [],
"_links": {
"self": [
{
"href": "https://example.com/wp-json/wc/v2/orders/87"
}
],
"collection": [
{
"href": "https://example.com/wp-json/wc/v2/orders"
}
]
}
}
`i have to show (Line_items) in a recycler view using volley Library.Please provide some related steps.Thankyou in advance for kind support.

You can first create a class LineItem as model for lineitems.
Then in the activity where you want the data to be used, create a list of line items and fill that list with data from you json object.
create a layout for that lineitem
create an adapter class
declare the adapter and pass it the list and then attach the adapter to the recyclerview.
Something like this:
ProductCategory class
package com.pesabay.pesabay;
/**
* Created by Valentin_Kavakure on 20-Jun-17.
*/
public class ProductCategory {
private int id,niveau,order,premier,nbrProduits;
private String name;
private String image;
public ProductCategory() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ProductCategory(int id) {
this.id = id;
}
public int getId() {
return id;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
Then the layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
app:cardElevation="6dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="5dp">
<ImageView
android:id="#+id/image"
android:layout_width="match_parent"
android:layout_height="150dp"
app:srcCompat="#drawable/bluebg" />
<TextView
android:id="#+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</android.support.v7.widget.CardView>
The adapter:
public class CatGridAdapter extends RecyclerView.Adapter<CatGridAdapter.ViewHolder> {
private List<ProductCategory> categoryList;
private Context context;
private RecyclerViewClickListener recyclerViewClickListener;
public void setRecyclerViewClickListener(RecyclerViewClickListener recyclerViewClickListener) {
this.recyclerViewClickListener = recyclerViewClickListener;
}
public CatGridAdapter(List<ProductCategory> categoryList, Context context) {
this.categoryList = categoryList;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(context).inflate(R.layout.category_grid_layout,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.title.setText(categoryList.get(position).getName());
}
#Override
public int getItemCount() {
return categoryList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView imageView;TextView title;
public ViewHolder(final View itemView) {
super(itemView);
title=(TextView)itemView.findViewById(R.id.title);
imageView=(ImageView)itemView.findViewById(R.id.image);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (recyclerViewClickListener!=null) {
recyclerViewClickListener.recyclerViewItemClicked(v, getAdapterPosition());
}
}
});
}
}
}
And the in my activity:
recyclerView=(RecyclerView)findViewById(R.id.recycler_data);
categoryList=new ArrayList<>();
catGridAdapter=new CatGridAdapter(categoryList,CategoryGrid.this);
pg=(ProgressBar)findViewById(R.id.pg);
catGridAdapter.setRecyclerViewClickListener(new RecyclerViewClickListener() {
#Override
public void recyclerViewItemClicked(View view, int position) {
/* some code*/
});
gridLayoutManager=new GridLayoutManager(CategoryGrid.this,2);
recyclerView.setLayoutManager(gridLayoutManager);
recyclerView.setAdapter(catGridAdapter);

Volley is the library for request the information. When Volley succeed, you get this this JSON response. After that, you need to parse Line_items and pass them to the RecyclerView Adapter.
Hope it helps.

Related

set data into recyclerview using gson in android

I'm trying to set recyclerview data from this type of json response but data is not setting into recylerview
Response:
{
"vehicles": [
{
"id": 1,
"vehicle_number": "gj03fn3235",
"driver_id": 4,
"vehicle_type": "3",
"admindata": {
"id": 7,
"email": "chirag.pwt2#gmail.com"
},
"userdata": {
"id": 4,
"email": "keval.pwt#gmail.com"
}
},
{
"id": 2,
"vehicle_number": "gj03fn3236",
"driver_id": 4,
"vehicle_type": "4",
"admindata": {
"id": 7,
"email": "keval.pwt#gmail.com"
},
"userdata": {
"id": 4,
"email": "keval.pwt#gmail.com"
}
}
]
}
I have created a pojo class of response But my data is not setting into recylerview api call successfully but response print in logcat i tried to set vehicle_number and email in recylerview
Here is my java code:
#Override
public void onSuccess(int
statusCode, Header[] headers, JSONObject
response) {
super.onSuccess(statusCode,
headers, response);
try {
Gson gson = new
GsonBuilder().create();
List<VehicleList> list =
gson.fromJson(response.getJSONArray
("vehicles").toString(), new
TypeToken<List<VehicleList>>() {
}.getType());
Log.e("listsize",""+list.size());
if (list.size() == 0) {
txt_error.setVisibility(View.VISIBLE);
} else {
VehiclesDriverAdpter
acceptedRequestAdapter = new
VehiclesDriverAdpter(list);
recyclerView.setAdapter
(acceptedRequestAdapter);
acceptedRequestAdapter.
notifyDataSetChanged();
}
} catch (JSONException e) {
}
}
My Adapter class:
public class VehiclesDriverAdpter extends
RecyclerView.Adapter<VehiclesDriverAdpter.Holder> {
List<VehicleList> list;
List<Vehicle> list1;
FragmentActivity activity;
public VehiclesDriverAdpter(List<VehicleList> list) {
this.list = list;
}
#Override
public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
return new
Holder(LayoutInflater.from(parent.getContext())
.inflate(R.layout.adapter_vehicle, parent, false));
}
#Override
public void onBindViewHolder(final Holder holder, int position) {
final Vehicle pojo1 = list1.get(position);
Log.e("VehicleNumber",""+pojo1.getVehicleNumber());
holder.txt_vehicle_number.setText(pojo1.getVehicleNumber());
holder.txt_vehicle_driver_name.setText(pojo1.getUserdata().getEmail());
holder.drivername.setText(pojo.getDriver_name());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bundle bundle = new Bundle();
bundle.putSerializable("data", pojo1);
VehiclesInfoFragment detailFragment = new
VehiclesInfoFragment();
detailFragment.setArguments(bundle);
((HomeActivity) holder.itemView.getContext()).
changeFragment(detailFragment, "Passenger Information");
}
});
BookFont(holder, holder.txt_vehilce_type);
BookFont(holder, holder.txt_vehicle_driver_name);
BookFont(holder, holder.txt_vehicle_driver_mobile_no);
MediumFont(holder, holder.txt_vehicle_number);
}
#Override
public int getItemCount() {
return list.size();
}
public class Holder extends RecyclerView.ViewHolder {
TextView txt_vehicle_number, txt_vehilce_type, txt_vehicle_driver_name,
txt_vehicle_driver_mobile_no;
CircleImageView img_driver;
public Holder(View itemView) {
super(itemView);
txt_vehicle_number = (TextView)
itemView.findViewById(R.id.txt_vehicle_number);
txt_vehilce_type = (TextView)
itemView.findViewById(R.id.txt_vehilce_type);
txt_vehicle_driver_name = (TextView)
itemView.findViewById(R.id.txt_vehicle_driver_name);
txt_vehicle_driver_mobile_no = (TextView)
itemView.findViewById(R.id.txt_vehicle_driver_mobile_no);
}
}
public void BookFont(Holder holder, TextView view1) {
Typeface font1 =
Typeface.createFromAsset(holder.itemView.getContext().getAssets(),
"font/AvenirLTStd_Book.otf");
view1.setTypeface(font1);
}
public void MediumFont(Holder holder, TextView view) {
Typeface font =
Typeface.createFromAsset(holder.itemView.getContext().getAssets(),
"font/AvenirLTStd_Medium.otf");
view.setTypeface(font);
}
}
Try this one
YourActivity.this.runOnUiThread(new Runnable() {
public void run() {
setRecyclerData();
}
});
private void setRecyclerData(){
VehiclesDriverAdpter acceptedRequestAdapter = new VehiclesDriverAdpter(list);
recyclerView.setAdapter(acceptedRequestAdapter);
acceptedRequestAdapter.notifyDataSetChanged();
}
I think you have forgotten to add layout manager on your recyclerView add it in code like this
LinearLayoutManager mLayoutManager = new LinearLayoutManager(getBaseContext());
recyclerView.setLayoutManager(mLayoutManager);
VehiclesDriverAdpter acceptedRequestAdapter = new VehiclesDriverAdpter(list);
recyclerView.setAdapter (acceptedRequestAdapter);
You put data to List<VehicleList> list list, but take it from List<Vehicle> list1;
You can try(but only if you always have one item in VehicleList) something like this
public VehiclesDriverAdpter(List<VehicleList> list) {
if(!list.isEmpty()){
this.list1 = list.get(0);
}
}

How to parse this json objects on recyclerview? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I want to show this json in recyclerview. how can I do it?
I just want to list "user" and "exchangeName".
My Json;
{
"events": {
"101": {
"id": "0001",
"type": "exchange",
"user": "BTUser01",
"exchangeName": "BTCTurk",
"transactions": {
"send": "249",
"get": "24.1"
},
"certificate": [
"BTUser01Certificate"
]
},
"102": {
"id": "0002",
"type": "exchange",
"user": "BTUser02",
"exchangeName": "Koinim",
"transactions": {
"send": "300",
"get": "641"
},
"certificate": [
"BTUser02Certificate"
]
},
"103": {
"id": "0003",
"type": "exchange2",
"user": "BTUser03",
"exchangeName": "Koineks",
"transactions": {
"send": "823",
"get": "751"
},
"certificate": [
"BTUser03Certificate"
]
},
"104": {
"id": "0004",
"type": "exchange3",
"user": "BTUser04",
"exchangeName": "Paribu",
"transactions": {
"send": "543",
"get": "3.1"
},
"certificate": [
"BTUser04Certificate"
]
}
}
}
MainActivity;
public class MainActivity extends AppCompatActivity {
TextView ev, ev2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ev = (TextView) findViewById(R.id.ev);
ev2 = (TextView) findViewById(R.id.ev2);
Retrofit retrofit = new Retrofit.Builder().baseUrl("MYAPİ_ADRESS_LINK").addConverterFactory(GsonConverterFactory.create()).build();
Service service = retrofit.create(Service.class);
Call<ResponseBody> call = service.getData();
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(#NonNull Call<ResponseBody> call, #NonNull Response<ResponseBody> response) {
if (response.isSuccessful()) {
String res = null;
if (response.body() != null) {
try {
res = response.body().string();
parse(res);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
#Override
public void onFailure(#NonNull Call<ResponseBody> call, #NonNull Throwable t) {
int a = 0;
}
});
}
Model parse(String str) {
Model model = new Model();
try {
String source = str.replace("\n", "").replace("\t", "").replace("\r", "");
String s = new Gson().toJson(source);
s = s.replace("\\","");
s = s.substring(1,s.length()-1);
JSONObject object = new JSONObject(s).getJSONObject("events");
Iterator<String> iter = object.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
JSONObject value = new JSONObject(String.valueOf(object.get(key)));
model.setExternalId(Integer.parseInt(key));
model.setUser(value.getString("user"));
model.setSend(value.getString("send"));
ev.setText(model.user);
ev2.setText(model.send);
return model;
} catch (JSONException e) {
// Something went wrong!
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return model;
}
}
My Model;
public class Model {
int externalId;
int id;
String type;
String user;
String exchangeName;
Transactions transactions;
List<certificate> certificateList;
public int getExternalId() {
return externalId;
}
public void setExternalId(int externalId) {
this.externalId = externalId;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getExchangeName() {
return exchangeName;
}
public void setExchangeName(String exchangeName) {
this.exchangeName = exchangeName;
}
public Transactions getTransactions() {
return transactions;
}
public void setTransactions(Transactions transactions) {
this.transactions = transactions;
}
public List<certificate> getCertificateList() {
return certificateList;
}
public void setCertificateList(List<certificate> certificateList) {
this.certificateList = certificateList;
}
class Transactions{
String send;
String get;
public String getSend() {
return send;
}
public void setSend(String send) {
this.send = send;
}
public String getGet() {
return get;
}
public void setGet(String get) {
this.get = get;
}
}
class certificate{
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
First of all you could have found this answer easily in the hundreds of tutorials and guides available.
To achieve this you will need to create a custom adapter and a custom view for the adapter item.
To preface this answer. I wasn't sure if you want to show multiple Model items in the RecyclerView, or some other data. This example assumes that you use a List<Model>, however, it's an easy change to make it work with another list of objects.
Example of how the adapter could look like
public class MyAdapter extends RecyclerView.Adapter
{
private Context _context;
private List<Model> _items;
public void setItems(List<Model> items)
{
this._items = items;
notifyDataSetChanged();
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
_context = parent.getContext();
return new MyAdapter.ItemViewHolder(parent);
}
#Override
public void onBindViewHolder(#NonNull final RecyclerView.ViewHolder holder, int position)
{
final MyAdapter.ItemViewHolder viewHolder = (MyAdapter.ItemViewHolder) holder;
final Model item = _items.get(position);
viewHolder._user.setText(item.user);
viewHolder._exchangeName.setText(item.exchangeName);
}
#Override
public int getItemCount()
{
return _items != null ? _items.size() : 0;
}
private static class ItemViewHolder extends RecyclerView.ViewHolder
{
private TextView _user;
private TextView _exchangeName;
private ItemViewHolder(ViewGroup parent)
{
super(LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_view, parent, false));
this._user = itemView.findViewById(R.id.user);
this._exchangeName = itemView.findViewById(R.id.exchange_name);
}
}
}
R.layout.adapter_view
This needs to be a view containing at least the two TextView views references from the MyAdapter above. Simple example:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="#drawable/content_container"
android:orientation="vertical"
android:animateLayoutChanges="true"
android:padding="#dimen/padding_view_large"
android:layout_marginBottom="#dimen/padding_view_small">
<TextView
android:id="#+id/user"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/placeholder"
android:textColor="#color/black"
android:textSize="#dimen/text_size_medium"
android:layout_marginTop="#dimen/padding_view_small"/>
<TextView
android:id="#+id/exchange_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/placeholder"
android:textColor="#color/black"
android:textSize="#dimen/text_size_medium"
android:layout_marginTop="#dimen/padding_view_small"/>
</LinearLayout>
Binding the adapter
//First we set up the adapter and add our List<Model> object.
MyAdapter adapter = new MyAdapter();
adapter.setItems(... List<Model> items);
//Set up our RecyclerView and set the adapter.
final RecyclerView recyclerView = rootView.findViewById(R.id.model_list);
recyclerView.setLayoutManager(new LinearLayoutManager(_context));
recyclerView.setAdapter(adapter);
recyclerView.setHasFixedSize(true);
You need to first understand (and later create) the following things
RecyclerView Adapter
RecyclerView ViewHolder
After you read up on those two things the solution will be pretty clear. Just to point you in the right direction, you will have to create a custom adapter which you will use to populate your custom viewholders. Hope this helps get you going. Feel free to ask if you need any more help in this.

Json Data not loading in Fragment?

Hi Dear Developers,
I hope all of you doing great I am developing Android News app where I have used bottom navigation drawer combination with fragments. When I click each items json not displaying I have used Retrofit for network call.
below MainActivity.java file
public class MainActivity extends BottomBarHolderActivity implements AllJazeeraFragment.OnFragmentInteractionListener, BBCFragment.OnFragmentInteractionListener, CNNFragment.OnFragmentInteractionListener, CBCNewsFragment.OnFragmentInteractionListener {
// private ApiService apiService;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
NavigationPage page1 = new NavigationPage("AllJazeera", ContextCompat.getDrawable(this, R.drawable.alljazeera), AllJazeeraFragment.newInstance());
NavigationPage page2 = new NavigationPage("Support", ContextCompat.getDrawable(this, R.drawable.bbc_icon), CNNFragment.newInstance());
NavigationPage page3 = new NavigationPage("Billing", ContextCompat.getDrawable(this, R.drawable.cnn_icon), AllJazeeraFragment.newInstance());
NavigationPage page4 = new NavigationPage("Profile", ContextCompat.getDrawable(this, R.drawable.cbc_icon), CBCNewsFragment.newInstance());
List<NavigationPage> navigationPages = new ArrayList<>();
navigationPages.add(page1);
navigationPages.add(page2);
navigationPages.add(page3);
navigationPages.add(page4);
super.setupBottomBarHolderActivity(navigationPages);
}
public void onClicked() {
Toast.makeText(this, "Clicked!", Toast.LENGTH_SHORT).show();
}
}
below my AllJazeeraFragment class
where I have implemented network call using retrofit
public class AllJazeeraFragment extends Fragment {
public NewsAdapter adapter;
public Article articleList;
RecyclerView recyclerView;
private AllJazeeraFragment.OnFragmentInteractionListener listener;
public static AllJazeeraFragment newInstance() {
return new AllJazeeraFragment();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.alljazeera_fragment, container, false);
NewsInterface apiService = NewsClient.getApiService();
Call <Article> call = apiService.getAllJazeera();
call.enqueue(new Callback <Article>() {
#Override
public void onResponse(Call <Article> call, Response <Article> response) {
articleList = response.body();
recyclerView = rootView.findViewById(R.id.recycler_view);
adapter = new NewsAdapter((List<Article>) articleList);
RecyclerView.LayoutManager eLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(eLayoutManager);
recyclerView.setAdapter(adapter);
}
#Override
public void onFailure(Call <Article> call, Throwable t) {
}
});
return rootView;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof AllJazeeraFragment.OnFragmentInteractionListener) {
listener = (AllJazeeraFragment.OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
listener = null;
}
public interface OnFragmentInteractionListener {
}
}
below my alljazeera_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:id="#+id/recycler_view"
android:scrollbars="vertical"
android:layout_height="wrap_content"/>
</LinearLayout>
below my BBCFragment.java file
public class BBCFragment extends Fragment {
private OnFragmentInteractionListener listener;
Article articleList;
RecyclerView recyclerView;
NewsAdapter adapter;
public static BBCFragment newInstance() {
return new BBCFragment();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.bbc_fragment, container, false);
NewsInterface apiService = NewsClient.getApiService();
Call <Article> call = apiService.getBBC();
call.enqueue(new Callback <Article>() {
#Override
public void onResponse(Call<Article> call, Response <Article> response) {
articleList = response.body();
recyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
adapter = new NewsAdapter((List<Article>) articleList);
RecyclerView.LayoutManager eLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(eLayoutManager);
recyclerView.setAdapter(adapter);
}
#Override
public void onFailure(Call<Article> call, Throwable t) {
}
});
return rootView;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
listener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
listener = null;
}
public interface OnFragmentInteractionListener {
}
}
below bbc_fragment.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:id="#+id/recycler_view"
android:scrollbars="vertical"
android:layout_height="wrap_content"/>
</LinearLayout>
below my interface where I am calling ending points
public interface NewsInterface {
#GET("v2/top-headlines?sources=al-jazeera-english&apiKey=a5cc70bd52c9436785557878f4aa49e1")
Call <Article> getAllJazeera();
#GET("v2/top-headlines?sources=cbc-news&apiKey=a5cc70bd52c9436785557878f4aa49e1")
Call <Article> getCbC();
#GET("v2/top-headlines?sources=bbc-news&apiKey=a5cc70bd52c9436785557878f4aa49e1")
Call <Article> getBBC();
#GET("v2/top-headlines?sources=cnn&apiKey=a5cc70bd52c9436785557878f4aa49e1")
Call <Article> getCNN();
}
below news client class
public class NewsClient {
public static final String BASE_URL = "https://newsapi.org/";
/**
* Get Retrofit Instance
*/
private static Retrofit getRetrofitInstance() {
return new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
/**
* Get API Service
*
* #return API Service
*/
public static NewsInterface getApiService() {
return getRetrofitInstance().create(NewsInterface.class);
}
}
below json response from api
{
"status": "ok",
"totalResults": 9,
"articles": [
{
"source": {
"id": "al-jazeera-english",
"name": "Al Jazeera English"
},
"author": "Al Jazeera",
"title": "Former Maldives leader Gayoom freed on bail a week after election",
"description": "Former president's release came a week after half-brother Abdulla Yameen lost the presidential election.",
"url": "http://www.aljazeera.com/news/2018/09/maldives-leader-gayoom-freed-bail-week-election-180930150231895.html",
"urlToImage": "https://www.aljazeera.com/mritems/Images/2018/9/30/367ab1ceb832482b9db0c4b22cadf2f5_18.jpg",
"publishedAt": "2018-09-30T16:48:00Z",
"content": "Former Maldives president Maumoon Abdul Gayoom has been released on bail a week after his estranged half-brother Abdulla Yameen was defeated in a presidential election. Gayoom, the Indian Ocean island nation's longest-serving leader, and his legislator son Fa… [+2862 chars]"
},
{
"source": {
"id": "al-jazeera-english",
"name": "Al Jazeera English"
},
"author": "Faras Ghani",
"title": "Why are humans killing 100 million sharks every year?",
"description": "Increasing consumption of shark fin soup and illegal fishing may lead to extinction of certain species, experts warn.",
"url": "http://www.aljazeera.com/news/2018/09/humans-killing-100-million-sharks-year-180923150037790.html",
"urlToImage": "https://www.aljazeera.com/mritems/Images/2018/9/23/1ebd7c07e6dc49b095a58fe7c849a872_18.jpg",
"publishedAt": "2018-09-30T14:02:00Z",
"content": "Humans kill an estimated 100 million sharks annually and experts have warned that certain species face extinction if the trend continues. Consumption of shark fin soup, primarily in China and Vietnam, is the biggest reason behind the massive figure, contribut… [+6786 chars]"
},
{
"source": {
"id": "al-jazeera-english",
"name": "Al Jazeera English"
},
"author": "Al Jazeera",
"title": "Real Madrid football club honours Palestine activist Ahed Tamimi",
"description": "Palestinian activist, who spent eight months in Israeli prison, is welcomed at Bernabeu stadium by the football club.",
"url": "http://www.aljazeera.com/news/2018/09/real-madrid-football-club-honours-palestine-activist-ahed-tamimi-180930100616622.html",
"urlToImage": "https://www.aljazeera.com/mritems/Images/2018/9/30/fa170d306f5d41a5bafbef373f20da1b_18.jpg",
"publishedAt": "2018-09-30T12:09:00Z",
"content": "Palestinian activist Ahed Tamimi, whose arrest last year drew international condemnation, has been honoured by Spanish football club Real Madrid after she was released from Israeli prison. The 17-year-old was arrested in December 2017 after a video of her sla… [+2066 chars]"
},
{
"source": {
"id": "al-jazeera-english",
"name": "Al Jazeera English"
},
"author": "Sheetal Dhir",
"title": "It's time to speak about the economic cost of sexual assault",
"description": "The Kavanaugh scandal is an opportunity to finally talk about the economic toll sexual assault takes on our society.",
"url": "http://www.aljazeera.com/indepth/opinion/time-speak-economic-cost-sexual-assault-180930071453246.html",
"urlToImage": "https://www.aljazeera.com/mritems/Images/2018/9/30/1cf27079db8745d0b2995f820445b739_18.jpg",
"publishedAt": "2018-09-30T11:45:00Z",
"content": "I recently did a straw poll of the women in my life and realised that I know more survivors of sexual assault than I do mothers. The national statistics are staggering - according to the National Sexual Violence Resource Center, \"one in three women in the US … [+9518 chars]"
},
{
"source": {
"id": "al-jazeera-english",
"name": "Al Jazeera English"
},
"author": "Anumeha Yadav",
"title": "In Jharkhand, a tribal assertion met with fierce police crackdown",
"description": "Authorities say they are legally acquiring land to be used for 'development' projects, but villagers tell another story.",
"url": "http://www.aljazeera.com/indepth/features/jharkhand-tribal-assertion-met-fierce-police-crackdown-180929223820429.html",
"urlToImage": "https://www.aljazeera.com/mritems/Images/2018/9/28/619b6054917b46e3ac4f6813f60fe3cd_18.jpg",
"publishedAt": "2018-09-30T07:41:00Z",
"content": "Jharkhand, India: It was dusk in Uduburu, the time that farmers usually return home after working in the paddy fields, but the hamlet in the eastern Indian state of Jharkhand was deserted. The village square was empty and the mud huts were locked. After darkn… [+13300 chars]"
},
{
"source": {
"id": "al-jazeera-english",
"name": "Al Jazeera English"
},
"author": "Shereena Qazi",
"title": "How Afghanistan fell in love with cricket",
"description": "Cricket was imported by Afghan refugees from Pakistan, banned by the Taliban and finally embraced by government.",
"url": "http://www.aljazeera.com/news/2018/09/afghanistan-fell-love-cricket-180928141048315.html",
"urlToImage": "https://www.aljazeera.com/mritems/Images/2018/9/28/f7c2ddb6514642a7bb60e29ea3b6a37c_18.jpg",
"publishedAt": "2018-09-30T06:47:00Z",
"content": "Afghanistan recently ended its 2018 Asia Cup journey in Dubai with a series of impressive performances, filling Afghans at home with joy. With victories against Sri Lanka and Bangladesh, a tie against India and a competitive effort against Pakistan, the team … [+5118 chars]"
},
{
"source": {
"id": "al-jazeera-english",
"name": "Al Jazeera English"
},
"author": "Al Jazeera",
"title": "Indonesia: Rescuers search for survivors after quake, tsunami",
"description": "Rescuers rushing to reach people trapped by the quake and tsunami that has killed over 400 people in Palu city alone.",
"url": "http://www.aljazeera.com/news/2018/09/indonesia-rescuers-search-survivors-quake-tsunami-180930052755793.html",
"urlToImage": "https://www.aljazeera.com/mritems/Images/2018/9/30/59c2bcfc48a046f78ae30a9548511fcc_18.jpg",
"publishedAt": "2018-09-30T06:44:00Z",
"content": "Rescue teams in Indonesia have struggled to reach communities devastated by a major earthquake and tsunami on Sulawesi island, with a toll of more than 400 killed expected to rise sharply as contact is restored with remote areas. Amid the levelled trees, over… [+3207 chars]"
},
{
"source": {
"id": "al-jazeera-english",
"name": "Al Jazeera English"
},
"author": "Charlotte Mitchell",
"title": "Six months to go until Brexit: All you need to know",
"description": "Will Brexit definitely happen? Is a trade deal expected? What will happen to migrants? How will the economy be affected?",
"url": "http://www.aljazeera.com/news/2018/09/months-brexit-180923173227311.html",
"urlToImage": "https://www.aljazeera.com/mritems/Images/2018/9/28/e45c2ba07b944276b369e3fe291bf21b_18.jpg",
"publishedAt": "2018-09-29T08:17:00Z",
"content": "Britain is due to leave the EU in six months' time, at 23:00 GMT on March 29, 2019. Here are five things to know: 1. Will Brexit definitely happen? The UK government remains committed to reaching an agreement with the EU before negotiations end in March, howe… [+9323 chars]"
},
{
"source": {
"id": "al-jazeera-english",
"name": "Al Jazeera English"
},
"author": "James Rippingale",
"title": "The toll of burying Grenfell's dead",
"description": "For those who cared for the living and the dead after the Grenfell Tower fire, the struggle for justice continues.",
"url": "http://www.aljazeera.com/indepth/features/toll-burying-grenfell-dead-180926072155075.html",
"urlToImage": "https://www.aljazeera.com/mritems/Images/2018/9/28/faafdfc4216b47bbb86282cf33fca7df_18.jpg",
"publishedAt": "2018-09-29T06:40:00Z",
"content": "\"I'd never heard of Grenfell before. I didn't think there were that many Muslims in Chelsea,\" exclaims Abu Mumin, 48, of Eden Care, a Muslim end-of-life support charity run from a compact, green and white-walled Whitechapel office. It's a frantic Monday and t… [+9655 chars]"
}
]
}
below my NewsAdapter class
public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.NewsViewHolder> {
private List<Article> articleList;
public NewsAdapter(List<Article> articleList) {
this.articleList = articleList;
}
#NonNull
#Override
public NewsViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.
from(viewGroup.getContext()).
inflate(R.layout.news_item, viewGroup, false);
return new NewsViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull NewsViewHolder newsViewHolder, int i) {
Article article = articleList.get(i);
newsViewHolder.articleAuthor.setText(article.getAuthor());
newsViewHolder.articleTitle.setText(article.getTitle());
newsViewHolder.articleDescription.setText(article.getDescription());
Picasso.get().load(article.getUrlToImage()).into(newsViewHolder.articleImage);
}
#Override
public int getItemCount() {
return articleList.size();
}
public final static class NewsViewHolder extends RecyclerView.ViewHolder {
// TextView articleAuthor, articleTitle, articleDescription, articleUrl;
// ImageView articleImage;
#BindView(R.id.article_Image)
ImageView articleImage;
#BindView(R.id.article_Author)
TextView articleAuthor;
#BindView(R.id.article_Title)
TextView articleTitle;
#BindView(R.id.article_Description)
TextView articleDescription;
#BindView(R.id.article_Url)
TextView articleUrl;
public NewsViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
}
below my Article model class
public class Article {
#SerializedName("source")
#Expose
private Source source;
#SerializedName("author")
#Expose
private String author;
#SerializedName("title")
#Expose
private String title;
#SerializedName("description")
#Expose
private String description;
#SerializedName("url")
#Expose
private String url;
#SerializedName("urlToImage")
#Expose
private String urlToImage;
#SerializedName("publishedAt")
#Expose
private String publishedAt;
#SerializedName("content")
#Expose
private String content;
public Source getSource() {
return source;
}
public void setSource(Source source) {
this.source = source;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUrlToImage() {
return urlToImage;
}
public void setUrlToImage(String urlToImage) {
this.urlToImage = urlToImage;
}
public String getPublishedAt() {
return publishedAt;
}
public void setPublishedAt(String publishedAt) {
this.publishedAt = publishedAt;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
You have created your model class incorrectly, first of all you will need one more model class like this
ArticleResponse.java
public class ArticleResponse {
#SerializedName("status")
#Expose
private String status;
#SerializedName("totalResults")
#Expose
private Integer totalResults;
#SerializedName("articles")
#Expose
private List<Article> articles = null;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Integer getTotalResults() {
return totalResults;
}
public void setTotalResults(Integer totalResults) {
this.totalResults = totalResults;
}
public List<Article> getArticles() {
return articles;
}
public void setArticles(List<Article> articles) {
this.articles = articles;
}
}
Now change this public Article articleList; to this public
ArrayList<Article> articleList=new ArrayList();
Now change your network call like this
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.alljazeera_fragment, container, false);
NewsInterface apiService = NewsClient.getApiService();
Call <ArticleResponse> call = apiService.getAllJazeera();
call.enqueue(new Callback <ArticleResponse>() {
#Override
public void onResponse(Call <ArticleResponse> call, Response <ArticleResponse> response) {
articleList = new ArrayList<>(response.body().getArticles());
recyclerView = rootView.findViewById(R.id.recycler_view);
adapter = new NewsAdapter(articleList);
RecyclerView.LayoutManager eLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(eLayoutManager);
recyclerView.setAdapter(adapter);
}
#Override
public void onFailure(Call <ArticleResponse> call, Throwable t) {
}
});
return rootView;
}
Now change interface also like this
#GET("v2/top-headlines?sources=al-jazeera-english&apiKey=a5cc70bd52c9436785557878f4aa49e1")
Call <ArticleResponse> getAllJazeera();
#GET("v2/top-headlines?sources=cbc-news&apiKey=a5cc70bd52c9436785557878f4aa49e1")
Call <ArticleResponse> getCbC();
#GET("v2/top-headlines?sources=bbc-news&apiKey=a5cc70bd52c9436785557878f4aa49e1")
Call <ArticleResponse> getBBC();
#GET("v2/top-headlines?sources=cnn&apiKey=a5cc70bd52c9436785557878f4aa49e1")
Call <ArticleResponse> getCNN();
I see many issues with your code.
Your json has a list of articles. But your Call <Article> getAllJazeera() api returns a <Article> instead of <List<Article>>. In fact you should have a ArticleListResponse sort of model that contains a list of articles and other fields in your json such as
"status": "ok",
"totalResults": 9,
Another issue I see is that your retrofit success callback you are doing
adapter = new NewsAdapter((List<Article>) articleList);
even though articleList is not even List<Article>. You create an Article variable and try to cast it to a list.
You need to make all these changes and then your code might work.

Resources$NotFoundException When calling a Rest API using RetroFit 2

I am calling a REST Api with RetroFit 2 and trying to display it with a RecyclerView but for some reason I am getting a Resources$NotFoundException.
The JSON generated That i want to read and display in a RecyclerView is:
{
"generated_at": "2018-05-31T12:10:29+00:00",
"schema": "http:\/\/schemas.sportradar.com\/bsa\/soccer\/v1\/json\/endpoints\/soccer\/tournament_standings.json",
"tournament": {
"id": "sr:tournament:17",
"name": "Premier League",
"sport": {
"id": "sr:sport:1",
"name": "Soccer"
},
"category": {
"id": "sr:category:1",
"name": "England",
"country_code": "ENG"
},
"current_season": {
"id": "sr:season:40942",
"name": "Premier League 17\/18",
"start_date": "2017-08-11",
"end_date": "2018-05-14",
"year": "17\/18"
}
},
"season": {
"id": "sr:season:40942",
"name": "Premier League 17\/18",
"start_date": "2017-08-11",
"end_date": "2018-05-14",
"year": "17\/18",
"tournament_id": "sr:tournament:17"
},
"standings": [{
"tie_break_rule": "In the event that two (or more) teams have an equal number of points, the following rules break the tie:\r\n1. Goal difference\r\n2. Goals scored",
"type": "total",
"groups": [{
"team_standings": [{
"team": {
"id": "sr:competitor:17",
"name": "Manchester City"
},
"rank": 1,
"current_outcome": "Champions League",
"played": 38,
"win": 32,
"draw": 4,
"loss": 2,
"goals_for": 106,
"goals_against": 27,
"goal_diff": 79,
"points": 100
}]
}]
}]}
So I created a Response which is :
public class StandingsResponse {
#SerializedName("generated_at")
#Expose
private String mGeneratedAt;
#SerializedName("schema")
#Expose
private String mSchema;
#SerializedName("standings")
private List<Standings> mStandings;
public String getGeneratedAt() {
return mGeneratedAt;
}
public void setGeneratedAt(String generatedAt) {
mGeneratedAt = generatedAt;
}
public String getSchema() {
return mSchema;
}
public void setSchema(String schema) {
mSchema = schema;
}
public List<Standings> getStandings() {
return mStandings;
}
public void setStandings(List<Standings> standings) {
mStandings = standings;
}
The Response has a List of Standings, The standings POJO has a list of groups:
public class Standings {
#SerializedName("groups")
#Expose
private List<Group> mGroup;
public List<Group> getGroup() {
return mGroup;
}
public void setGroup(List<Group> group) {
mGroup = group;
}
The Groups POJO has a list of TeamStandings:
public class Group {
#SerializedName("team_standings")
#Expose
private List<TeamStandings> mTeamStandings;
public List<TeamStandings> getTeamStandings() {
return mTeamStandings;
}
public void setTeamStandings(List<TeamStandings> teamStandings) {
mTeamStandings = teamStandings;
}
And TeamStandings has all the data I want to display:
public class TeamStandings {
#SerializedName("team")
#Expose
private Team mTeam;
#SerializedName("rank")
#Expose
private Integer mRank;
#SerializedName("played")
#Expose
private Integer mPlayed;
#SerializedName("win")
#Expose
private Integer mWin;
#SerializedName("draw")
#Expose
private Integer mDraw;
#SerializedName("lose")
#Expose
private Integer mLose;
#SerializedName("goals_for")
#Expose
private Integer mGoalsFor;
#SerializedName("goals_against")
#Expose
private Integer mGoalsAgainst;
#SerializedName("goal_diff")
#Expose
private Integer mGoalsDiff;
#SerializedName("points")
#Expose
private Integer mPoints;
public Integer getGoalsFor() {
return mGoalsFor;
}
public void setGoalsFor(Integer goalsFor) {
mGoalsFor = goalsFor;
}
public Integer getGoalsAgainst() {
return mGoalsAgainst;
}
public void setGoalsAgainst(Integer goalsAgainst) {
mGoalsAgainst = goalsAgainst;
}
public Integer getGoalsDiff() {
return mGoalsDiff;
}
public void setGoalsDiff(Integer goalsDiff) {
mGoalsDiff = goalsDiff;
}
public Integer getRank() {
return mRank;
}
public void setRank(Integer rank) {
mRank = rank;
}
public Integer getPlayed() {
return mPlayed;
}
public void setPlayed(Integer played) {
mPlayed = played;
}
public Integer getWin() {
return mWin;
}
public void setWin(Integer win) {
mWin = win;
}
public Integer getDraw() {
return mDraw;
}
public void setDraw(Integer draw) {
mDraw = draw;
}
public Integer getLose() {
return mLose;
}
public void setLose(Integer lose) {
mLose = lose;
}
public Integer getPoints() {
return mPoints;
}
public void setPoints(Integer points) {
mPoints = points;
}
public Team getTeam() {
return mTeam;
}
public void setTeam(Team team) {
mTeam = team;
}
I am calling the response and correctly attaching the response body to the Adapter but for some reason the App crashes and I see this error in the Logcat:
android.content.res.Resources$NotFoundException: String resource ID #0x1
at android.content.res.Resources.getText(Resources.java:339)
at android.widget.TextView.setText(TextView.java:5496)
at com.mad.footstats.ui.adapters.StandingsAdapter.onBindViewHolder(StandingsAdapter.java:62)
Edit: this is my Adapter:
public class StandingsAdapter extends RecyclerView.Adapter<StandingsAdapter.StandingsViewHolder> {
private List<Standings> mStandings;
private int mRowLayout;
private Context mContext;
public class StandingsViewHolder extends RecyclerView.ViewHolder {
LinearLayout standingsLayout;
TextView teamRank, teamName, teamPlayed, teamWon, teamDraw,
teamLose, teamFor, teamAgainst, teamGd, teamPts;
public StandingsViewHolder(View itemView) {
super(itemView);
standingsLayout = itemView.findViewById(R.id.standings_layout);
teamRank = itemView.findViewById(R.id.standings_team_rank);
teamName = itemView.findViewById(R.id.standings_team_name);
teamPlayed = itemView.findViewById(R.id.standings_team_played);
teamWon = itemView.findViewById(R.id.standings_team_won);
teamDraw = itemView.findViewById(R.id.standings_team_draw);
teamLose = itemView.findViewById(R.id.standings_team_lost);
teamFor = itemView.findViewById(R.id.standings_team_for);
teamAgainst = itemView.findViewById(R.id.standings_team_against);
teamGd = itemView.findViewById(R.id.standings_team_gd);
teamPts = itemView.findViewById(R.id.standings_team_pts);
}
}
public StandingsAdapter (List<Standings> standings, int rowLayout,
Context context){
mStandings = standings;
mRowLayout = rowLayout;
mContext = context;
}
#Override
public StandingsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(mRowLayout, parent, false);
StandingsViewHolder holder = new StandingsViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(StandingsViewHolder holder, int position) {
holder.teamRank.setText(mStandings.get(position).getGroup().get(position)
.getTeamStandings().get(position).getRank());
holder.teamName.setText(mStandings.get(position).getGroup().get(position)
.getTeamStandings().get(position).getTeam().getName());
holder.teamPlayed.setText(mStandings.get(position).getGroup().get(position)
.getTeamStandings().get(position).getPlayed());
holder.teamWon.setText(mStandings.get(position).getGroup().get(position)
.getTeamStandings().get(position).getWin());
holder.teamDraw.setText(mStandings.get(position).getGroup().get(position)
.getTeamStandings().get(position).getDraw());
holder.teamLose.setText(mStandings.get(position).getGroup().get(position)
.getTeamStandings().get(position).getLose());
holder.teamFor.setText(mStandings.get(position).getGroup().get(position)
.getTeamStandings().get(position).getGoalsFor());
holder.teamAgainst.setText(mStandings.get(position).getGroup().get(position)
.getTeamStandings().get(position).getGoalsAgainst());
holder.teamGd.setText(mStandings.get(position).getGroup().get(position)
.getTeamStandings().get(position).getGoalsDiff());
holder.teamPts.setText(mStandings.get(position).getGroup().get(position)
.getTeamStandings().get(position).getPoints());
}
#Override
public int getItemCount() {
return mStandings.size();
}
This exception come because you set integer value in textview so you should be do type casting of String .
For Example
you doing
mTxtView.setText(mList.get(position).getMETHOD_WHICH_RETURN_INT())
you should be do
mTxtView.setText(""+mList.get(position).getMETHOD_WHICH_RETURN_INT())
You should be
holder.teamRank.setText(""+mStandings.get(position).getGroup().get(position)
.getTeamStandings().get(position).getRank());
holder.teamPlayed.setText(""+mStandings.get(position).getGroup().get(position)
.getTeamStandings().get(position).getPlayed());
holder.teamWon.setText(""+mStandings.get(position).getGroup().get(position)
.getTeamStandings().get(position).getWin());
holder.teamDraw.setText(mStandings.get(position).getGroup().get(position)
.getTeamStandings().get(position).getDraw());
holder.teamLose.setText(""+mStandings.get(position).getGroup().get(position)
.getTeamStandings().get(position).getLose());
holder.teamFor.setText(""+mStandings.get(position).getGroup().get(position)
.getTeamStandings().get(position).getGoalsFor());
holder.teamAgainst.setText(""+mStandings.get(position).getGroup().get(position)
.getTeamStandings().get(position).getGoalsAgainst());
holder.teamGd.setText(""+mStandings.get(position).getGroup().get(position)
.getTeamStandings().get(position).getGoalsDiff());
holder.teamPts.setText(""+mStandings.get(position).getGroup().get(position)
.getTeamStandings().get(position).getPoints());

Set Image array in recyclerview from json data in android

In my app I have got some json data from url. I have deserialize those data in controller class. Now I want to show those image into recyclerview.This recyclerview will be shown in detail activity. I have devided the relative layout into two part. First half is for information and the second half is for a recyclerview. I tried with the follwing code. The problem is I am very new in android developing and I am not getting the correct logic of doing this. I have explained in detail below-
Here is my model class
public class NewsModel {
#Expose
private String id;
#Expose
private String title;
#Expose
private List<AppImage> appImages;
public List<AppImage> getAppImages() {
return appImages;
}
public void setAppImages(List<AppImage> appImages) {
this.appImages = appImages;
}
}
The AppImageClass is
public class AppImage {
#Expose
private String _id;
#Expose
private String alt;
#Expose
private String src;
public String get_id() {
return _id;
}
public void set_id(String _id) {
this._id = _id;
}
public String getAlt() {
return alt;
}
public void setAlt(String alt) {
this.alt = alt;
}
public String getSrc() {
return src;
}
public void setSrc(String src) {
this.src = src;
}
}
The adapter class is
public class NewsImageAdapter extends RecyclerView.Adapter<NewsImageAdapter.ImageHolder> {
private Context context;
private List<NewsModel> imageObject;
public NewsImageAdapter(Context context, List<NewsModel> imageObject) {
this.context = context;
this.imageObject = imageObject;
}
#Override
public ImageHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.newsdetail_image_row,parent,false);
return new ImageHolder(view);
}
#Override
public void onBindViewHolder(ImageHolder holder, int position) {
final NewsModel currentImage=imageObject.get(position);
for (int i = 0; i < currentImage.getAppImages().size() ; i++)
{
AppImage appImage = currentImage.getAppImages().get(i);
Picasso.with(holder.itemView.getContext()).load(appImage.getSrc()).into( holder.images[i] ); }
Picasso.with(holder.itemView.getContext());
}
#Override
public int getItemCount() {
return imageObject.size();
}
public class ImageHolder extends RecyclerView.ViewHolder {
public ImageView images;
public ImageHolder(View itemView) {
super(itemView);
images= itemView.findViewById(R.id.news_image);
}
}
}
In Deatil activity
public class DetailNews extends AppCompatActivity {
private List<NewsModel> newsObject;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.news_detail);
setUpUIViews();
//newsObject=getAllImageList();
}
private void setUpUIViews() {
recyclerView = (RecyclerView)findViewById(R.id.image_list);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(DetailNews.this);
recyclerView.setLayoutManager(layoutManager);
adapter = new NewsImageAdapter(this,newsObject );
recyclerView.setAdapter(adapter);
}
private List<NewsImageModel> getAllImageList() {
//how to set image here?
return images;
}
The json data looks like this
[
{ "id": "5925280ec925a9a6dd5173bb",
"title": "Headline",
"appImages": [
{
"alt": "",
"src": "source1",
"_id": "12213"
},
{
"alt": "",
"src": "source2",
"_id": "fdgdg"
},
{
"alt": "",
"src": "source3",
"_id": "fdfdfdf"
},
{
"alt": "",
"src": "source4",
"_id": "599d9018daf57d002c100ffa"
},
{
"alt": "",
"src": "source5",
"_id": "f7879"
}
],
},
{ "id": "5925280ec925a9a6dd5173bb",
"title": "Headline",
"appImages": [
{
"alt": "",
"src": "source1",
"_id": "12213"
},
{
"alt": "",
"src": "source2",
"_id": "fdgdg"
},
{
"alt": "",
"src": "source3",
"_id": "fdfdfdf"
},
{
"alt": "",
"src": "source4",
"_id": "599d9018daf57d002c100ffa"
},
{
"alt": "",
"src": "source5",
"_id": "f7879"
}
],
},
]
You should use one "raw/item" for each image. You don't need use "Picasso" to load the images, you can use something like:
In your RecyclerView.Adapter
.
.
.
#Override
public void onBindViewHolder(ViewHolderCustom viewHolder, final int position) {
viewHolder.setImage("imageUrl");
}
static class ViewHolderCustom extends RecyclerView.ViewHolder{
private final ImageView imageViewPhotoUrl;
ViewHolderCustom(View v) {
super(v);
imageViewPhotoUrl = (ImageView) v.findViewById(R.id.iv_photo_url);
}
void setImage(String photo) {
if (photo != null && !photo.isEmpty())
new DownloadImageTask(imageViewPhotoUrl)
.execute(photo);
}
}
.
.
.
Your DownloadImageTask:
public class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
private ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urlDisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urlDisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
if (result != null)
bmImage.setImageBitmap(result);
}
}

Categories

Resources