I'm using GSON to parse a JSON feed like this here:
http://dvz.hj.cx/api/get_recent_posts/?dev=1
My model class looks like this one here:
public class Recent {
#Expose
private String status;
#Expose
private int count;
#Expose
private int count_total;
#Expose
private int pages;
#Expose
private List<Post> posts = new ArrayList<Post>();
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Recent withStatus(String status) {
this.status = status;
return this;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public Recent withCount(int count) {
this.count = count;
return this;
}
public int getCount_total() {
return count_total;
}
public void setCount_total(int count_total) {
this.count_total = count_total;
}
public Recent withCount_total(int count_total) {
this.count_total = count_total;
return this;
}
public int getPages() {
return pages;
}
public void setPages(int pages) {
this.pages = pages;
}
public Recent withPages(int pages) {
this.pages = pages;
return this;
}
public List<Post> getPosts() {
return posts;
}
public void setPosts(List<Post> posts) {
this.posts = posts;
}
public Recent withPosts(List<Post> posts) {
this.posts = posts;
return this;
}
}
As you can see I'm referring to another model class called Post.
The Post model class looks like this one:
public class Post {
#Expose
private int id;
#Expose
private String url;
#Expose
private String title;
#Expose
private String date;
#Expose
private List<Category> categories = new ArrayList<Category>();
#Expose
private List<Object> tags = new ArrayList<Object>();
#Expose
private Author author;
#Expose
private List<Attachment> attachments = new ArrayList<Attachment>();
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Post withId(int id) {
this.id = id;
return this;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Post withUrl(String url) {
this.url = url;
return this;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Post withTitle(String title) {
this.title = title;
return this;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public Post withDate(String date) {
this.date = date;
return this;
}
public List<Category> getCategories() {
return categories;
}
public void setCategories(List<Category> categories) {
this.categories = categories;
}
public Post withCategories(List<Category> categories) {
this.categories = categories;
return this;
}
public Author getAuthor() {
return author;
}
public void setAuthor(Author author) {
this.author = author;
}
public Post withAuthor(Author author) {
this.author = author;
return this;
}
public List<Attachment> getAttachments() {
return attachments;
}
public void setAttachments(List<Attachment> attachments) {
this.attachments = attachments;
}
public Post withAttachments(List<Attachment> attachments) {
this.attachments = attachments;
return this;
}
}
And again I'm reffering to some other models. Until now erverything works perfect, but now I need to access some of this getters and setters in my BaseAdapter.
My Adapter classe looks like this:
public class NewsList extends BaseAdapter {
private List<Recent> listData;
private LayoutInflater layoutInflater;
private Context mContext;
public ImageLoader imageLoader;
public NewsList(Context context, List<Recent> listData) {
this.listData = listData;
layoutInflater = LayoutInflater.from(context);
mContext = context;
imageLoader = new ImageLoader(context);
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.news_row_layout, null);
holder = new ViewHolder();
holder.headlineView = (TextView) convertView.findViewById(R.id.title);
holder.commentView = (TextView) convertView.findViewById(R.id.comment);
holder.reportedDateView = (TextView) convertView.findViewById(R.id.date);
holder.imageView = (ImageView) convertView.findViewById(R.id.thumbImage);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Recent rec = (Recent) listData.get(position);
Post post = (Post) rec.getPosts();
Attachment att = (Attachment) post.getAttachments();
List<Images> img = att.getImages();
Thumbnail thumb = (Thumbnail) img.getThumbnail();
Author author = (Author) post.getAuthor();
if(post != null){
/* date and time */
String date = post.getDate().replace("-",".");
String zeit = date.substring(11,16);
String datum = date.substring(0, 11);
String djahr = datum.substring(0,4);
String dmonat = datum.substring(5,8);
String dtag = datum.substring(8,10);
holder.headlineView.setText(Html.fromHtml(post.getTitle()));
holder.reportedDateView.setText(Html.fromHtml("Am <b>" + dtag+"."+dmonat+djahr+" </b>um <b>"+zeit+"</b>"));
holder.commentView.setText(Html.fromHtml("Von: <b>" + author.getName()));
ImageView image = holder.imageView;
if(post.attachments.getMime_type().contains("image")){
imageLoader.DisplayImage(thumb.getUrl(), image);
}
}
return convertView;
}
static class ViewHolder {
TextView headlineView;
TextView commentView;
TextView reportedDateView;
ImageView imageView;
}
}
As you see I try to get the List<Post> which is located inside the ArrayList<Recent>.
This line works perfect:
Recent rec = (Recent) listData.get(position);
But as soon as it comes to this line it doesn't work:
Post post = (Post) rec.getPosts();
I have no idea how to resolve this. Please help its very important for me. If you have a better solution, its welcome.
When it comes to this line Post post = (Post) rec.getPosts();, LogCat says
Cannot convert ArrayList to List
You are misinterpreting List<T> with T and this same problem is present at different parts of your code:
getPosts() returns List<Post> not Post like getImages() returns List<Images> not Images, you might need a loop to iterate over your List<Post>, getting single Post and then getting its data like List<Attachment>.
Change it to the following:
Recent rec = (Recent) listData.get(position);
List<Post> posts = rec.getPosts();
for(int i = 0; i < posts.size(); i++){
Post post = (Post) posts.get(i);
if(post != null){
List<Attachment> atts = post.getAttachments();
Attachment att = (Attachment) atts.get(0) // You can use loop instead of get(0)
List<Images> imgs = att.getImages();
Images img = (Images) imgs.get(0); // You can use loop instead of get(0)
Thumbnail thumb = (Thumbnail) img.getThumbnail();
Author author = (Author) post.getAuthor();
...
}
}
Related
I am working on a video player app. I have two fragments: one is AllVideolist fragment and the other one is Videos folders fragment. The AllVideoListenter code here fragment is working fine, but I don't know how to show get all videos folder.
This is my MainActivity.java code.
MainActivity.java
public ArrayList<videoFiles> getAllVideos(Context context) {
ArrayList<videoFiles> tempArrayList = new ArrayList<>();
Uri uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
String [] projection = {
MediaStore.Video.Media._ID,
MediaStore.Video.Media.DATA,
MediaStore.Video.Media.TITLE,
MediaStore.Video.Media.DISPLAY_NAME,
MediaStore.Video.Media.SIZE,
MediaStore.Video.Media.DATE_ADDED,
MediaStore.Video.Media.DURATION
};
Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null);
if (cursor!= null){
while (cursor.moveToNext()){
String id =cursor.getString(0);
String path =cursor.getString(1);
String title =cursor.getString(2);
String fileName =cursor.getString(3);
String size =cursor.getString(4);
String dateAdded =cursor.getString(5);
String duration =cursor.getString(6);
int durationa = Integer.parseInt(duration);
String duration_formet;
int sec = (durationa/1000)%60;
int min = (durationa/(1000*60))%60;
int hours = durationa/(1000*60*60);
if (hours == 0){
duration_formet = String.valueOf(min).concat(":" .concat(String.format(Locale.UK, "%02d",sec)));
}else {
duration_formet = String.valueOf(hours).concat(":" .concat(String.format(Locale.UK, "%02d",min).concat(":" .concat(String.format(Locale.UK, "%02d",sec)))));
}
videoFiles videoFiles = new videoFiles(id, path, title,fileName,size, dateAdded,duration_formet);
Log.d("path", path);
tempArrayList.add(videoFiles);
}
cursor.close();
}
return tempArrayList;
}
I craete this model class.
VideoFiles.java
public class videoFiles {
///------------------MODEL CLASS ---------------
private String id;
private String path;
private String title;
private String fileName;
private String size;
private String dateAdded;
private String duration;
public videoFiles(String id, String path, String title, String fileName, String size, String dateAdded, String duration) {
this.id = id;
this.path = path;
this.title = title;
this.fileName = fileName;
this.size = size;
this.dateAdded = dateAdded;
this.duration = duration;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
public String getDateAdded() {
return dateAdded;
}
public void setDateAdded(String dateAdded) {
this.dateAdded = dateAdded;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
This is folder Adapter.
FolderAdapter.java
public class FolderAdapter extends RecyclerView.Adapter<FolderAdapter.folderViewHolder> {
View view;
Context context;
private ArrayList<videoFiles> folderList;
public FolderAdapter(Context context, ArrayList<videoFiles> folderList) {
this.context = context;
this.folderList = folderList;
}
#NonNull
#Override
public FolderAdapter.folderViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
view = LayoutInflater.from(context).inflate(R.layout.foldeitems, parent, false);
return new folderViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull FolderAdapter.folderViewHolder holder, int position) {
holder.folderName.setText(folderList.get(position).getPath());
}
#Override
public int getItemCount() {
return folderList.size();
}
public class folderViewHolder extends RecyclerView.ViewHolder {
TextView folderName;
public folderViewHolder(#NonNull View itemView) {
super(itemView);
folderName = itemView.findViewById(R.id.foldername);
}
}
}
This is main foledr fragment. I want to show videos in folder by folder
FoldeFragment.java
public class FolderFragment extends Fragment {
View view;
RecyclerView recyclerView;
public FolderFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view= inflater.inflate(R.layout.fragment_folder, container, false);
recyclerView = view.findViewById(R.id.folderRecylerView);
return view;
}
}
There is no "videos folder" in Android. There are number of default locations for videos, but they vary from device to device. Devices that have expandable memory often have video storage defaults that don't exist on non-expandable devices. User are not obliged to put video files in these default locations, anyway.
If you want to get a list of all directories that contain video files, you'll either need to implement some sort of search/index operation yourself, or use the built-in media database. You should be able to enumerate the list of videos from the database, and extract the unique folder names.
For what it's worth, I answered a similar question here:
How to show only videos folder?
I am trying to save an ArrayList of objects (List shelfItems) in the bundle to retrieve it next time the activity is opened.
(the activity gets info from firestore and I want to decrease reads and take away loading time each time the activity is opened).
but i get this error message:
savedInstanceState.putParcelableArrayList("key", shelfItems);
"putParcelableArrayList(java.lang.String, java.util.ArrayList)' in 'android.os.Bundle' cannot be applied to '(java.lang.String, java.util.List)"
This is my object class:
import android.os.Parcel;
import android.os.Parcelable;
public class ShelfItem implements Parcelable{
private String mTitle;
private String mAuthor;
private String mThumbnail;
private long mRating;
private long mEndDate;
private long mBeginDate;
private String mId;
private long mPages;
private boolean mVisible;
//make ShelfItem object
public ShelfItem(String title, String author, String thumbnail, long rating, long beginDate, long endDate, String id, long pages, boolean visible) {
mTitle = title;
mAuthor = author;
mThumbnail = thumbnail;
mRating = rating;
mBeginDate = beginDate;
mEndDate = endDate;
mId = id;
mPages = pages;
mVisible = visible;
}
public String getTitle() {
return mTitle;
}
public String getAuthor() {
return mAuthor;
}
public String getThumbnail() {
return mThumbnail;
}
public long getRating() {
return mRating;
}
public long getBeginDate() {
return mBeginDate;
}
public long getEndDate() {
return mEndDate;
}
public String getId() {
return mId;
}
public long getPages() {
return mPages;
}
public boolean getVisible() {
return mVisible;
}
public ShelfItem(Parcel in) {
mId = in.readString();
mTitle = in.readString();
mAuthor = in.readString();
mThumbnail = in.readString();
mBeginDate = in.readLong();
mEndDate = in.readLong();
mPages = in.readLong();
mVisible = in.readByte() != 0;
mRating = in.readLong();
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags) {
out.writeString(mId);
out.writeString(mTitle);
out.writeString(mAuthor);
out.writeString(mThumbnail);
out.writeLong(mBeginDate);
out.writeLong(mEndDate);
out.writeLong(mPages);
out.writeByte((byte) (mVisible ? 1 : 0));
out.writeLong(mRating);
}
public static final Parcelable.Creator<ShelfItem> CREATOR = new Parcelable.Creator<ShelfItem>() {
public ShelfItem createFromParcel(Parcel in) {
return new ShelfItem(in);
}
public ShelfItem[] newArray(int size) {
return new ShelfItem[size];
}
};
}
and this is how I try to save the list:
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putParcelableArrayList("key", shelfItems);
}
As we learn Java, we're taught to use the interface type (List) instead of the implementation type (ArrayList) when we declare our variables. You probably have code somewhere that looks like this:
List<ShelfItem> shelfItems = new ArrayList<>();
However, in the particular case of Bundle and saving lists, you must use ArrayList specifically, and not any List in general.
If I'm right, and your list is declared like I've shown above, just change it to explicitly use ArrayList:
ArrayList<ShelfItem> shelfItems = new ArrayList<>();
If you're getting the list from somewhere else, and you can't control the implementation type of it, you can construct a new ArrayList when you need to save it:
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
ArrayList<ShelfItem> toSave = new ArrayList<>(shelfItems);
savedInstanceState.putParcelableArrayList("key", toSave);
}
I have a class that has parcelable implemented and I want to pass it to another activity.
This is how I've gone about it
public class Result implements Parcelable {
public static final String TMDB_IMAGE_PATH = "http://image.tmdb.org/t/p/w500";
#SerializedName("vote_count")
#Expose
private Integer voteCount;
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("video")
#Expose
private Boolean video;
#SerializedName("vote_average")
#Expose
private Double voteAverage;
#SerializedName("title")
#Expose
private String title;
#SerializedName("popularity")
#Expose
private Double popularity;
#SerializedName("poster_path")
#Expose
private String posterPath;
#SerializedName("original_language")
#Expose
private String originalLanguage;
#SerializedName("original_title")
#Expose
private String originalTitle;
#SerializedName("genre_ids")
#Expose
private JsonArray genreIds = null;
#SerializedName("backdrop_path")
#Expose
private String backdropPath;
#SerializedName("adult")
#Expose
private Boolean adult;
#SerializedName("overview")
#Expose
private String overview;
#SerializedName("release_date")
#Expose
private String releaseDate;
public Result(Integer voteCount, Integer id, Boolean video,Double voteAverage ,
String title ,Double popularity,String posterPath, String originalLanguage,
String originalTitle, JsonArray genreIds,String backdropPath,Boolean adult, String overview,String releaseDate){
this.voteCount = voteCount;
this.id = id;
this.video = video;
this.voteAverage = voteAverage;
this.title = title;
this.popularity = popularity;
this.posterPath = posterPath;
this.originalLanguage = originalLanguage;
this.originalTitle = originalTitle;
this.genreIds = genreIds;
this.backdropPath = backdropPath;
this.adult = adult;
this.overview = overview;
this.releaseDate = releaseDate;
}
private Result(Parcel source) {
this.voteCount = source.readInt();
this.id = source.readInt();
this.video = source.readByte() != 0;
this.voteAverage = source.readDouble();
this.title = source.readString();
this.popularity = source.readDouble();
this.posterPath = source.readString();
this.originalLanguage = source.readString();
this.originalTitle = source.readString();
this.backdropPath = source.readString();
this.adult = source.readByte() != 0;
this.overview = source.readString();
this.releaseDate = source.readString();
}
public Integer getVoteCount() {
return voteCount;
}
public void setVoteCount(Integer voteCount) {
this.voteCount = voteCount;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Boolean getVideo() {
return video;
}
public void setVideo(Boolean video) {
this.video = video;
}
public Double getVoteAverage() {
return voteAverage;
}
public void setVoteAverage(Double voteAverage) {
this.voteAverage = voteAverage;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Double getPopularity() {
return popularity;
}
public void setPopularity(Double popularity) {
this.popularity = popularity;
}
public String getPosterPath() {
return TMDB_IMAGE_PATH + posterPath;
}
public void setPosterPath(String posterPath) {
this.posterPath = posterPath;
}
public String getOriginalLanguage() {
return originalLanguage;
}
public void setOriginalLanguage(String originalLanguage) {
this.originalLanguage = originalLanguage;
}
public String getOriginalTitle() {
return originalTitle;
}
public void setOriginalTitle(String originalTitle) {
this.originalTitle = originalTitle;
}
public JsonArray getGenreIds() {
return genreIds;
}
public void setGenreIds(JsonArray genreIds) {
this.genreIds = genreIds;
}
public String getBackdropPath() {
return TMDB_IMAGE_PATH +backdropPath;
}
public void setBackdropPath(String backdropPath) {
this.backdropPath = backdropPath;
}
public Boolean getAdult() {
return adult;
}
public void setAdult(Boolean adult) {
this.adult = adult;
}
public String getOverview() {
return overview;
}
public void setOverview(String overview) {
this.overview = overview;
}
public String getReleaseDate() {
return releaseDate;
}
public void setReleaseDate(String releaseDate) {
this.releaseDate = releaseDate;
}
public static final Parcelable.Creator<Result> CREATOR = new Parcelable.Creator<Result>() {
public Result createFromParcel(Parcel source) {
Result movie = new Result(source);
return movie;
}
public Result[] newArray(int size) {
return new Result[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int i) {
dest.writeString(posterPath);
dest.writeByte((byte) (adult ? 1 : 0));
dest.writeString(overview);
dest.writeString(releaseDate);
dest.writeInt(id);
dest.writeString(originalTitle);
dest.writeString(originalLanguage);
dest.writeString(title);
dest.writeString(backdropPath);
dest.writeDouble(popularity);
dest.writeInt(voteCount);
dest.writeByte((byte) (video ? 1 : 0));
dest.writeDouble(voteAverage);
}
}
This is how I send the Parcelable class From my RecycerView Adapter
public class MovieAdapter extends RecyclerView.Adapter<MovieAdapter.ViewHolder> {
private List<Result> movies;
private int rowLayout;
private Context context;
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView movieTitle;
TextView data;
TextView movieDescription;
TextView rating;
ImageView pic;
public ViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
movieTitle = (TextView) itemView.findViewById(R.id.title);
data = (TextView) itemView.findViewById(R.id.subtitle);
rating = (TextView) itemView.findViewById(R.id.rating);
pic = (ImageView) itemView.findViewById(R.id.image_view_pic);
}
#Override
public void onClick(View view) {
int itemPosition = getAdapterPosition();
Result movie = movies.get(itemPosition);
Intent intent = new Intent(view.getContext(), MovieDetailActivity.class);
intent.putExtra("movieDetails",movie);
view.getContext().startActivity(intent);
}
}
public MovieAdapter(List<Result> movies, Context context){
this.movies = movies;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_movie, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.movieTitle.setText(movies.get(position).getTitle());
holder.data.setText(movies.get(position).getReleaseDate());
holder.rating.setText(movies.get(position).getVoteAverage().toString());
String PictureString = movies.get(position).getPosterPath();
Picasso.with(context)
.load(PictureString)
.placeholder(R.color.colorAccent)
.into(holder.pic);
}
#Override
public int getItemCount() {
return movies.size();
}
}
This is where I receive it
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment);
Intent intent = getIntent();
Result films = intent.getParcelableExtra("movieDetails");
}
So the problem with this code is that i am getting a null value at receving end but my Recycler view is displaying data.
Please can someone point me to the probelm?
The order in writing data and reading it should be the same. When in writeToParcel() you first write posterPath
#Override
public void writeToParcel(Parcel dest, int i) {
dest.writeString(posterPath);
....
}
Then when reading from Parcel you should read it first. like below:
private Result(Parcel source) {
this.posterPath = source.readString();
...
}
and so on.
//our model class name of Property
public class Property implements Parcelable {
...
}
//Sending our parcelable model class within intent
Intent intent = new Intent(getActivity(), MainActivity.class);
intent.putExtra("Property", property);
startActivity(intent);
//collect our intent
Intent intent = getIntent();
Property property = intent.getParcelableExtra("Property");
Good day. I need to implement parcelable in Model class.Currently it is Serializable. for now only setdate and set title if thare If any one can help. please edit code.
MainActivity.java
Document document = Jsoup.connect("http://feeds.bbci.co.uk/urdu/rss.xml").ignoreHttpErrors(true).get();
Elements itemElements = document.getElementsByTag("item");
for (int i = 0; i < itemElements.size(); i++) {
Element item = itemElements.get(i);
NewsItem newsItem = new NewsItem();
newsItem.setDate(item.child(4).text());
newsItem.setTitle(item.child(0).text());
newsItemsList.add(newsItem);
}
} catch (IOException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
#Override
public void run() {
adapter = new NewsAdaptor(Main2Activity.this,
newsItemsList);
lvRss.setAdapter(adapter);
}
});
return null;
}
NewsItem.java //model class
public class NewsItem implements Serializable {
String imagePath;
String title;
String link;
String date;
public NewsItem () {
}
public String getImagePath () {
return imagePath;
}
public void setImagePath ( String imagePath ) {
this.imagePath = imagePath;
}
public String getTitle () {
return title;
}
public void setTitle ( String title ) {
this.title = title;
}
public String getLink () {
return link;
}
public void setLink ( String link ) {
this.link = link;
}
public String getDate () {
return date;
}
public void setDate ( String date ) {
this.date = date;
}
NewsAdapter.java
public class NewsAdaptor extends BaseAdapter {
private int textSize;
TextView tvtitle;
private int color;
Context context;
public NewsAdaptor ( Context context, ArrayList <NewsItem> newsList ) {
this.context = context;
this.newsList = newsList;
this.color = Color.RED;
}
ArrayList<NewsItem> newsList;
#Override
public int getCount () {
return newsList.size();
}
#Override
public Object getItem ( int position ) {
return newsList.get(position);
}
#Override
public long getItemId ( int position ) {
return 0;
}
#Override
public View getView ( int position, View convertView, ViewGroup parent ) {
if (convertView == null){
convertView=View.inflate(context, R.layout.newsitemlist_layout,null);
}
NewsItem currentNews = newsList.get(position);
ImageView iv1 = (ImageView) convertView.findViewById(R.id.mainimg);
TextView tvdate = (TextView) convertView.findViewById(R.id.pubDateid);
Picasso.with(context).load(currentNews.getImagePath()).placeholder(R.drawable.expressimg).into(iv1);
tvdate.setText(currentNews.getDate());
tvtitle = (TextView) convertView.findViewById(R.id.textView1id);
tvtitle.setText(currentNews.getTitle());
tvtitle.setTextColor(color);
return convertView;
}
public void setTextColor(int color) {
this.color = color;
}
Check this Parcelable NewsItem:
public class NewsItem implements Parcelable {
String imagePath;
String title;
String link;
String date;
public NewsItem() {
}
protected NewsItem(Parcel in) {
imagePath = in.readString();
title = in.readString();
link = in.readString();
date = in.readString();
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(imagePath);
dest.writeString(title);
dest.writeString(link);
dest.writeString(date);
}
#Override
public int describeContents() {
return 0;
}
public static final Creator<NewsItem> CREATOR = new Creator<NewsItem>() {
#Override
public NewsItem createFromParcel(Parcel in) {
return new NewsItem(in);
}
#Override
public NewsItem[] newArray(int size) {
return new NewsItem[size];
}
};
public String getImagePath() {
return imagePath;
}
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
I have an autocompletetextview. I am getting results from an API and sending to the adapter on textchanged.
Here is the adapter.
public class ProductSearchAdapter extends BaseAdapter implements Filterable {
private Context context;
private ArrayList<ProductListModel> originalList;
private ArrayList<ProductListModel> suggestions = new ArrayList<>();
private Filter filter = new CustomFilter();
public ProductSearchAdapter(Context context, ArrayList<ProductListModel> originalList) {
this.context = context;
this.originalList = originalList;
}
#Override
public int getCount() {
return suggestions.size(); // Return the size of the suggestions list.
}
#Override
public Object getItem(int position) {
return originalList.get(position).getName();
}
#Override
public long getItemId(int position) {
return 0;
}
/**
* This is where you inflate the layout and also where you set what you want to display.
* Here we also implement a View Holder in order to recycle the views.
*/
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(context);
ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.product_search_row, parent, false);
holder = new ViewHolder();
holder.textViewProductName = (TextView) convertView.findViewById(R.id.textViewProductName);
holder.imageViewProductImage = (ImageView) convertView.findViewById(R.id.imageViewProductImage);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.textViewProductName.setText(originalList.get(position).getName());
Picasso.with(context)
.load(originalList.get(position).getImagesSmall().get(0).getSrc())
.into(holder.imageViewProductImage);
return convertView;
}
#Override
public Filter getFilter() {
return filter;
}
private static class ViewHolder {
ImageView imageViewProductImage;
TextView textViewProductName;
}
/**
* Our Custom Filter Class.
*/
private class CustomFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
suggestions.clear();
if (originalList != null && constraint != null) { // Check if the Original List and Constraint aren't null.
for (int i = 0; i < originalList.size(); i++) {
if (originalList.get(i).getName().toLowerCase().contains(constraint)) { // Compare item in original list if it contains constraints.
suggestions.add(originalList.get(i)); // If TRUE add item in Suggestions.
}
}
}
FilterResults results = new FilterResults(); // Create new Filter Results and return this to publishResults;
results.values = suggestions;
results.count = suggestions.size();
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
}
}
Now the problem is the dropdown is not showing up. Whereas if I try the same autocompletetextview with array adapter, its showing up.
Here is the activity part I am calling the api from:
autoCompleteTextViewSearch.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (charSequence.toString().length() > 0) {
hitSearchAPI(charSequence.toString());
}
}
#Override
public void afterTextChanged(Editable editable) {
}
});
On API response:
final GsonBuilder gsonBuilder = new GsonBuilder();
final Gson gson = gsonBuilder.create();
productList = gson.fromJson(responseString, ProductListModel[].class);
arrayListProducts = new ArrayList<ProductListModel>(Arrays.asList(productList));
productsSearchAdapter = new ProductSearchAdapter(MainActivity.this, arrayListProducts);
autoCompleteTextViewSearch.setThreshold(1);
autoCompleteTextViewSearch.setAdapter(productsSearchAdapter);
Same textview working with array adapter but not with custom adapter.
ProductListModel:
public class ProductListModel {
String _id;
String name;
String color;
String description;
int credits;
ProductItemModel category;
ArrayList<ProductItemModel> subcategories;
ProductItemModel fit;
ProductBrandModel brand;
ArrayList<ProductItemModel> rules;
ProductBrandModel condition;
ArrayList<ProductImagesModel> images;
ArrayList<ProductItemModel> size;
ArrayList<ProductImagesModel> imagesSmall;
String userId;
long time_created;
long time_approved;
long time_featured;
long time_rejected;
boolean approved;
boolean rejected;
boolean featured;
int status;
ProductUserProfileModel user_profile;
String rejected_reason_id;
String categoryId;
int likes;
boolean likedBy;
public String get_id() {
return _id;
}
public void set_id(String _id) {
this._id = _id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getCredits() {
return credits;
}
public void setCredits(int credits) {
this.credits = credits;
}
public ProductItemModel getCategory() {
return category;
}
public void setCategory(ProductItemModel category) {
this.category = category;
}
public ArrayList<ProductItemModel> getSubcategories() {
return subcategories;
}
public void setSubcategories(ArrayList<ProductItemModel> subcategories) {
this.subcategories = subcategories;
}
public ProductItemModel getFit() {
return fit;
}
public void setFit(ProductItemModel fit) {
this.fit = fit;
}
public ProductBrandModel getBrand() {
return brand;
}
public void setBrand(ProductBrandModel brand) {
this.brand = brand;
}
public ArrayList<ProductItemModel> getRules() {
return rules;
}
public void setRules(ArrayList<ProductItemModel> rules) {
this.rules = rules;
}
public ProductBrandModel getCondition() {
return condition;
}
public void setCondition(ProductBrandModel condition) {
this.condition = condition;
}
public ArrayList<ProductImagesModel> getImages() {
return images;
}
public void setImages(ArrayList<ProductImagesModel> images) {
this.images = images;
}
public ArrayList<ProductItemModel> getSize() {
return size;
}
public void setSize(ArrayList<ProductItemModel> size) {
this.size = size;
}
public ArrayList<ProductImagesModel> getImagesSmall() {
return imagesSmall;
}
public void setImagesSmall(ArrayList<ProductImagesModel> imagesSmall) {
this.imagesSmall = imagesSmall;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public long getTime_created() {
return time_created;
}
public void setTime_created(long time_created) {
this.time_created = time_created;
}
public long getTime_approved() {
return time_approved;
}
public void setTime_approved(long time_approved) {
this.time_approved = time_approved;
}
public long getTime_featured() {
return time_featured;
}
public void setTime_featured(long time_featured) {
this.time_featured = time_featured;
}
public long getTime_rejected() {
return time_rejected;
}
public void setTime_rejected(long time_rejected) {
this.time_rejected = time_rejected;
}
public boolean isApproved() {
return approved;
}
public void setApproved(boolean approved) {
this.approved = approved;
}
public boolean isRejected() {
return rejected;
}
public void setRejected(boolean rejected) {
this.rejected = rejected;
}
public boolean isFeatured() {
return featured;
}
public void setFeatured(boolean featured) {
this.featured = featured;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public ProductUserProfileModel getUser_profile() {
return user_profile;
}
public void setUser_profile(ProductUserProfileModel user_profile) {
this.user_profile = user_profile;
}
public String getRejected_reason_id() {
return rejected_reason_id;
}
public void setRejected_reason_id(String rejected_reason_id) {
this.rejected_reason_id = rejected_reason_id;
}
public String getCategoryId() {
return categoryId;
}
public void setCategoryId(String categoryId) {
this.categoryId = categoryId;
}
public int getLikes() {
return likes;
}
public void setLikes(int likes) {
this.likes = likes;
}
public boolean isLikedBy() {
return likedBy;
}
public void setLikedBy(boolean likedBy) {
this.likedBy = likedBy;
}
}
You need to add toString() method to your model so the AutoCompleteTextView can compare between the typed String and the returned value.
if you are looking by name the toString() needs to return it :
#Override
public String toString() {
return name ;
}
}