I'm using volley to load data using JSON Parsing in to a recycler view. I've used recylcer view before, but somehow, the downloaded data is persistent this time, meaning its still there after the app is closed, maybe stays in cache. I'm not sure, what I'm doing wrong here. Any help is appreciated, thanks.
Edit: The application is storing downloaded data after the app is closed, which doesn't happen when using recycler view.
This is my Activity Class:
package com.example.recyclerview;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class PostActivity extends AppCompatActivity implements
OnItemClick{
private ArrayList<PostData> posts = new ArrayList<>();
private PostRecycleViewAdapter viewAdapter;
private String listingJsonUrl = "https://jsonplaceholder.typicode.com/posts/";
Toolbar toolbar;
private ProgressDialog progressDialog;
private RequestQueue requestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
progressDialog = new ProgressDialog(this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setCancelable(true);
final RecyclerView.LayoutManager viewLayoutManager = new LinearLayoutManager(getApplicationContext());
viewAdapter = new PostRecycleViewAdapter(posts);
final RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(viewLayoutManager);
recyclerView.setAdapter(viewAdapter);
viewAdapter.setClickListener(this);
new DownloadData().execute(listingJsonUrl);
}
#Override
public void onClick(View view, int position) {
final PostData data = posts.get(position);
String title;
int id;
Intent commentIntent = new Intent(this, CommentsActivity.class);
id = data.getId();
title = data.getTitle();
if(title.length() > 25){
title = title.substring(0,25);
title = title.concat("..");
}
commentIntent.putExtra("title",title) ;
commentIntent.putExtra("id", id);
startActivity(commentIntent);
}
class DownloadData extends AsyncTask<String, String, String>{
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
#Override
protected String doInBackground(String... url) {
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url[0], new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
JSONArray jsonArray = new JSONArray(response.toString());
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
PostData postData = new PostData(jsonObject.getInt("id"),jsonObject.getString("title"), jsonObject.getString("body"));
posts.add(postData);
viewAdapter.notifyDataSetChanged();
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("JsonError", error.getMessage());
}
});
getRequestQueue().add(jsonArrayRequest);
return null;
}
}
public RequestQueue getRequestQueue()
{
if (requestQueue == null)
{
requestQueue = com.android.volley.toolbox.Volley.newRequestQueue(getApplicationContext());
}
return requestQueue;
}
}
This is my RecyclerView Adapter Class:
package com.example.recyclerview;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
public class PostRecycleViewAdapter extends RecyclerView.Adapter<PostRecycleViewAdapter.ViewHolder>
{
private List<PostData> postData;
private OnItemClick itemClick;
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView title, body;
public ViewHolder(View view){
super(view);
title = (TextView) view.findViewById(R.id.title);
body = (TextView) view.findViewById(R.id.body);
view.setTag(view);
view.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if(itemClick != null) itemClick.onClick(view, getAdapterPosition());
}
}
public PostRecycleViewAdapter(List<PostData> postData)
{
this.postData = postData;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemLayout = LayoutInflater.from(parent.getContext()).inflate(R.layout.post_recycler_view,parent,false);
return new ViewHolder(itemLayout);
}
#Override
public void onBindViewHolder(PostRecycleViewAdapter.ViewHolder holder, int position) {
PostData data = postData.get(position);
holder.title.setText(data.getTitle());
holder.body.setText(data.getBody());
}
#Override
public int getItemCount() {
return postData.size();
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);}
public void setClickListener(OnItemClick itemClick) {
this.itemClick = itemClick;
}
}
And this is the data item class:
package com.example.recyclerview;
public class PostData {
private String title, body;
private int id;
public PostData(int id, String title, String body)
{
this.id = id;
this.title = title;
this.body = body;
}
public String getTitle() {
return title;
}
public String getBody() {
return body;
}
public int getId() {
return id;
}
}
Related
I am working with a project and I am trying to fetch some link from a json data and I want to connect the link with a button in my recycleview so that whenever the button is clicked, it'll automatically connet to the respective websites. I gave user permission to interner in Manifest. So, How to connect it?
package com.example.covidcuretemplate1;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private RequestQueue requestQueue;
private ExampleAdapter exampleAdapter;
private ArrayList<ExampleItem> exampleList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this, RecyclerView.HORIZONTAL,false));
exampleList = new ArrayList<>();
requestQueue = Volley.newRequestQueue(this);
parseJSON();
}
private void parseJSON() {
String url = "https://newsapi.org/v2/top-headlines?country=in&category=health&apiKey=*************************";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("articles");
for(int i = 0; i < jsonArray.length(); i++)
{
JSONObject article = jsonArray.getJSONObject(i);
if(article.isNull("description") || article.isNull("urlToImage")) {
continue;
}
if(article.getString("description").isEmpty() || article.getString("urlToImage").isEmpty())
continue;
String title = article.getString("title");
String description = article.getString("description");
String date = article.getString("publishedAt");
String imageurl = article.getString("urlToImage");
//How to connect this??????
String newsurl = article.getString("url");
exampleList.add(new ExampleItem(imageurl,title,description,date));
}
exampleAdapter = new ExampleAdapter(MainActivity.this,exampleList);
recyclerView.setAdapter(exampleAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
requestQueue.add(request);
}
}
My Adapter class, Here can anybody suggest anything in the place of toast? The Toast is working fine !!!
public class ExampleAdapter extends RecyclerView.Adapter<ExampleAdapter.ExampleViewHolder> {
public Context mcontext;
public ArrayList<ExampleItem> marrayList;
public ExampleAdapter(Context mcontext, ArrayList<ExampleItem> marrayList) {
this.mcontext = mcontext;
this.marrayList = marrayList;
}
#NonNull
#Override
public ExampleViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mcontext).inflate(R.layout.card_item,parent,false);
ExampleViewHolder exampleViewHolder = new ExampleViewHolder(view);
return exampleViewHolder;
}
#Override
public void onBindViewHolder(#NonNull ExampleViewHolder holder, int position) {
ExampleItem examplItem = marrayList.get(position);
String imageurl = examplItem.getMimgurl();
String title = examplItem.getMtitle();
String description = examplItem.getMdescription();
String date = examplItem.getMdate();
/////////////
final String newsurl = examplItem.getMurl();
////////////
holder.textview_title.setText(title);
holder.textview_description.setText(description);
holder.textview_date.setText(date);
Glide.with(mcontext).load(imageurl).into(holder.imageview_news);
///////////////////////////
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//////////////////////////////////NEED HELP!!!!!!!!!!!!!!!!!!/////////
Toast.makeText(mcontext,newsurl,Toast.LENGTH_LONG).show();
}
});
//////////////////////////
}
#Override
public int getItemCount() {
return marrayList.size();
}
public static class ExampleViewHolder extends RecyclerView.ViewHolder{
public ImageView imageview_news;
public TextView textview_title;
public TextView textview_description;
public TextView textview_date;
///////////////////////////
public Button button;
///////////////////////////
public ExampleViewHolder(#NonNull View itemView) {
super(itemView);
imageview_news = itemView.findViewById(R.id.imageview_news);
textview_title = itemView.findViewById(R.id.textview_title);
textview_description = itemView.findViewById(R.id.textview_description);
textview_date = itemView.findViewById(R.id.textview_date);
/////////////////////////
button = itemView.findViewById(R.id.button);
////////////////////////
}
}
}
Try to set intent for the website inside the onClickListener. Something like this:
Button button= findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String url = "http://www.YourWebsite.com"; //insert the link you prase
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
}
});
You can use this code inside onClickListener to open it in the browser.
Uri uri = Uri.parse(newsurl);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
Please help with the following problems, the problem is that the data does not want to appear in the fragment home, even though the internet condition is on
My HomeFragment code:
package untag.adproj.lestari.lestari.Home;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import untag.adproj.lestari.lestari.R;
public class HomeFragment extends Fragment {
private String URL="http://pembuatanprogram.000webhostapp.com";
private RecyclerAdapter recyclerAdapter;
private RecyclerView recyclerView;
private ArrayList<Data> listdata;
private GridLayoutManager gridLayoutManager;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
public HomeFragment() {
// 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_home, container, false);
recyclerView = view.findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
gridLayoutManager = new GridLayoutManager(getActivity(), 2);
gridLayoutManager.setOrientation(GridLayoutManager.VERTICAL);
recyclerView.setLayoutManager(gridLayoutManager);
listdata = new ArrayList<Data>();
AmbilData();
recyclerAdapter = new RecyclerAdapter(getActivity(),listdata);
recyclerView.setAdapter(recyclerAdapter);
recyclerAdapter.notifyDataSetChanged();
return view;
}
private void AmbilData() {
JsonArrayRequest aarRequest = new JsonArrayRequest(URL + "/produk.php" ,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
if (response.length()>0){
for (int i =0 ; i<response.length();i++){
try {
JSONObject data = response.getJSONObject(i);
Data item = new Data();
item.setId(data.getString("id"));
item.setJudul(data.getString("judul"));
item.setHarga(data.getString("harga"));
item.setThubnail(data.getString(URL+"/img/"+data.getString("gambar")));
listdata.add(item);
recyclerAdapter.notifyDataSetChanged();
} catch (JSONException e) {
}
}
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
};
Volley.newRequestQueue(getActivity()).add(aarRequest);
}
}
My RecyclerAdapter code:
package untag.adproj.lestari.lestari.Home;
import android.app.Activity;
import android.content.Context;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
import untag.adproj.lestari.lestari.R;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private ArrayList<Data> listdata;
private Activity activity;
private Context context;
public RecyclerAdapter(Activity activity, ArrayList<Data> listdata) {
this.listdata = listdata;
this.activity = activity;
}
#Override
public RecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.fragment_home_list, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
//holder.mImage.setImageResource(listdata.get(position).getThubnail());
holder.id.setText(listdata.get(position).getId());
holder.judul.setText(listdata.get(position).getJudul());
holder.harga.setText(listdata.get(position).getHarga());
final ViewHolder x=holder;
Glide.with(activity)
.load(listdata.get(position).getThubnail())
.into(holder.thumbnail);
holder.id.setVisibility(View.GONE);
}
#Override
public int getItemCount() {
return listdata.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
private CardView cv;
private TextView id,judul,harga;
private ImageView thumbnail;
public ViewHolder(View v) {
super(v);
cv=(CardView)v.findViewById(R.id.card_view);
id=(TextView)v.findViewById(R.id.id);
judul=(TextView)v.findViewById(R.id.judul);
harga=(TextView)v.findViewById(R.id.harga);
thumbnail=(ImageView)v.findViewById(R.id.thumbnail);
}
}
}
My Data code:
package untag.adproj.lestari.lestari.Home;
public class Data {
private String id;
private String judul;
private String harga;
private String thubnail;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getJudul() {
return judul;
}
public void setJudul(String judul) {
this.judul = judul;
}
public String getHarga() {
return harga;
}
public void setHarga(String harga) {
this.harga = harga;
}
public String getThubnail() {
return thubnail;
}
public void setThubnail(String thubnail) {
this.thubnail = thubnail;
}
}
My code refresh comes from Youtube
but in the tutorial it does not use fragment, please anyone help me
You have a wrong point, that is not update the list of recycler view, the list you add value in code listdata.add(item); belong to your fragment
Please add below method in your adapter
public void addData(List<Data> data) {
listdata.addAll(data);
notifyDataSetChanged();
}
And edit AmbilData function as below
private void AmbilData() {
JsonArrayRequest aarRequest = new JsonArrayRequest(URL + "/produk.php" ,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
if (response.length()>0){
for (int i =0 ; i<response.length();i++){
try {
JSONObject data = response.getJSONObject(i);
Data item = new Data();
item.setId(data.getString("id"));
item.setJudul(data.getString("judul"));
item.setHarga(data.getString("harga"));
item.setThubnail(data.getString(URL+"/img/"+data.getString("gambar")));
listdata.add(item);
} catch (JSONException e) {
}
}
recyclerAdapter.addData(listdata);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
};
Volley.newRequestQueue(getActivity()).add(aarRequest);
}
package untag.adproj.lestari.lestari.Home;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import untag.adproj.lestari.lestari.R;
public class HomeFragment extends Fragment {
private String URL="http://pembuatanprogram.000webhostapp.com";
private RecyclerAdapter recyclerAdapter;
private RecyclerView recyclerView;
private ArrayList<Data> listdata;
private ArrayList<Data> tempList;
private GridLayoutManager gridLayoutManager;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
public HomeFragment() {
// 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_home, container, false);
recyclerView = view.findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
gridLayoutManager = new GridLayoutManager(getActivity(), 2);
gridLayoutManager.setOrientation(GridLayoutManager.VERTICAL);
recyclerView.setLayoutManager(gridLayoutManager);
tempList = new ArrayList<Data>();
listdata = new ArrayList<Data>();
AmbilData();
recyclerAdapter = new RecyclerAdapter(getActivity(),listdata);
recyclerView.setAdapter(recyclerAdapter);
recyclerAdapter.notifyDataSetChanged();
return view;
}
private void AmbilData() {
JsonArrayRequest aarRequest = new JsonArrayRequest(URL + "/produk.php" ,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
if (response.length()>0){
for (int i =0 ; i<response.length();i++){
try {
JSONObject data = response.getJSONObject(i);
Data item = new Data();
item.setId(data.getString("id"));
item.setJudul(data.getString("judul"));
item.setHarga(data.getString("harga"));
item.setThubnail(data.getString(URL+"/img/"+data.getString("gambar")));
tempList.add(item);
recyclerAdapter.notifyDataSetChanged();
} catch (JSONException e) {
}
}
listdata.clear();
listdata.addAll(tempList);
recyclerAdapter.notifyDataSetChanged();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
};
Volley.newRequestQueue(getActivity()).add(aarRequest);
}
}
Use temp list then addAll() method then call notifyDataSetChanged() method.
If you want to notify your adapter from a loop then you should go for notifyItemInserted() otherwise keep the notifyDataSetChanged() outside of the loop.
Like this;
for (int i =0 ; i<response.length();i++){
try {
JSONObject data = response.getJSONObject(i);
Data item = new Data();
item.setId(data.getString("id"));
item.setJudul(data.getString("judul"));
item.setHarga(data.getString("harga"));
item.setThubnail(data.getString(URL+"/img/"+data.getString("gambar")));
listdata.add(item);
recyclerAdapter.notifyItemInserted(listdata.size()-1); //To update the recyclerview one by one from a loop.
} catch (JSONException e) {
}
}
// OR
for (int i =0 ; i<response.length();i++){
try {
JSONObject data = response.getJSONObject(i);
Data item = new Data();
item.setId(data.getString("id"));
item.setJudul(data.getString("judul"));
item.setHarga(data.getString("harga"));
item.setThubnail(data.getString(URL+"/img/"+data.getString("gambar")));
listdata.add(item);
} catch (JSONException e) {
}
}
recyclerAdapter.notifyDataSetChanged(); //To update the whole recyclerview in one shot
Good afternoon guys, I am trying to fetch some data from the police data website.
Unfortunately, the application doesn't show any data saying "E/RecyclerView: No adapter attached; skipping layout".
I have attached the LatestCrimesActivity, adapter and the ListItem class.
Thank you for your help.
This is LatestCrimesActivity:
package com.example.cosmin.crimerate.Latest_crimes_api;
import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.cosmin.crimerate.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class LatestCrimesActivity extends AppCompatActivity {
private static final String URL_DATA = "https://data.police.uk/api/crimes-street/all-crime?poly=52.268,0.543:52.794,0.238:52.130,0.478&date=2017-01";
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private List<ListItem> listItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_latest_crimes);
recyclerView = (RecyclerView) findViewById(R.id.recyclerViewlatest);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
listItems=new ArrayList<>();
loadRecyclerViewData();
}
private void loadRecyclerViewData() {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading data...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET,
URL_DATA,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray array = jsonObject.getJSONArray("");
for (int i=0; i<array.length();i++){
JSONObject o = array.getJSONObject(i);
ListItem item = new ListItem(
o.getString("category"),
o.getString("location_type"),
o.getString("street"),
o.getString("status")
);
listItems.add(item);
}
adapter = new MyAdapter(listItems, getApplicationContext());
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
Adapter:
package com.example.cosmin.crimerate.Latest_crimes_api;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.TextView;
import com.example.cosmin.crimerate.R;
import java.util.List;
/**
* Created by Cosmin on 25/11/2017.
*/
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<ListItem> listItems;
private Context context;
public MyAdapter(List<ListItem> listItems, LatestCrimesActivity latestCrimesActivity) {
this.listItems = listItems;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
ListItem listItem = listItems.get(position);
holder.textViewCat.setText(listItem.getCategory());
holder.textViewLoc.setText(listItem.getLocation());
holder.textViewStreet.setText(listItem.getStreet());
holder.textViewStatus.setText(listItem.getStatus());
}
#Override
public int getItemCount() {
return listItems.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView textViewCat;
public TextView textViewLoc;
public TextView textViewStreet;
public TextView textViewStatus;
public ViewHolder(View itemView) {
super(itemView);
textViewCat = (TextView) itemView.findViewById(R.id.textViewCat);
textViewLoc = (TextView) itemView.findViewById(R.id.textViewLoc);
textViewStreet = (TextView) itemView.findViewById(R.id.textViewStreet);
textViewStatus = (TextView) itemView.findViewById(R.id.textViewStatus);
}
}
}
This is ListItem class:
package com.example.cosmin.crimerate.Latest_crimes_api;
/**
* Created by Cosmin on 25/11/2017.
*/
public class ListItem {
private String category;
private String location;
private String street;
private String status;
public ListItem (String category, String location, String street, String status){
this.category=category;
this.location=location;
this.street=street;
this.status=status;
}
public String getCategory (){
return category;
}
public String getLocation (){
return location;
}
public String getStreet (){
return street;
}
public String getStatus (){
return status;
}
}
Just try to change some lines. First set adapter before your api call.
recyclerView = (RecyclerView) findViewById(R.id.recyclerViewlatest);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
listItems=new ArrayList<>();
adapter = new MyAdapter(listItems, getApplicationContext());
recyclerView.setAdapter(adapter);
Then when you received the answer, fill listItems, then call notifyDataSetChange() method of your adapter object.
I tried to display jsonObject in Recyclerview use retrofit library, but it only accept in the Array format. I tried to change the jsonObject to jsonArray, but the problem is the server don't recognize the json type. So now my question is, how to display jsonObject to recyclerview widget. Give me tips or idea..Thank in advance
This is my Jsonobject Data..
{
"success": true,
"data": {
"id": 1,
"parent_id": null,
"name": "Ionnex Sdn Bhd",
"description": "Test Value",
"image": "http://www.ionnex.com/images/logo_ionnex.png",
"phone_no": "12345678",
"fax": "123456",
"address": "Kl Sentral",
"latitude": 0,
"longitude": 0,
"created_at": "2017-08-15 02:26:00",
"donors_count": "4",
"donors_amount": "601.00"
}
}
This is my Fragment connect to the recyclerview widget.
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.baracode.eilsan.data.ApiRequest;
import com.baracode.eilsan.donate.DonateMenuActivity;
import com.baracode.eilsan.donate.parentOrganisation.ParentOrganisationActivity;
import com.baracode.eilsan.donate.parentOrganisation.adapter.DonateParentOrganisationAdapter;
import com.baracode.eilsan.donate.parentOrganisation.adapter.OrganisationAdapter;
import com.baracode.eilsan.donate.parentOrganisation.adapter.OrganisationModel;
import com.baracode.eilsan.R;
import com.baracode.eilsan.model.Caused;
import com.baracode.eilsan.model.Organisation;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import static android.R.id.message;
public class OrganisationFragment extends Fragment {
private ViewPager viewPager;
private ImageView mosqueImage;
private RecyclerView recyclerView;
// private ArrayList<OrganisationModel> organisationModelArrayList = new ArrayList<>();
private ArrayList<Organisation> organisationList = new ArrayList<>();
// Organisation organisationList = new Organisation();
private OrganisationAdapter organisationAdapter;
private OrganisationFragment.MainPagerAdapter adapter;
private Organisation organisation;
private Context context;
private ApiRequest apiRequest;
public Organisation selectedOrganization = null;
public OrganisationFragment() {
// Required empty public constructor
}
public View view = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_organisation, container, false);
recyclerView = rootView.findViewById(R.id.organisation_recyclerview);
mosqueImage = rootView.findViewById(R.id.donate_fragment_mosque_image);
// organisationModelArrayList.clear();
prepareOrganisationData();
// Organisation org = ParentOrganisationActivity.selectedOrganization;
// recyclerView.setAdapter();
return rootView;
}
//here create parse
public static OrganisationFragment newInstance(Organisation organisation) {
OrganisationFragment fragment = new OrganisationFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
fragment.selectedOrganization = organisation;
return fragment;
}
public class MainPagerAdapter extends FragmentStatePagerAdapter {
private FragmentManager fragmentManager;
private final ArrayList<Fragment> fragmentList = new ArrayList<>();
private final ArrayList<String> fragmentTitleList = new ArrayList<>();
MainPagerAdapter(FragmentManager fm) {
super(fm);
fragmentManager = fm;
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
#Override
public int getCount() {
return fragmentList.size();
}
#Override
public CharSequence getPageTitle(int position) {
return fragmentTitleList.get(position);
}
void addFragment(Fragment fragment, String title) {
fragmentList.add(fragment);
fragmentTitleList.add(title);
}
}
//Organisation data change here
private void prepareOrganisationData() {
// OrganisationModel organisationModel = new OrganisationModel("Masjid Sultan Abu Bakar", "Kuala Lumpur", R.drawable.mosque_1);
// this.organisationModelArrayList.add(organisationModel);
//
// organisationModel = new OrganisationModel("Masjid Zahir", "Kuala Lumpur", R.drawable.mosque_2);
// this.organisationModelArrayList.add(organisationModel);
Bundle extras = getActivity().getIntent().getExtras();
if (extras == null) {
selectedOrganization = null;
} else {
Gson gson = new Gson();
// Gson gson = new GsonBuilder().serializeNulls().create();
selectedOrganization = gson.fromJson(extras.getString("org"), Organisation.class);
Organisation org = selectedOrganization;
Picasso.with(context).load(org.getImage()).into(mosqueImage);
}
ApiRequest.getInstance().getOrganisationIdDetails(getActivity(), selectedOrganization.id, new ApiRequest.GetAllOrgIdDetailsCallback() {
#Override
public void getAllOrgIdDetailsSuccess(ArrayList<Organisation> result) {
organisationList = result;
organisationAdapter = new OrganisationAdapter(organisationList, context);
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 2);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(organisationAdapter);
}
#Override
public void getAllOrgDetailsFail(String message) {
}
});
}
/* TODO
add onClick listener to each object
*/
}
This is my Fragment Adapter..
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.baracode.eilsan.R;
import com.baracode.eilsan.donate.organisation.OrganisationActivity;
import com.baracode.eilsan.model.Caused;
import com.baracode.eilsan.model.Organisation;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
public class OrganisationAdapter extends RecyclerView.Adapter<OrganisationAdapter.MyViewHolder> {
private Context context;
// private final ArrayList<OrganisationModel> organisationModelList;
ArrayList<Organisation> organisationModelList;
public OrganisationAdapter(ArrayList<Organisation> organisationModelList , Context context) {
this.organisationModelList = organisationModelList;
this.context = context;
}
#Override
public OrganisationAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_organisation_recyclerview, parent, false);
return new OrganisationAdapter.MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(OrganisationAdapter.MyViewHolder holder, int position) {
// OrganisationModel organisationModel = organisationModelList.get(position);
final Organisation organisationModel = organisationModelList.get(position);
holder.organisationName.setText(organisationModel.getName());
holder.cityName.setText(organisationModel.getAddress());
// holder.mosqueImage.setImageResource(organisationModel.getOrganisationImage());
Picasso.with(context)
.load(organisationModel.getImage())
.into(holder.mosqueImage);
holder.headlineLinearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent;
switch (view.getId()) {
case R.id.organisation_linearlayout:
intent = new Intent(view.getContext(), OrganisationActivity.class);
view.getContext().startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return organisationModelList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView organisationName, cityName;
public ImageView mosqueImage;
public LinearLayout headlineLinearLayout;
public MyViewHolder(View view) {
super(view);
organisationName = view.findViewById(R.id.donate_parent_organisation_name);
cityName = view.findViewById(R.id.donate_parent_organisation_city_name);
mosqueImage = view.findViewById(R.id.donate_parent_organisation_image);
headlineLinearLayout = view.findViewById(R.id.organisation_linearlayout);
}
}
/* TODO
* Implement on click listener on the recyclerview
* */
}
This is my Fragment Model(Setter n Getter)
public class OrganisationModel {
private String organisationName = "";
private String cityName = "";
private int organisationImage;
public int getOrganisationImage() {
return organisationImage;
}
public void setOrganisationImage(int organisationImage) {
this.organisationImage = organisationImage;
}
public String getOrganisationName() {
return organisationName;
}
public void setOrganisationName(String organisationName) {
this.organisationName = organisationName;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public OrganisationModel(String organisationName, String cityName, int organisationImage) {
this.organisationName = organisationName;
this.cityName = cityName;
this.organisationImage = organisationImage;
}
}
This is MyApirequest class to get the Json Object
public void getOrganisationIdDetails(final Context context, String organizationIdDetails, final GetAllOrgIdDetailsCallback apiCallback) {
String accessToken = LocalData.getInstance().loadStringData(LocalData.KEY_ACCESS_TOKEN);
Call<JsonObject> call = apiService.getOrgIdDetails("Bearer " + accessToken, organizationIdDetails);
call.enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
Log.d("eihsan", "getOrgIdDetails: " + response.body().toString());
Boolean isSuccess = response.body().get("success").getAsBoolean();
if (isSuccess) {
JsonObject jsonData = response.body().get("data").getAsJsonObject();
//JsonArray jsonArray = jsonData.getAsJsonArray("data");
Organisation org = new Organisation();
// ArrayList<Organisation> organisationList = new ArrayList<>();
org.setId(jsonData.get("id").getAsString());
org.setParentId(jsonData.get("parent_id").toString());
org.setName(jsonData.get("name").getAsString());
org.setDescription(jsonData.get("description").getAsString());
org.setImage(jsonData.get("image").getAsString());
org.setPhone_no(jsonData.get("phone_no").getAsString());
org.setFax(jsonData.get("fax").getAsString());
org.setAddress(jsonData.get("address").getAsString());
org.setLatitude(jsonData.get("latitude").getAsString());
org.setLongitude(jsonData.get("longitude").getAsString());
org.setDonorCount(jsonData.get("donors_count").getAsString());
apiCallback.getAllOrgIdDetailsSuccess(org);
} else {
apiCallback.getAllOrgDetailsFail("Data Error occurred");
}
}
#Override
public void onFailure(Call<JsonObject> call, Throwable throwable) {
}
});
}
AFTER FEW MONTH, I SOLVED THE PROBLEM..
Use retrofit library and call the api before display. So here how to call the data for future reference....
public void getOneOrg(String orgId, final GetOneOrgCallback apiCallback) {
String auth = "Bearer " + LocalData.getInstance().loadStringData(LocalData.SP_KEY_ACCESS_TOKEN);
Call<JsonObject> call = apiService.getOneOrg(auth, orgId);
call.enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
StaticFunction.showLogD("getOneOrg: " + response.body().toString());
Boolean isSuccess = response.body().get("success").getAsBoolean();
if (isSuccess) {
JsonObject jsonData = response.body().get("data").getAsJsonObject();
Organization org = gson.fromJson(jsonData, Organization.class);
apiCallback.getOneOrgSuccess(org);
} else {
apiCallback.getOneOrgFail("Data error");
}
}
#Override
public void onFailure(Call<JsonObject> call, Throwable throwable) {
apiCallback.getOneOrgFail("Data error");
}
});
}
Here how i called the json object in API "Organization" is the java file for each variables in api.
Inside my tab bar i want to show my data in Recycler view by using json parsing using volley library. I parsed the data and it showing in toast perfectly.But in Recycler view its not showing Here is my codes.
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.JsonObjectRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import javax.xml.transform.ErrorListener;
import info.tatwa.adupter.AdupterBoxOffice;
import info.tatwa.extras.Keys;
import info.tatwa.extras.UrlEndPoint;
import info.tatwa.login.L;
import info.tatwa.model.Movies;
import info.tatwa.network.MyApplication;
import info.tatwa.network.VolleySingleton;
import info.tatwa.newnav.R;
import info.tatwa.extras.UrlEndPoint.*;
import info.tatwa.extras.Keys.EndpointBoxOffice.*;
public class FragmentBoxOffice extends Fragment {
private VolleySingleton volleySingleton;
private RequestQueue requestQueue;
private AdupterBoxOffice adupterBoxOffice;
private ArrayList<Movies>listMovie = new ArrayList<>();
private ImageLoader imageLoader;
private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
public static final String ROTET_TOMATO_URL_BOX_OFFICE="My url is here"
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private RecyclerView listMovieHits;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment FragmentBoxOffice.
*/
public static FragmentBoxOffice newInstance(String param1, String param2) {
FragmentBoxOffice fragment = new FragmentBoxOffice();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public static String getRequestUrl(int limit){
//ROTET_TOMATO_URL_BOX_OFFICE+"?apikey="+ MyApplication.ROTET_TOMATO_API_KEY+"&limit="+limit;
return UrlEndPoint.URL_BOX_OFFICE +
UrlEndPoint.URL_CHAR_QUASTIAN+
UrlEndPoint.URL_CHAR_PAREM_APIKEY +
MyApplication.ROTET_TOMATO_API_KEY +
UrlEndPoint.URL_CHAR_APPEND+
UrlEndPoint.URL_CHAR_PAREM_LIMIT + limit;
}
public FragmentBoxOffice() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
volleySingleton = VolleySingleton.getsInstance();
requestQueue = volleySingleton.getmRequestQueue();
senJsonRequest();
}
public void senJsonRequest(){
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, getRequestUrl(10), (String)null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
paresJSONResponse(response);
listMovie =paresJSONResponse(response);
adupterBoxOffice.setMovieList(listMovie);
L.t(getActivity(), response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(),"Error"+error.getMessage(),Toast.LENGTH_SHORT).show();
}
});
requestQueue.add(request);
}
public ArrayList<Movies> paresJSONResponse(JSONObject response){
ArrayList<Movies> listMovie = new ArrayList<>();
if(response ==null|| response.length()==0 ){
return null;
}
try {
StringBuilder data = new StringBuilder();
JSONArray arrayMovie = response.getJSONArray(Keys.EndpointBoxOffice.KEY_MOVIES);
Log.v("BIKASH", "JSON Object id" + arrayMovie);
for(int i = 0; i<arrayMovie.length();i++){
JSONObject currentMovies= arrayMovie.getJSONObject(i);
Long id =currentMovies.getLong(Keys.EndpointBoxOffice.KEY_ID);
String title=currentMovies.getString(Keys.EndpointBoxOffice.KEY_TITLE);
JSONObject objectReleaseDates=currentMovies.getJSONObject(Keys.EndpointBoxOffice.KEY_RELEASE_DATES);
String releaseDate=null;
if(objectReleaseDates.has(Keys.EndpointBoxOffice.KEY_THEATER)){
releaseDate = objectReleaseDates.getString(Keys.EndpointBoxOffice.KEY_THEATER);
}
else {
releaseDate="NA";
}
int audianceRatting=-1;
JSONObject objectRatting = currentMovies.getJSONObject(Keys.EndpointBoxOffice.KEY_RATINGS);
{
if(objectRatting.has(Keys.EndpointBoxOffice.KEY_AUDIENCE_SCORE)){
audianceRatting=objectRatting.getInt(Keys.EndpointBoxOffice.KEY_AUDIENCE_SCORE);
}
}
String synuypsis = currentMovies.getString(Keys.EndpointBoxOffice.KEY_SYNOPSIS);
String urlThumbnel = null;
JSONObject objPoster = currentMovies.getJSONObject(Keys.EndpointBoxOffice.KEY_THUMBNAIL);
if(objPoster.has(Keys.EndpointBoxOffice.KEY_THUMBNAIL)){
urlThumbnel = objPoster.getString(Keys.EndpointBoxOffice.KEY_THUMBNAIL);
}
Movies movie =new Movies();
movie.setId(id);
movie.setTitle(title);
Date date = dateFormat.parse(releaseDate);
movie.setReleaseDateTheater(date);
movie.setAudienceScore(audianceRatting);
movie.setSynopsis(synuypsis);
movie.setUrlThumbnail(urlThumbnel);
listMovie.add(movie);
// data.append(id + "\n");
}
L.t(getActivity(),listMovie.toString());
} catch (JSONException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
return listMovie;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view =inflater.inflate(R.layout.fragment_fragment_box_office, container, false);
listMovieHits =(RecyclerView)view.findViewById(R.id.listMovieHits);
listMovieHits.setLayoutManager(new LinearLayoutManager(getActivity()));
adupterBoxOffice = new AdupterBoxOffice(getActivity());
listMovieHits.setAdapter(adupterBoxOffice);
senJsonRequest();
return view;
}
}
My Adupter
import android.content.Context;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import java.util.ArrayList;
import info.tatwa.model.Movies;
import info.tatwa.myfragment.FragmentBoxOffice;
import info.tatwa.network.VolleySingleton;
import info.tatwa.newnav.R;
public class AdupterBoxOffice extends RecyclerView.Adapter<AdupterBoxOffice.ViewHolderBoxOffice> {
private LayoutInflater layoutInflater;
FragmentBoxOffice activity;
private ArrayList<Movies> listMovie = new ArrayList<>();
private VolleySingleton volleySingleton;
private ImageLoader imageLoader;
public AdupterBoxOffice(Context context){
layoutInflater=LayoutInflater.from(context);
volleySingleton=VolleySingleton.getsInstance();
imageLoader = volleySingleton.getImageLoader();
}
public void setMovieList(ArrayList<Movies>listMovie){
this.listMovie = listMovie;
notifyItemRangeChanged(0,listMovie.size());
}
#Override
public ViewHolderBoxOffice onCreateViewHolder(ViewGroup parent, int viewType) {
layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.movie_list_itom,parent,false);
ViewHolderBoxOffice viewHolder =new ViewHolderBoxOffice(view);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolderBoxOffice holder, int position) {
Movies currentMovie =listMovie.get(position);
holder.movieTitle.setText(currentMovie.getTitle());
holder.movieReleaseDate.setText(currentMovie.getReleaseDateTheater().toString());
holder.movieRatting.setRating(currentMovie.getAudienceScore()/20.0f);
String urlThumbnel = currentMovie.getUrlThumbnail();
if(urlThumbnel!=null){
imageLoader.get(urlThumbnel, new ImageLoader.ImageListener() {
#Override
public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
holder.imagePoster.setImageBitmap(response.getBitmap());
}
#Override
public void onErrorResponse(VolleyError error) {
}
});
}
}
#Override
public int getItemCount() {
return listMovie.size();
}
static class ViewHolderBoxOffice extends RecyclerView.ViewHolder {
private ImageView imagePoster;
private TextView movieTitle;
private TextView movieReleaseDate;
private RatingBar movieRatting;
public ViewHolderBoxOffice(View itemView) {
super(itemView);
imagePoster=(ImageView)itemView.findViewById(R.id.movieThumbnail);
movieTitle =(TextView)itemView.findViewById(R.id.movieTitle);
movieReleaseDate=(TextView)itemView.findViewById(R.id.movieReleaseDate);
movieRatting=(RatingBar)itemView.findViewById(R.id.movieAudienceScore);
}
}
}
And My Model class
import android.os.Parcel;
import android.os.Parcelable;
import java.util.Date;
public class Movies{
private long id;
private String title;
private Date releaseDateTheater;
private int audienceScore;
private String synopsis;
private String urlThumbnail;
private String urlSelf;
private String urlCast;
private String urlReviews;
private String urlSimilar;
public Movies() {
}
public Movies(long id,
String title,
Date releaseDateTheater,
int audienceScore,
String synopsis,
String urlThumbnail,
String urlSelf,
String urlCast,
String urlReviews,
String urlSimilar) {
this.id = id;
this.title = title;
this.releaseDateTheater = releaseDateTheater;
this.audienceScore = audienceScore;
this.synopsis = synopsis;
this.urlThumbnail = urlThumbnail;
this.urlSelf = urlSelf;
this.urlCast = urlCast;
this.urlReviews = urlReviews;
this.urlSimilar = urlSimilar;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Date getReleaseDateTheater() {
return releaseDateTheater;
}
public void setReleaseDateTheater(Date releaseDateTheater) {
this.releaseDateTheater = releaseDateTheater;
}
public int getAudienceScore() {
return audienceScore;
}
public void setAudienceScore(int audienceScore) {
this.audienceScore = audienceScore;
}
public String getSynopsis() {
return synopsis;
}
public void setSynopsis(String synopsis) {
this.synopsis = synopsis;
}
public String getUrlThumbnail() {
return urlThumbnail;
}
public void setUrlThumbnail(String urlThumbnail) {
this.urlThumbnail = urlThumbnail;
}
public String getUrlSelf() {
return urlSelf;
}
public void setUrlSelf(String urlSelf) {
this.urlSelf = urlSelf;
}
public String getUrlCast() {
return urlCast;
}
public void setUrlCast(String urlCast) {
this.urlCast = urlCast;
}
public String getUrlReviews() {
return urlReviews;
}
public void setUrlReviews(String urlReviews) {
this.urlReviews = urlReviews;
}
public String getUrlSimilar() {
return urlSimilar;
}
public void setUrlSimilar(String urlSimilar) {
this.urlSimilar = urlSimilar;
}
#Override
public String toString() {
return "\nID: " + id +
"\nTitle " + title +
"\nDate " + releaseDateTheater +
"\nSynopsis " + synopsis +
"\nScore " + audienceScore +
"\nurlThumbnail " + urlThumbnail +
"\nurlSelf " + urlSelf +
"\nurlCast " + urlCast +
"\nurlReviews " + urlReviews +
"\nurlSimilar " + urlSimilar +
"\n";
}
}
Please help me out .. Thanks in advance ..
After adupterBoxOffice.setMovieList(listMovie);
try add adupterBoxOffice.notifyDataSetChanged();
I found my solution.I put some wrong key during pars the Json. That's why my ArrayList returning zero.
Many many thanks to all for helping me out.