How to get videos folder? - java

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?

Related

Getter returning null when testing get methods

I am trying to get data from my database to show on a listview. The problem I am having is it seems the getters are not working properly. When I test what they are returning, it comes back null.
Any insight would be appreciated as I am lost here. Thanks in advance.
Here is where I initialise the class:
public ArrayList<GameStats> getAllData() {
ArrayList<GameStats> arrayList = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM savedGamesTable", null);
while(cursor.moveToNext()){
int id = cursor.getInt(0);
String lName = cursor.getString(1);
int lScore = cursor.getInt(2);
String rName = cursor.getString(3);
int rScore = cursor.getInt(4);
String notes = cursor.getString(5);
GameStats gameStats = new GameStats(id, lName, lScore, rName, rScore, notes);
arrayList.add(gameStats);
}
return arrayList;
}
Here is where I am trying to use the getters:
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.activity_saved_games, null);
TextView lName = convertView.findViewById(R.id.lName);
TextView lScore = convertView.findViewById(R.id.lScore);
TextView rName = convertView.findViewById(R.id.rName);
TextView rScore = convertView.findViewById(R.id.rScore);
TextView notes = convertView.findViewById(R.id.notes);
GameStats gameStats = arrayList.get(position);
testVar = gameStats.getlName();
Log.d("MyAdaptor","gameStats = " + var);
lName.setText(gameStats.getlName());
lScore.setText(String.valueOf(gameStats.getlScore()));
rName.setText(gameStats.getrName());
rScore.setText(String.valueOf(gameStats.getrScore()));
notes.setText(gameStats.getNotes());
return convertView;
}
Here is the model class:
public class GameStats {
int id, lScore, rScore;
String lName, rName, notes;
public GameStats(int id, String lName, int lScore, String rName, int rScore, String notes) {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getlScore() {
return lScore;
}
public void setlScore(int lScore) {
this.lScore = lScore;
}
public int getrScore() {
return rScore;
}
public void setrScore(int rScore) {
this.rScore = rScore;
}
public String getlName() {
return lName;
}
public void setlName(String lName) {
this.lName = lName;
}
public String getrName() {
return rName;
}
public void setrName(String rName) {
this.rName = rName;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
}
and here is where I am calling the methods:
public class SavedGameScreen extends AppCompatActivity {
ListView lv1;
ArrayList<GameStats> arrayList;
MyAdaptor myAdaptor;
DatabaseHelper databaseHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_saved_game_screen);
lv1 = findViewById(R.id.lv1);
databaseHelper = new DatabaseHelper(this);
arrayList = new ArrayList<>();
loadData();
}
private void loadData() {
arrayList = databaseHelper.getAllData();
myAdaptor = new MyAdaptor(this, arrayList);
lv1.setAdapter(myAdaptor);
myAdaptor.notifyDataSetChanged();
}
}
Please change the constructor as below and see if that works,
public GameStats(int id, String lName, int lScore, String rName, int rScore, String notes) {
this.id = id;
this.lName = IName;
this.lScore = IScore;
this.rName = rName;
this.rScore = rScore;
this.notes = notes;
}
In your model class initialize the variables using constrtuctor. I guess that is the problem. Since you are not initializing the model class properties, it the getters will return "null" or any garbage value
You are passing the values to the model constructor but you are not assigning it to the model variables. You need to change the code as below,
public GameStats(int id, String lName, int lScore, String rName, int rScore, String notes) {
this.id = id;
this.lName = IName;
this.lScore = IScore;
this.rName = rName;
this.rScore = rScore;
this.notes = notes;
}
Else initialise each variable through setter() method.

Parcelable class does not make a parcelable object

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

TodoList application android

Please I need your help .I'am trying to take the date from an activity and then put it in an array list then print it in an ListView .
The problem is the data that I should take it from "Adding Todo" is not showing in the ListView . it do take me to the List Activity but without showing the data .
This is How the app going to be "Adding todo"
And this is the ListView where the data should be in it
My code :-
MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.list_view);
arrayList = new ArrayList<>();
todoAdapter = new TodoAdapter(this , arrayList);
listView.setAdapter(todoAdapter);
}
public void onClick(View view) {
Intent intent = new Intent();
intent.setClass(MainActivity.this, AddTodo.class);
startActivityForResult(intent, Intent_Constants.INTENT_REQUEST_CODE);
}
protected void onActivityResult(int reqCode ,int resultCode , Intent data ){
// here Iam trying to get the data from ADDING TO DO class
if(resultCode == Intent_Constants.INTENT_REQUEST_CODE){
titleText = data.getStringExtra(Intent_Constants.INTENT_TITLE);
priorityText = data.getStringExtra(Intent_Constants.INTENT_PRIORITY);
statusText = data.getStringExtra(Intent_Constants.INTENT_STATUES);
dateText = data.getStringExtra(Intent_Constants.INTENT_DATE);
timeText = data.getStringExtra(Intent_Constants.INTENT_TIME);
todoAdapter.todo.add(new Todo (titleText , statusText ,priorityText ,dateText ,timeText));
}
}
Intent_Constants
public class Intent_Constants {
public final static int INTENT_REQUEST_CODE = 1;
public final static int INTENT_RESULT_CODE = 1 ;
public final static String INTENT_TITLE = "Title";
public final static String INTENT_PRIORITY = "Priority";
public final static String INTENT_TIME = "Time";
public final static String INTENT_DATE = "Date";
public final static String INTENT_STATUES = "Statues";
}
AddTodo class
In this class I find the id then I converted to String
public void saveButton (View view){
Intent intent = new Intent();
intent.putExtra(Intent_Constants.INTENT_TITLE , title);
intent.putExtra(Intent_Constants.INTENT_DATE , date);
intent.putExtra(Intent_Constants.INTENT_TIME , time);
intent.putExtra(Intent_Constants.INTENT_PRIORITY , priority);
intent.putExtra(Intent_Constants.INTENT_STATUES , completed);
setResult(INTENT_RESULT_CODE, intent);
finish();
}
TodoAdapter class
ArrayList<Todo> todo ;
public TodoAdapter(#NonNull Context context, ArrayList<Todo> todo) {
super(context, R.layout.todo_list,todo);
this.todo = todo;
}
public static class ViewHolder {
TextView titleText;
TextView priorityText;
TextView dateText;
TextView timeText;
CheckBox statusBox;
ImageButton edit_image;
ImageButton open_image;
ImageButton delet_image;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater inflater = LayoutInflater.from(getContext()) ;
View customeView =inflater.inflate(R.layout.todo_list,parent ,false);
holder.titleText.setText(getItem(position).getTitle());
holder.priorityText.setText(getItem(position).getPriority());
holder.dateText.setText(getItem(position).getDate());
holder.timeText.setText(getItem(position).getTime());
holder.statusBox.setChecked(false);
holder.edit_image = customeView.findViewById(R.id.edit_imageView);
holder.open_image = customeView.findViewById(R.id.open_imageButton);
holder.delet_image = customeView.findViewById(R.id.delete_imageView);
holder.edit_image.setImageResource(R.drawable.ic_edit_black_24dp);
holder.open_image.setImageResource(R.drawable.ic_refresh_black_24dp);
holder.delet_image.setImageResource(R.drawable.ic_delete_black_24dp);
return customeView;
}
Todo class
public class Todo {
private String title ;
private String status ;
private String priority ;
private String date ;
private String time ;
public Todo() {
}
public Todo(String title, String status, String priority, String date, String time) {
this.title = title;
this.status = status;
this.priority = priority;
this.date = date;
this.time = time;
}
public String getTitle() {
return title;
}
public String getStatus() {
return status;
}
public String getPriority() {
return priority;
}
public String getDate() {
return date;
}
public String getTime() {
return time;
}
public void setTitle(String title) {
this.title = title;
}
public void setStatus(String status) {
this.status = status;
}
public void setPriority(String priority) {
this.priority = priority;
}
public void setDate(String date) {
this.date = date;
}
public void setTime(String time) {
this.time = time;
}
}
You can just set a new adapter, I know it isn't best way, but should do the work. Don't create new one, but nulify yours, and initialize it with new data.
#Noura change this
arrayList.add(new Todo(titleText , statusText ,priorityText ,dateText ,timeText));
to
todoAdapter.todo.add(new Todo(titleText , statusText ,priorityText ,dateText ,timeText));
todoAdapter.notifyDataSetChanged();
and at the constructor u need to update your code like below
ArrayList<Todo> todo ;
public TodoAdapter(#NonNull Context context, ArrayList<Todo> todo) {
this.todo = todo
super(context, R.layout.todo_list,todo);
}

How to implement Parcelable

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

Android GSON access List in ArrayList

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

Categories