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.
Related
I am using a adapter for homework and at that adaper there is also a adapter which contains images and i am getting urls from firebase database here i have code for more information.
what product.getUrl is actually containing
D/ADAPTER_IMAGE: [https://firebasestorage.googleapis.com/v0/b/ngf-connection.appspot.com/o/uploads%2FBtech%20CSE%20I%2F917838245010_status_66703835b57940eb8812f50c09aacbd1.jpg?alt=media&token=b9de8228-36f4-496a-9ca5-dc0640f2eb9e
2020-04-08 18:13:10.331 12057-12057/com.ngfcet.ngfconnection D/ADAPTER_IMAGE: https://firebasestorage.googleapis.com/v0/b/ngf-connection.appspot.com/o/uploads%2FBtech%20CSE%20I%2F917248800852_status_200b86ad9f0d43e8aab65037b1588f32.jpg?alt=media&token=47b2f7ed-3cf1-4aea-9883-0f552e24754e
2020-04-08 18:13:10.344 12057-12057/com.ngfcet.ngfconnection D/ADAPTER_IMAGE: https://firebasestorage.googleapis.com/v0/b/ngf-connection.appspot.com/o/uploads%2FBtech%20CSE%20I%2F918400606848_status_cdad13e789b049fcbe4c396cf7170fa6.jpg?alt=media&token=fbb825bf-1aab-4056-b12b-01ca458a21a5
2020-04-08 18:13:10.355 12057-12057/com.ngfcet.ngfconnection D/ADAPTER_IMAGE: https://firebasestorage.googleapis.com/v0/b/ngf-connection.appspot.com/o/uploads%2FBtech%20CSE%20I%2FIMG-20200408-WA0003.jpg?alt=media&token=fb16dd18-26aa-4d28-86ea-de32dbbdbeb4]
Adapter 1: Main Line is with comment //setting another adaper from here
import android.content.Context;
import android.net.Uri;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.database.ValueEventListener;
import com.ngfcet.ngfconnection.R;
import com.ngfcet.ngfconnection.SendHomeworkActivity;
import com.ngfcet.ngfconnection.Util.CoreHelper;
import com.ngfcet.ngfconnection.models.HomeworkStudents;
import com.ngfcet.ngfconnection.models.ImageHomeworkModel;
import com.ngfcet.ngfconnection.models.ImagesModel;
import java.net.URI;
import java.net.URISyntaxException;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;
public class HomeworkAdapter extends RecyclerView.Adapter<HomeworkAdapter.ProductViewHolder> {
//this context we will use to inflate the layout
private Context mCtx;
String dateValue, datePrevValue;
URI myUri;
//we are storing all the products in a list
private List<HomeworkStudents> productList;
private static SingleClickListener sClickListener;
ImagesHomeworkAdapter adapter;
List<ImageHomeworkModel> imagesList;
CoreHelper coreHelper;
private static int sSelected = -1;
//getting the context and product list with constructor
public HomeworkAdapter(Context mCtx, List<HomeworkStudents> productList) {
this.mCtx = mCtx;
this.productList = productList;
}
#Override
public ProductViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//inflating and returning our view holder
LayoutInflater inflater = LayoutInflater.from(mCtx);
View view = inflater.inflate(R.layout.recycler_home_work, null);
return new ProductViewHolder(view);
}
#Override
public void onBindViewHolder(ProductViewHolder holder, int position) {
//getting the product of the specified position
final HomeworkStudents product = productList.get(position);
//binding the data with the viewholder views
holder.textViewDescription.setText(product.getDescription());
holder.textViewSubject.setText(product.getSubject());
coreHelper = new CoreHelper(mCtx);
imagesList = new ArrayList<>();
adapter = new ImagesHomeworkAdapter(mCtx, imagesList);
GridLayoutManager gridLayoutManager = new GridLayoutManager(mCtx, 4);
holder.recyclerViewHomeWorkImages.setHasFixedSize(true);
holder.recyclerViewHomeWorkImages.setLayoutManager(gridLayoutManager);
holder.recyclerViewHomeWorkImages.setAdapter(adapter);
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy & kk:mm:ss");
Date sourceDate = null;
try {
sourceDate = dateFormat.parse(product.getDateTime());
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat targetFormat = new SimpleDateFormat("kk:mm");
String targetdatevalue = targetFormat.format(sourceDate);
holder.textViewDateTime.setText(targetdatevalue);
SimpleDateFormat format1 = new SimpleDateFormat("dd-MM-yyyy & kk:mm:ss");
Date dt1 = null;
try {
dt1 = format1.parse(product.getDateTime());
} catch (ParseException e) {
e.printStackTrace();
}
DateFormat format2 = new SimpleDateFormat("EEEE");
String finalDay = format2.format(dt1);
holder.tvDayHomework.setText(finalDay);
Date realDate = null;
try {
realDate = dateFormat.parse(product.getDateTime());
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat dateHomework = new SimpleDateFormat("dd MMM yyyy");
dateValue = dateHomework.format(realDate);
holder.tvDateHomework.setText(dateValue);
if (sSelected == position) {
holder.textViewDescription.setSingleLine(false);
if (!product.getAttachments().equals("")) {
String urls = product.getAttachments();
String[] urlsArray = urls.split(",");
for (String url : urlsArray) {
Log.d("IMAGE_URL", url);
holder.recyclerViewHomeWorkImages.setVisibility(View.VISIBLE);
holder.imgButtonDownload.setVisibility(View.VISIBLE);
imagesList.add(new ImageHomeworkModel(url, "Name")); // setting another adapter from here
}
}
// holder.mTextView.setBackgroundColor(Color.parseColor("#CBEEEEEE"));
// holder.mTextView.setTextColor(Color.parseColor("#FBC02D"));
} else {
holder.textViewDescription.setSingleLine(true);
holder.imgButtonDownload.setVisibility(View.GONE);
holder.recyclerViewHomeWorkImages.setVisibility(View.GONE);
// holder.mTextView.setBackgroundColor(Color.parseColor("#FFFFFF"));
// holder.mTextView.setTextColor(Color.parseColor("#000000"));
}
holder.imgButtonDownload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!product.getAttachments().equals("")) {
StringTokenizer tokenizer = new StringTokenizer(product.getAttachments(), ",");
while (tokenizer.hasMoreTokens()) {
// System.out.println(tokenizer.nextToken());
Log.d("Attachment Token", tokenizer.nextToken());
}
// Toast.makeText(mCtx, product.getAttachments(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(mCtx, "Nothing to download", Toast.LENGTH_SHORT).show();
}
}
});
if (position == 0) {
holder.llDayDateHomework.setVisibility(View.VISIBLE);
} else {
HomeworkStudents previous = productList.get(position - 1);
Date previoudDate = null;
Date otherDate = null;
try {
previoudDate = dateFormat.parse(previous.getDateTime());
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat previousDateHomework = new SimpleDateFormat("dd MMM yyyy");
String previousDateValue = previousDateHomework.format(previoudDate);
try {
otherDate = dateFormat.parse(product.getDateTime());
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat otherDateHomework = new SimpleDateFormat("dd MMM yyyy");
String otherDateValue = otherDateHomework.format(otherDate);
if (previousDateValue.equals(otherDateValue)) {
holder.llDayDateHomework.setVisibility(View.GONE);
} else {
holder.llDayDateHomework.setVisibility(View.VISIBLE);
}
}
}
#Override
public int getItemCount() {
return productList.size();
}
class ProductViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView textViewDescription, textViewSubject, textViewDateTime, tvDayHomework, tvDateHomework;
LinearLayout llDayDateHomework;
CardView cardViewHomework;
ImageButton imgButtonDownload;
RecyclerView recyclerViewHomeWorkImages;
public ProductViewHolder(View itemView) {
super(itemView);
textViewDescription = itemView.findViewById(R.id.tvTitleHomework);
textViewSubject = itemView.findViewById(R.id.tvSubjectHomework);
textViewDateTime = itemView.findViewById(R.id.tvDateTimeHomework);
tvDayHomework = itemView.findViewById(R.id.tvDayHomework);
tvDateHomework = itemView.findViewById(R.id.tvDateHomework);
llDayDateHomework = itemView.findViewById(R.id.llDayDateHomework);
cardViewHomework = itemView.findViewById(R.id.cardViewHomework);
imgButtonDownload = itemView.findViewById(R.id.imgButtonDownload);
recyclerViewHomeWorkImages = itemView.findViewById(R.id.recyclerViewHomeWorkImages);
cardViewHomework.setOnClickListener(this);
}
#Override
public void onClick(View view) {
sSelected = getAdapterPosition();
sClickListener.onItemClickListener(getAdapterPosition(), view);
}
}
public void selectedItem() {
notifyDataSetChanged();
}
public void setOnItemClickListener(SingleClickListener clickListener) {
sClickListener = clickListener;
}
public interface SingleClickListener {
void onItemClickListener(int position, View view);
}
}
Adapter 2: Main line is with comment //Setting image with picasso
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.ngfcet.ngfconnection.R;
import com.ngfcet.ngfconnection.models.ImageHomeworkModel;
import com.squareup.picasso.Picasso;
import java.util.List;
public class ImagesHomeworkAdapter extends RecyclerView.Adapter<ImagesHomeworkAdapter.ImageViewHolder> {
Context context;
List<ImageHomeworkModel> imagesList;
public ImagesHomeworkAdapter(Context context, List<ImageHomeworkModel> imagesList) {
this.context = context;
this.imagesList = imagesList;
}
#NonNull
#Override
public ImagesHomeworkAdapter.ImageViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.picked_img_layout, parent, false);
return new ImagesHomeworkAdapter.ImageViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ImagesHomeworkAdapter.ImageViewHolder holder, final int position) {
ImageHomeworkModel product = imagesList.get(position);
holder.btnRemove.setVisibility(View.GONE);
Picasso.with(context).load(product.getUrls()).into(holder.imgSetData); //Setting image with picasso
Log.d("ADAPTER_IMAGE_URL", product.getUrls());
if (holder.imgSetData.getDrawable() == null) {
holder.imgSetData.setImageResource(R.drawable.ic_pdf);
}
}
#Override
public int getItemCount() {
return imagesList.size();
}
class ImageViewHolder extends RecyclerView.ViewHolder {
ImageView btnRemove, imgSetData;
public ImageViewHolder(#NonNull View itemView) {
super(itemView);
btnRemove = itemView.findViewById(R.id.imgDeleteSelectedImage);
imgSetData = itemView.findViewById(R.id.imgSetData);
}
}
}
Model Class
public class ImageHomeworkModel {
private String Urls;
private String fileName;
public ImageHomeworkModel(String urls, String fileName) {
Urls = urls;
this.fileName = fileName;
}
public ImageHomeworkModel(String[] urlsArray, String name) {
}
public String getUrls() {
return Urls;
}
public void setUrls(String urls) {
Urls = urls;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
}
Please help me to solve my issue picasso not showing image even logcan isn't showing anything
Hey i got the answer of my question problem is square bracets
url containg [ ] in starting and end but
replace is not working
I'm doing
product.getUrls().replace("[", "");
product.getUrls().replace("]", "");
but it's not replacing sqaure btackets.
Currently working on a ExpandableListView in android using RecyclerView. I have done almost all the thing but somehow I am getting a NullpointerException which I can not sort out.Any help will be appreciated.
I am sharing the code snippet and also the git link
Used Library
Code I have tried
The app is crasing at this line in the apadter class
public DriverScheduleExpandableAdapter(Context mContext, #NonNull
List<DriverSchedule.Schedules> parentList) {
super(parentList);//////**this is where the app is crashing**
mRecipeList = parentList;
mInflater = LayoutInflater.from(mContext);
}
Error coming is :
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'java.util.Iterator java.util.List.iterator()' on a null object reference
at com.bignerdranch.expandablerecyclerview.model.ExpandableWrapper.generateChildItemList(ExpandableWrapper.java:99)
at com.bignerdranch.expandablerecyclerview.model.ExpandableWrapper.<init>(ExpandableWrapper.java:33)
at com.bignerdranch.expandablerecyclerview.ExpandableRecyclerAdapter.generateParentWrapper(ExpandableRecyclerAdapter.java:1357)
at com.bignerdranch.expandablerecyclerview.ExpandableRecyclerAdapter.generateFlattenedParentChildList(ExpandableRecyclerAdapter.java:1326)
at com.bignerdranch.expandablerecyclerview.ExpandableRecyclerAdapter.<init>(ExpandableRecyclerAdapter.java:120)
at com.rtstl.expandablelistview.adapter.DriverScheduleExpandableAdapter.<init>(DriverScheduleExpandableAdapter.java:23)
at com.rtstl.expandablelistview.MainActivity.inflateadapter(MainActivity.java:50)
at com.rtstl.expandablelistview.MainActivity.initview(MainActivity.java:41)
at com.rtstl.expandablelistview.MainActivity.onCreate(MainActivity.java:36)
at android.app.Activity.performCreate(Activity.java:6357)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2408)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2515)
at android.app.ActivityThread.access$1000(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1379)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5571)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:745)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:635)
MainActivity.java
package com.rtstl.expandablelistview;
import android.content.Context;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.rtstl.expandablelistview.adapter.DriverScheduleAdapter;
import com.rtstl.expandablelistview.adapter.DriverScheduleExpandableAdapter;
import com.rtstl.expandablelistview.databinding.ActivityMainBinding;
import com.rtstl.expandablelistview.model.DriverSchedule;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class MainActivity extends AppCompatActivity {
ActivityMainBinding binding;
Context mContext;
DriverSchedule list_driver;
DriverScheduleAdapter adapter;
DriverScheduleExpandableAdapter adapterExp;
Gson gson;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext=this;
gson=new Gson();
initview();
}
private void initview() {
binding= DataBindingUtil.setContentView(this, R.layout.activity_main);
inflateadapter();
}
private void inflateadapter() {
////for reading file from raw folder otherwise it's not required
list_driver= gson.fromJson(readFileFromRawDirectory(R.raw.driverschedule), new TypeToken<DriverSchedule>(){}.getType());
////////////////////////////////////////
Toast.makeText(mContext,""+list_driver.getData().getSclist().size(),Toast.LENGTH_SHORT).show();
adapterExp = new DriverScheduleExpandableAdapter(mContext, list_driver.getData().getSclist());
binding.rvRecycle.setLayoutManager(new LinearLayoutManager(this));
binding.rvRecycle.setAdapter(adapter);
}
private String readFileFromRawDirectory(int resourceId){
InputStream iStream = this.getResources().openRawResource(resourceId);
ByteArrayOutputStream byteStream = null;
try {
byte[] buffer = new byte[iStream.available()];
iStream.read(buffer);
byteStream = new ByteArrayOutputStream();
byteStream.write(buffer);
byteStream.close();
iStream.close();
//inflateadapter();
} catch (IOException e) {
e.printStackTrace();
}
return byteStream.toString();
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/rv_Recycle"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
</layout>
Adapter class
package com.rtstl.expandablelistview.adapter;
import android.content.Context;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.bignerdranch.expandablerecyclerview.ExpandableRecyclerAdapter;
import com.rtstl.expandablelistview.R;
import com.rtstl.expandablelistview.model.DriverSchedule;
import java.util.List;
public class DriverScheduleExpandableAdapter extends ExpandableRecyclerAdapter<DriverSchedule.Schedules, DriverSchedule.Alloted_kids, RouteViewHolder, KidViewHolder> {
private LayoutInflater mInflater;
private List<DriverSchedule.Schedules> mRecipeList;
private static final int PARENT_NORMAL = 1;
private static final int CHILD_NORMAL = 3;
public DriverScheduleExpandableAdapter(Context mContext, #NonNull List<DriverSchedule.Schedules> parentList) {
super(parentList);//////**this is where the app is crashing**
mRecipeList = parentList;
mInflater = LayoutInflater.from(mContext);
}
#NonNull
#Override
public RouteViewHolder onCreateParentViewHolder(#NonNull ViewGroup parentViewGroup, int viewType) {
View recipeView;
switch (viewType) {
default:
case PARENT_NORMAL:
recipeView = mInflater.inflate(R.layout.group_item, parentViewGroup, false);
break;
}
return new RouteViewHolder(recipeView);
}
#NonNull
#Override
public KidViewHolder onCreateChildViewHolder(#NonNull ViewGroup childViewGroup, int viewType) {
View ingredientView;
switch (viewType) {
default:
case CHILD_NORMAL:
ingredientView = mInflater.inflate(R.layout.child_item, childViewGroup, false);
break;
}
return new KidViewHolder(ingredientView);
}
#Override
public void onBindParentViewHolder(#NonNull RouteViewHolder parentViewHolder, int parentPosition, #NonNull DriverSchedule.Schedules parent) {
parentViewHolder.bind(parent);
}
#Override
public void onBindChildViewHolder(#NonNull KidViewHolder childViewHolder, int parentPosition, int childPosition, #NonNull DriverSchedule.Alloted_kids child) {
childViewHolder.bind(child);
}
#Override
public int getParentViewType(int parentPosition) {
return PARENT_NORMAL;
}
#Override
public int getChildViewType(int parentPosition, int childPosition) {
return CHILD_NORMAL;
}
#Override
public boolean isParentViewType(int viewType) {
return viewType == PARENT_NORMAL;
}
}
DriverSchedule.java
package com.rtstl.expandablelistview.model;
import android.databinding.BaseObservable;
import com.bignerdranch.expandablerecyclerview.model.Parent;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.List;
/**
* Created by User1 on 09-03-2018.
*/
public class DriverSchedule extends BaseObservable {
#SerializedName("status")
#Expose
public String status;
#SerializedName("msg")
#Expose
public String msg;
#SerializedName("data")
#Expose
public Data data;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
public class Data {
#SerializedName("schedules")
#Expose
List<Schedules> sclist;
#SerializedName("driver_details")
#Expose
Driver_details driver_details;
public List<Schedules> getSclist() {
return sclist;
}
public void setSclist(List<Schedules> sclist) {
this.sclist = sclist;
}
public Driver_details getDriver_details() {
return driver_details;
}
public void setDriver_details(Driver_details driver_details) {
this.driver_details = driver_details;
}
}
public class Schedules implements Parent<Alloted_kids> {
#SerializedName("is_active")
#Expose
public String is_active;
#SerializedName("route_details")
#Expose
public Route_details route_details;
#SerializedName("alloted_kids")
#Expose
public List<Alloted_kids> alloted_kids;
public String getIs_active() {
return is_active;
}
public void setIs_active(String is_active) {
this.is_active = is_active;
}
public Route_details getRoute_details() {
return route_details;
}
public void setRoute_details(Route_details route_details) {
this.route_details = route_details;
}
public List<Alloted_kids> getAlloted_kids() {
return alloted_kids;
}
public void setAlloted_kids(List<Alloted_kids> alloted_kids) {
this.alloted_kids = alloted_kids;
}
#Override
public List<Alloted_kids> getChildList() {
return null;
}
#Override
public boolean isInitiallyExpanded() {
return false;
}
}
public class Driver_details {
#SerializedName("driver_details")
#Expose
public Driver_details1 driver_details;
public Driver_details1 getDriver_details() {
return driver_details;
}
public void setDriver_details(Driver_details1 driver_details) {
this.driver_details = driver_details;
}
}
public class Route_details {
#SerializedName("ds_id")
#Expose
public String ds_id;
#SerializedName("kidpool_route_id")
#Expose
public String kidpool_route_id;
public String getDs_id() {
return ds_id;
}
public void setDs_id(String ds_id) {
this.ds_id = ds_id;
}
public String getKidpool_route_id() {
return kidpool_route_id;
}
public void setKidpool_route_id(String kidpool_route_id) {
this.kidpool_route_id = kidpool_route_id;
}
}
public class Alloted_kids {
#SerializedName("kid_name")
#Expose
public String kid_name;
#SerializedName("kid_image")
#Expose
public String kid_image;
public String getKid_name() {
return kid_name;
}
public void setKid_name(String kid_name) {
this.kid_name = kid_name;
}
public String getKid_image() {
return kid_image;
}
public void setKid_image(String kid_image) {
this.kid_image = kid_image;
}
}
public class Driver_details1 {
#SerializedName("driver_id")
#Expose
public String driver_id;
#SerializedName("driver_name")
#Expose
public String driver_name;
public String getDriver_id() {
return driver_id;
}
public void setDriver_id(String driver_id) {
this.driver_id = driver_id;
}
public String getDriver_name() {
return driver_name;
}
public void setDriver_name(String driver_name) {
this.driver_name = driver_name;
}
}
}
KidViewHolder.java
package com.rtstl.expandablelistview.adapter;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.TextView;
import com.bignerdranch.expandablerecyclerview.ChildViewHolder;
import com.rtstl.expandablelistview.R;
import com.rtstl.expandablelistview.model.DriverSchedule;
class KidViewHolder extends ChildViewHolder{
private TextView mIngredientTextView;
public KidViewHolder(#NonNull View itemView) {
super(itemView);
mIngredientTextView = (TextView) itemView.findViewById(R.id.tv_childname);
}
public void bind(#NonNull DriverSchedule.Alloted_kids ingredient) {
mIngredientTextView.setText(ingredient.getKid_name());
}
}
RouteViewHolder.java
package com.rtstl.expandablelistview.adapter;
import android.annotation.SuppressLint;
import android.os.Build;
import android.support.annotation.NonNull;
import android.view.View;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.TextView;
import com.bignerdranch.expandablerecyclerview.ParentViewHolder;
import com.rtstl.expandablelistview.R;
import com.rtstl.expandablelistview.model.DriverSchedule;
class RouteViewHolder extends ParentViewHolder {
private static final float INITIAL_POSITION = 0.0f;
private static final float ROTATED_POSITION = 180f;
#NonNull
private final ImageView mArrowExpandImageView;
private TextView mRecipeTextView;
public RouteViewHolder(#NonNull View itemView) {
super(itemView);
mRecipeTextView = (TextView) itemView.findViewById(R.id.group_name);
mArrowExpandImageView = (ImageView) itemView.findViewById(R.id.iv_exp);
}
public void bind(#NonNull DriverSchedule.Schedules recipe) {
mRecipeTextView.setText(recipe.getRoute_details().getKidpool_route_id());
}
#SuppressLint("NewApi")
#Override
public void setExpanded(boolean expanded) {
super.setExpanded(expanded);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
if (expanded) {
mArrowExpandImageView.setRotation(ROTATED_POSITION);
} else {
mArrowExpandImageView.setRotation(INITIAL_POSITION);
}
}
}
#Override
public void onExpansionToggled(boolean expanded) {
super.onExpansionToggled(expanded);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
RotateAnimation rotateAnimation;
if (expanded) { // rotate clockwise
rotateAnimation = new RotateAnimation(ROTATED_POSITION,
INITIAL_POSITION,
RotateAnimation.RELATIVE_TO_SELF, 0.5f,
RotateAnimation.RELATIVE_TO_SELF, 0.5f);
} else { // rotate counterclockwise
rotateAnimation = new RotateAnimation(-1 * ROTATED_POSITION,
INITIAL_POSITION,
RotateAnimation.RELATIVE_TO_SELF, 0.5f,
RotateAnimation.RELATIVE_TO_SELF, 0.5f);
}
rotateAnimation.setDuration(200);
rotateAnimation.setFillAfter(true);
mArrowExpandImageView.startAnimation(rotateAnimation);
}
}
}
See this issue it seems that your list has some null values
https://github.com/bignerdranch/expandable-recycler-view/issues/321
I ran your code and logged your list you have null values in a list
check this method
#Override
public List<Alloted_kids> getChildList() {
return null;
}
this method should return non null value this method only causing problem
use return Collections.emptyList(); instead of return null there
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.
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;
}
}
I have a web service for search in some videos by name.
It pass me the names and images of the videos.
how should I say which image is for which video?
and how shoud i say it to play
package com.video;
import java.util.List;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import com.uvideo.adapter.VideoSearchAdapter;
import com.uvideo.controller.MasterVideoController;
import com.uvideo.model.VideoSearch;
public class ActivityVideoSearch extends Activity implements OnClickListener {
private VideoSearchAdapter videoSearchAdapter;
private GridView grdVideoList;
private List<VideoSearch> listVideo;
private EditText edtKeySearch;
private Button btnSearch;
// -------------------------
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_activity_video_search);
ini();
}
// -------------------------
private void ini() {
grdVideoList = (GridView) findViewById(R.id.grdVideoList);
edtKeySearch = (EditText) findViewById(R.id.edtKeySearch);
btnSearch = (Button) findViewById(R.id.btnSearchVideo);
btnSearch.setOnClickListener(this);
}
// -------------------------
private class SearchVideo extends AsyncTask<String, Void, List<VideoSearch>>{
#Override
protected List<VideoSearch> doInBackground(String... params) {
MasterVideoController masterVideoController = new MasterVideoController();
return masterVideoController.searchVideo(params[0]);
}
#Override
protected void onPostExecute(List<VideoSearch> result) {
super.onPostExecute(result);
listVideo = result;
videoSearchAdapter = new VideoSearchAdapter(getBaseContext(),result);
grdVideoList.setAdapter(videoSearchAdapter);
}
}
// -------------------------
#Override
public void onClick(View v) {
new SearchVideo().execute(edtKeySearch.getText().toString());
}
}
package com.video.adapter;
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.uvideo.R;
import com.uvideo.model.VideoSearch;
public class VideoSearchAdapter extends ArrayAdapter {
private List<VideoSearch> listVideo;
private Context context;
// ---------------------
public VideoSearchAdapter(Context context,List<VideoSearch> listVideo) {
super(context, R.layout.row_video_item, listVideo);
this .listVideo = listVideo;
this.context = context;
}
// ---------------------
#Override
public int getCount() {
return super.getCount();
}
// ---------------------
#Override
public VideoSearch getItem(int position) {
return ((listVideo!=null ? listVideo.get(position):null));
}
// ---------------------
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if(view==null){
LayoutInflater inflater=(LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.row_video_item, parent,false);
}
final VideoSearch video=listVideo.get(position);
if(video!=null){
TextView txtMusicName = (TextView) view.findViewById(R.id.txtVideoName);
txtMusicName.setTextSize(16);
txtMusicName.setText(video.getVideoTitle());
// ---------------------
}
return view;
}
// ---------------------
#Override
public long getItemId(int position) {
return position;
}
}
package com.video.controller;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import com.uvideo.model.VideoDetail;
import com.uvideo.model.VideoSearch;
import com.uvideo.tools.parser.XmlParser;
import com.uvideo.tools.webservice.WebServiceConnection;
import com.uvideo.tools.webservice.WebServiceConnection2;
public class MasterVideoController extends WebServiceConnection {
private String result;
private JSONObject jsonObject;
private JSONArray jsonObjectArray;
private final static String SEARCHKEY="SearchKey";
// -------------------------
public MasterVideoController() {
}
// -------------------------
public List<VideoDetail> getVideoList(){
List<NameValuePair> params = new ArrayList<NameValuePair>();
result = super.sendRequest("MasterVideo", params);
return getVideoListJson(result);
}
// -------------------------
private List<VideoDetail> getVideoListJson(String json){
List<VideoDetail> listVideo = new ArrayList<VideoDetail>();
json = new XmlParser().getxml(json);
try{
jsonObject = new JSONObject(json);
listVideo.add(new VideoDetail(jsonObject.optString(VideoDetail.VIDEOTITLE)
, jsonObject.optString(VideoDetail.VIDEOPATH)
, jsonObject.optString(VideoDetail.VIDEOIMAGE)
, jsonObject.optInt(VideoDetail.VIDEOVISIT)
, jsonObject.optString(VideoDetail.CHANNELNAME)
, jsonObject.optString(VideoDetail.USERNAME)
, jsonObject.optString(VideoDetail.USERIMAGE)
, jsonObject.optInt(VideoDetail.USERVIDEOCOUNT)
, jsonObject.optInt(VideoDetail.USERFOLLOWER)));
//}
return listVideo;
}
catch(Exception exp){
}
return null;
}
// -------------------------
public List<VideoSearch> searchVideo(String requestSearchKey){
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(SEARCHKEY,requestSearchKey));
result = super.sendRequest("SearchByVideoTitle", params);
return getVideoListSearchJson(result);
}
// -------------------------
private List<VideoSearch> getVideoListSearchJson(String json){
List<VideoSearch> listVideo = new ArrayList<VideoSearch>();
json = new XmlParser().getxml(json);
try{
jsonObjectArray = new JSONArray(json);
for (int i = 0; i < jsonObjectArray.length(); i++) {
jsonObject = (JSONObject) jsonObjectArray.get(i);
listVideo.add(new VideoSearch(jsonObject.optString(VideoSearch.VIDEOTITLE)
, jsonObject.optString(VideoSearch.VIDEOPATH)
, jsonObject.optString(VideoSearch.VIDEOIMAGE)
, jsonObject.optInt(VideoSearch.VIDEOVISIT)
, jsonObject.optString(VideoSearch.USERNAME)));
}
return listVideo;
}
catch(Exception exp){
String a = "";
}
return null;
}
// -------------------------
}
package com.video.model;
public class VideoSearch {
// -------------------------
public final static String VIDEOTITLE="VideoTitle";
public final static String VIDEOPATH="VideoPath";
public final static String VIDEOIMAGE="VideoImage";
public final static String VIDEOVISIT="VideoVisit";
public final static String USERNAME="UserName";
// -------------------------
private String videoTitle ;
private String videoPath ;
private String videoImage ;
private int videoVisit ;
private String username ;
// -------------------------
public VideoSearch(String videoTitle , String videoPath ,String videoImage ,int
videoVisit , String username) {
this.videoTitle = videoTitle;
this.videoPath = videoPath;
this.videoImage = videoImage;
this.videoVisit = videoVisit;
this.username = username;
}
// -------------------------
public VideoSearch() {
}
// -------------------------
public String getVideoTitle(){
return videoTitle;
}
public String getvideoPath(){
return videoPath;
}
public String getVideoImage(){
return videoImage;
}
public int getVideoVisit(){
return videoVisit;
}
public String getUsername(){
return username;
}
// -------------------------
public void setVideoTitle(String videoTitle){
this.videoTitle = videoTitle;
}
public void setvideoPath(String videoPath){
this.videoPath = videoPath;
}
public void setVideoImage(String videoImage){
this.videoImage = videoImage;
}
public void setVideoVisit(int videoVisit){
this.videoVisit = videoVisit;
}
public void setUsername(String username){
this.username = username;
}
// -------------------------
}
Firstly, your not clearly stated.
If you are using web service, then you should send the items by coupling them in web service.
Like in JSON
{
video[{"name":"abc","image_url":"kvndskk"}{"name":"abc","image_url":"kvndskk"}{"name":"abc","image_url":"kvndskk"}{"name":"abc","image_url":"kvndskk"}
]
}
here you see you receiving in couple