I'm trying to get Image from Uri using glide but what i'm not getting an Image.
Model class - AlbumData
public class AlbumData {
private long id;
public String title;
public String description;
public Uri imageId;
public long getID() {
return id;
}
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
/*public int getImageId() {
return imageId;
}
*/
public Uri getArtwork(){return imageId;}
public Bitmap getArtworkBitmap(Context ctx) {
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(ctx.getContentResolver(), imageId);
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
public AlbumData(long id, String title, String description, Uri imageId) {
this.id = id;
this.title = title;
this.description = description;
this.imageId = imageId;
}}
RecyclerView - AlbumRecyclerViewAdapter
public class AlbumRecyclerViewAdapter extends RecyclerView.Adapter<AlbumRecyclerViewAdapter.CustomViewHolder> {
private final String TAG = "test1";
Songs myTab;
MediaPlayer mediaPlayer;
public List<AlbumData> list = Collections.emptyList();
Context context;
public AlbumRecyclerViewAdapter(List<AlbumData> list, Context context, Songs myTab) {
this.list = list;
this.context = context;
this.myTab = myTab;
}
#Override
public CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View songView = LayoutInflater.from(parent.getContext()).inflate(R.layout.album_custom_row, parent, false);
CustomViewHolder myHolder = new CustomViewHolder(songView, context, list);
return myHolder;
}
#Override
public void onBindViewHolder(CustomViewHolder holder, int position) {
AlbumData album = list.get(position);
//Use the provided View Holder on the onCreateViewHolder method to
//Populate the current row on the RecyclerView
holder.getItemId();
holder.title.setText(list.get(position).title);
holder.description.setText(list.get(position).description);
//holder.imageView.setImageResource(list.get(position).imageId);
Bitmap bitmap = null;
/*try {
bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), album.getArtwork());
holder.imageView.setImageBitmap(bitmap);
} catch (Exception exception) {
// log error
}
*/
Glide.with(context).load(Uri.parse("file://" + album.getArtwork())).asBitmap().skipMemoryCache(true).into(holder.imageView);
}
#Override
public int getItemCount() {
//returns the number of elements the RecyclerView will displaye
return list.size();
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
//Insert a new item to the RecyclerView on a predefined position
public void insert(int position, AlbumData data) {
list.add(position, data);
notifyItemChanged(position);
}
public void remove(AlbumData data) {
int position = list.indexOf(data);
list.remove(position);
notifyItemRemoved(position);
}
public static class CustomViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
CardView cv;
TextView title;
TextView description;
ImageView imageView;
Context context;
List<AlbumData> list = new ArrayList<AlbumData>();
public CustomViewHolder(View itemView, Context context, List<AlbumData> list)
{
super(itemView);
this.context = context;
this.list = list;
this.itemView.setOnClickListener(this);
cv = (CardView) itemView.findViewById(R.id.cardView);
title = (TextView) itemView.findViewById(R.id.playList_name);
description = (TextView) itemView.findViewById(R.id.album_artist);
imageView = (ImageView) itemView.findViewById(R.id.imageView1);
}
#Override
public void onClick(View view) {
int position = getAdapterPosition();
AlbumData list = this.list.get(position);
}
}}
Fragment class - SongFragment
public class Songs extends Fragment {
final public static Uri sArtworkUri = Uri
.parse("content://media/external/audio/albumart");
private MediaPlayer mp;
private Intent playIntent;
private boolean musicBound = false;
private static final String KEY_LAYOUT_MANAGER = "layoutManager";
private RecyclerView mRecyclerView;
private AlbumRecyclerViewAdapter mAdapter;
protected List<AlbumData> songsList;
private enum LayoutManagerType {
GRID_LAYOUT_MANAGER,
LINEAR_LAYOUT_MANAGER
}
protected LayoutManagerType mCurrentLayoutManagerType;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Initialize dataset, this data would usually come from a local content provider or
// remote server.
//fill_with_data();
//Instantiate the list
songsList = new ArrayList<AlbumData>();
getSongList();
Collections.sort(songsList, new Comparator<AlbumData>() {
public int compare(AlbumData a, AlbumData b) {
return a.getTitle().compareTo(b.getTitle());
}
});
}
public Songs() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_songs, container,
false);
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerview);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mCurrentLayoutManagerType = LayoutManagerType.LINEAR_LAYOUT_MANAGER;
if (savedInstanceState != null) {
// Restore saved layout manager type.
mCurrentLayoutManagerType = (LayoutManagerType) savedInstanceState
.getSerializable(KEY_LAYOUT_MANAGER);
}
mAdapter = new AlbumRecyclerViewAdapter(songsList, getContext(), Songs.this);
// Set CustomAdapter as the adapter for RecyclerView.
mRecyclerView.setAdapter(mAdapter);
return rootView;
}
public void getSongList() {
//retrieve song info
ContentResolver musicResolver = getActivity().getContentResolver();
Uri musicUri = MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI;
Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null);
if (musicCursor != null && musicCursor.moveToFirst()) {
//get columns
int titleColumn = musicCursor.getColumnIndex
(MediaStore.Audio.Albums.ALBUM);
int idColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Albums._ID);
int artistColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Albums.ARTIST);
//int imageColumn = musicCursor.getColumnIndex
// (MediaStore.Audio.Albums.ALBUM_ART);
//add songs to list
do {
long thisId = musicCursor.getLong(idColumn);
String thisTitle = musicCursor.getString(titleColumn);
String thisArtist = musicCursor.getString(artistColumn);
//int thisAlbum = (int) musicCursor.getLong(imageColumn);
Uri albumArtUri = ContentUris.withAppendedId(sArtworkUri, thisId);
songsList.add(new AlbumData(thisId, thisTitle, thisArtist, albumArtUri));
}
while (musicCursor.moveToNext());
musicCursor.close();
}
}}
Though I commented out the bitmap section in BindViewHolder as when i using that method, it makes recyclerView slow.
So trying to use glide but I don't know why i'm not getting image. Any help would be precious.!
You are using Uri in ImageId, get string from ImageId like below, hope it will work
Glide.with(this)
.load(list.get(position).imageId)
.centerCrop()
.placeholder(R.mipmap.ic_launcher)
.crossFade()
.into(logoIv);
for simple load
Glide.with(this).load("uri")
.placeholder(R.mipmap.ic_launcher)
.into(logoIv);
and round imageview using glide
Glide.with(this)
.load("uri")
.centerCrop()
.placeholder(R.mipmap.ic_launcher)
.crossFade()
.into(logoIv);
Glide.with(this).load(uri.getPath())
.placeholder(R.mipmap.ic_launcher)
.into(logoIv);
uri.getPath() should solve the issue.
Try this one.
Glide.with(mContext)
.load(new File(pictureUri.getPath())) // Uri of the picture
.into(logoIv);
Finally I got the answer -
Glide.with(context).load(list.get(position).imageId).
placeholder(R.drawable.ic_action_movie).into(holder.imageView);
Related
I'm trying to do a simple thing and its get all images from the external storage into recycle view and display them.
My problem is that for some reason i recieve null and i dont know why.
I successfully getting all the images into array list of string.
And then on the Reycleview i'm getting error of null exception.
Cant find what im doing wrong.
The log shows me that the error comes from the Recycler.From the method "onBindViewHolder" (i also mentioned this line).
It craches holder.imgView.setImageURI(imageUri); - still cant understand why,
even though i checked that its not null.
My Code
private BootstrapButton btnLoadImage;
private RecyclerView rvImages;
private static final int REQUEST_CODE = 1;
private boolean mStoragePermissions;
private ArrayList<String> imageLists;
private ImageViewAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnLoadImage = (BootstrapButton)findViewById(R.id.btnLoadImges);
rvImages = (RecyclerView)findViewById(R.id.rvPictures);
btnLoadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(mStoragePermissions){
imageLists = getFilePaths();
Log.d("MainActivity",imageLists.toString());
if(imageLists != null)
setAdapter(imageLists);
}else{
verifyStoragePermissions();
}
}
});
}
private void setAdapter(ArrayList<String> imageLists) {
adapter = new ImageViewAdapter(getApplication(),imageLists);
rvImages.setAdapter(adapter);
rvImages.setLayoutManager(new GridLayoutManager(getApplication(),3));
btnLoadImage.setVisibility(View.INVISIBLE);
}
public ArrayList<String> getFilePaths()
{
Uri u = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String[] projection = {MediaStore.Images.ImageColumns.DATA};
Cursor c = null;
SortedSet<String> dirList = new TreeSet<String>();
ArrayList<String> resultIAV = new ArrayList<String>();
String[] directories = null;
if (u != null)
{
c = managedQuery(u, projection, null, null, null);
}
if ((c != null) && (c.moveToFirst()))
{
do
{
String tempDir = c.getString(0);
tempDir = tempDir.substring(0, tempDir.lastIndexOf("/"));
try{
dirList.add(tempDir);
}
catch(Exception e)
{
Log.d("MainActivity",e.getMessage().toString());
}
}
while (c.moveToNext());
directories = new String[dirList.size()];
dirList.toArray(directories);
}
for(int i=0;i<dirList.size();i++)
{
File imageDir = new File(directories[i]);
File[] imageList = imageDir.listFiles();
if(imageList == null)
continue;
for (File imagePath : imageList) {
try {
if(imagePath.isDirectory())
{
imageList = imagePath.listFiles();
}
if ( imagePath.getName().contains(".jpg")|| imagePath.getName().contains(".JPG")
|| imagePath.getName().contains(".jpeg")|| imagePath.getName().contains(".JPEG")
|| imagePath.getName().contains(".png") || imagePath.getName().contains(".PNG") )
{
String path= imagePath.getAbsolutePath();
resultIAV.add(path);
}
}
// }
catch (Exception e) {
e.printStackTrace();
}
}
}
return resultIAV;
}
public class ImageViewAdapter extends RecyclerView.Adapter<ImageViewHolder>{
private LayoutInflater inflater;
private Context context;
private ArrayList<String> data;
public ImageViewAdapter(Context context, ArrayList<String> data){
this.context = context;
this.inflater = LayoutInflater.from(context);
this.data = data;
}
#NonNull
#Override
public ImageViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = inflater.inflate(R.layout.image_item,parent,false);
return new ImageViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ImageViewHolder holder, int position) {
String imgSrc = data.get(position);
Uri imageUri = Uri.parse(imgSrc);
if(imageUri != null) {
//**Here i always getting null exception **
holder.imgView.setImageURI(imageUri);
}
}
#Override
public int getItemCount() {
return data.size();
}
}
public class ImageViewHolder extends RecyclerView.ViewHolder{
private ImageView imgView;
public ImageViewHolder(View itemView){
super(itemView);
imgView = (ImageView)findViewById(R.id.imageView);
}
}
}
What is null is this in your ImageViewHolder ImageView imgView;
You're using
imgView = (ImageView)findViewById(R.id.imageView);
But look that findViewById is finding a view in your activity, and not in your RecyclerView ViewHolder, precisely in your image_item.xml root layout.
So, just use findViewById in that view:
public ImageViewHolder(View itemView){
super(itemView);
imgView = (ImageView) itemView.findViewById(R.id.imageView);
}
I'm trying to develop android application which can load images from the url in to RecyclerView With the help of Picasso library. But the problem comes that after some sequence "in my case after every 6 image" same image is duplicating in recyclerview. I'm added some code
#Override
public int getItemCount() {
return data.length;
}
#Override
public long getItemId(int position) {
return position;
}
in my adapter but this is not working for me.
Below is my currant adapter code please help me to findout the solution for this.
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private Context context;
private Img[] data;
public MyAdapter(Context context, Img[] data) {
this.context = context;
this.data = data;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.image_row, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
final Img user = data[position];
final String imageStr = user.getImgurl();
String taKey = loadTaluka();
final String id = user.getImgId().toString();
if (user.getTaluka().equals(taKey)) {
float date = Float.parseFloat(user.getDateTime());
float lastDayDate = Float.parseFloat(dispDate()) - 1;
if (date >= lastDayDate) {
Picasso.with(holder.myImg.getContext()).load(imageStr).placeholder(R.drawable.loading_1).networkPolicy(NetworkPolicy.OFFLINE).into(holder.myImg, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError() {
Picasso.with(holder.myImg.getContext()).load(imageStr).placeholder(R.drawable.loading_1).into(holder.myImg);
}
});
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, LoadImg.class);
intent.putExtra("url", imageStr);
intent.putExtra("id", id);
context.startActivity(intent);
}
});
}
}
#Override
public int getItemCount() {
return data.length;
}
#Override
public long getItemId(int position) {
return position;
}
/*
#Override
public int getItemViewType(int position) {
return position;
}*/
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView userTitle;
TextView age;
TextView country;
TextView url;
public ImageView myImg;
public MyViewHolder(View itemView) {
super(itemView);
myImg = (ImageView) itemView.findViewById(R.id.postImg);
}
}
//Extras
private String loadTaluka() {
SharedPreferences sf = context.getSharedPreferences("Taluka", MODE_PRIVATE);
return sf.getString("taluka", "a");
}
//Image Viewholder Adapter End
private String dispDate() {
Date c = Calendar.getInstance().getTime();
#SuppressLint("SimpleDateFormat") SimpleDateFormat day = new SimpleDateFormat("dd");
String dayFinal = day.format(c);
#SuppressLint("SimpleDateFormat") SimpleDateFormat month = new SimpleDateFormat("MM");
String monthFinal = month.format(c);
#SuppressLint("SimpleDateFormat") SimpleDateFormat year = new SimpleDateFormat("yyyy");
String yearFinal = year.format(c);
#SuppressLint("SimpleDateFormat") SimpleDateFormat hour = new SimpleDateFormat("HH");
String hourFinal = hour.format(c);
String finalDate = Integer.toString(Integer.parseInt(dayFinal) + Integer.parseInt(monthFinal) + Integer.parseInt(yearFinal)) + "." + hourFinal;
return finalDate;
}
}
-Thankyou.
Because of Recycler views RAM Management, the recycler view try to load cards from the cache and because of your recycler view's cache, the items loads incorrectly.
for preventing this you must add an else to your if like this:
if (date >= lastDayDate)
{
//Do Your Code
}
else
{
//The Default Item View Settings Here...
}
public void onBindViewHolder(MyAdapter.MyViewHolde holder, int position) {
//how to set image for loading the images for gallery
----------
}
//and code for how to get images from gallery in main activity
You have to first get all images from gallery in you activity then have to set the list of images to RecyclerView
Use below method to get all all images-
private ArrayList<String> getAllShownImagesPath(Activity activity) {
Uri uri;
Cursor cursor;
int column_index_data, column_index_folder_name;
ArrayList<String> listOfAllImages = new ArrayList<String>();
String absolutePathOfImage = null;
uri = android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String[] projection = { MediaColumns.DATA,
MediaStore.Images.Media.BUCKET_DISPLAY_NAME };
cursor = activity.getContentResolver().query(uri, projection, null,
null, null);
column_index_data = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
column_index_folder_name = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.BUCKET_DISPLAY_NAME);
while (cursor.moveToNext()) {
absolutePathOfImage = cursor.getString(column_index_data);
listOfAllImages.add(absolutePathOfImage);
}
return listOfAllImages;
}
Now set the This list of images to RecyclerView Adapter.
Take this RecyclerView Example as an reffrence to set all gallery images.
public class GalleryFragment extends Fragment {
public GalleryFragment() {
// Required empty public constructor
}
private Context context;
private RecyclerView recyclerView;
ArrayList<String> imageData;
MyAdapter adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_gallery, container, false);
context = getActivity();
recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getActivity(), 3);
recyclerView.setLayoutManager(layoutManager);
MyTask myTask = new MyTask();
myTask.execute();
return view;
}
private class MyTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
imageData = getAllShownImagesPath(getActivity());
Log.e("imageData: ", String.valueOf(imageData.size()));
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
adapter = new MyAdapter(imageData, getActivity());
recyclerView.setAdapter(adapter);
}
}
private ArrayList<String> getAllShownImagesPath(Activity activity) {
Uri uri;
Cursor cursor;
int column_index_data, column_index_folder_name;
ArrayList<String> listOfAllImages = new ArrayList<String>();
String absolutePathOfImage = null;
uri = android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String[] projection = {MediaStore.MediaColumns.DATA,
MediaStore.Images.Media.BUCKET_DISPLAY_NAME};
cursor = activity.getContentResolver().query(uri, projection, null,
null, null);
column_index_data = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
column_index_folder_name = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.BUCKET_DISPLAY_NAME);
while (cursor.moveToNext()) {
absolutePathOfImage = cursor.getString(column_index_data);
listOfAllImages.add(absolutePathOfImage);
}
return listOfAllImages;
}
}
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolde> {
Context context;
private ArrayList<String> imageData = new ArrayList<String>();
public MyAdapter(ArrayList<String> imageData, FragmentActivity activity) {
this.imageData = imageData;
this.context = activity;
}
#Override
public MyAdapter.MyViewHolde onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.inflate_single_image_row, parent, false);
return new MyViewHolde(itemView);
}
#Override
public void onBindViewHolder(MyAdapter.MyViewHolde holder, int position) {
String data = imageData.get(position);
if (data != null){
Glide.with(context).load(data).into(holder.singleImageView);
}else {
Toast.makeText(context, "Images Empty", Toast.LENGTH_SHORT).show();
}
}
#Override
public int getItemCount() {
return imageData.size();
}
public class MyViewHolde extends RecyclerView.ViewHolder {
ImageView singleImageView;
public MyViewHolde(View itemView) {
super(itemView);
singleImageView = (ImageView) itemView.findViewById(R.id.singleImageView);
}
}
}
This Get list of photo galleries on Android will help you..
One thing i want to add here is you should add the gallery retrieving data inside a AsyncTask or Thread. It is not good practice to fetch gallery data in UI thread because if gallery images are huge than you may get ANR due to processing in UI tread.
What I'm trying to do is fetch images from database and show them in listView. for this i am using one adapter and list elements class but it is not showing any image but one string value that passed from main activity to elements class actually address of the image in which it is stored in database. Like this
Please don't make it duplicate
http://howdysend.com/Howdy/uploads/6.png ... actually that is the address of the image in database and 6 is the id of the image. Here is my code
Main activity
listEvents.setAdapter((ListAdapter) adapterNewsFeed);
adapterNewsFeed = new AdapterNewsFeed(getActivity(), R.layout.custom_events_list_in_newsfeed);
listEvents.setAdapter((ListAdapter) adapterNewsFeed);
try {
jsonObject = new JSONObject(json_string);
jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
String EventTitle, EventDate, FriendName,friend_id,image;
while (count < jsonArray.length()) {
JSONObject JO = jsonArray.getJSONObject(count);
friend_id=JO.getString("friend_id");
EventTitle = JO.getString("address");
EventDate = JO.getString("DOB");
FriendName = JO.getString("name");
image=("http://howdysend.com/Howdy/uploads/" + friend_id + ".png");
EventsElements eventsElements = new EventsElements(image,EventTitle, EventDate, FriendName);
adapterNewsFeed.add(eventsElements);
listEvents.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
EventsElements eventsElements =(EventsElements) adapterNewsFeed.getItem(position);
Intent i = new Intent(getActivity(), SendGreetings.class);
i.putExtra("user_id", eventsElements.getFriendName());
startActivity(i);
}
});
Elements Class
public class EventsElements {
private String EventTitle, EventDate,FriendName;
public String image;
public EventsElements(String EventTitle,String EventDate,String FriendName, String image){
this.setEventTitle(EventTitle);
this.setEventDate(EventDate);
this.setFriendName(FriendName);
this.setImage(image);
}
public String getEventTitle(){
return EventTitle;
}
public void setEventTitle(String EventTitle) {
this.EventTitle = EventTitle;
}
public String getEventDate() {
return EventDate;
}
public void setEventDate(String EventDate) {
this.EventDate = EventDate;
}
public String getFriendName() {
return FriendName;
}
public void setFriendName(String FriendName) {
this.FriendName = FriendName;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
And AdapterNewsFeed
public class AdapterNewsFeed extends ArrayAdapter {
List list=new ArrayList();
public AdapterNewsFeed(Context context, int resource) {
super(context,resource);
}
#Override
public int getCount() {
return list.size();
}
public void add(EventsElements object) {
super.add(object);
list.add(object);
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
view=convertView;
ElementsHolder elemetsHolder;
if (view==null){
LayoutInflater layoutInflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.custom_events_list_in_newsfeed,parent,false);
elemetsHolder=new ElementsHolder();
elemetsHolder.EventTitle=(TextView) view.findViewById(R.id.EventTitle);
elemetsHolder.EventDate=(TextView) view.findViewById(R.id.EventDate);
elemetsHolder.FriendName=(TextView) view.findViewById(R.id.FriendName);
elemetsHolder.imageView=(ImageView)view.findViewById(R.id.FriendsUserImage);
view.setTag(elemetsHolder);
}
else
{
elemetsHolder=(ElementsHolder) view.getTag();
}
EventsElements eventsElements=(EventsElements)this.getItem(position);
elemetsHolder.EventTitle.setText(eventsElements.getEventTitle());
elemetsHolder.EventDate.setText(eventsElements.getEventDate());
elemetsHolder.FriendName.setText(eventsElements.getFriendName());
Picasso.with(getContext()).load(Uri.parse(eventsElements.getImage())).fit().into(elemetsHolder.imageView);
return view;
}
static class ElementsHolder
{
TextView EventTitle,EventDate,FriendName;
ImageView imageView;
String user_id;
}
}
Your image is from Url so basically you don't need Uri.parse(eventsElements.getImage(). Instead just set your url like this
Picasso.with(getContext()).load(eventsElements.getImage()).fit().into(elemetsHolder.imageView);
For more info check https://guides.codepath.com/android/Displaying-Images-with-the-Picasso-Library
Hope this helps!!
I want to populate a ListView with different layouts for odd and even rows. It should look like this:
I use two objects "OddListItem" and "EvenListItem" to store/access the data. I do not know how to pass both objects to my custom listview adapter and get the correct view.
My object classes:
public class OddListItem {
private String time_start;
private String time_end;
private String location;
public OddListItem(String time_start, String time_end, String location) {
super();
this.time_start = time_start;
this.time_end = time_end;
this.location = location;
}
// getters and setters
void setTimeStart(String time_start) {
this.time_start = time_start;
}
void setTimeEnd(String time_end) {
this.time_end = time_end;
}
void setLocation(String location) {
this.location = location;
}
public String getTimeStart() {
return time_start;
}
public String getTimeEnd() {
return time_end;
}
public String getLocation() {
return location;
}
}
public class EvenListItem {
private String image;
private String location;
public EvenListItem (String image, String location) {
super();
this.image = image;
this.location = location;
}
// getters and setters
void setImage(String image) {
this.image = image;
}
void setLocation(String location) {
this.location = location;
}
public String getImage() {
return image;
}
public String getLocation() {
return location;
}
}
MyCustomAdapter:
public class MyCustomAdapter extends BaseAdapter {
// Tag for Logging
private static final String TAG = "MyCustomAdapter";
int type;
private static final int TYPE_ITEM = 0;
private static final int TYPE_SEPARATOR = 1;
private static final int TYPE_MAX_COUNT = TYPE_SEPARATOR + 1;
private ArrayList<OddListItem> mData = new ArrayList<OddListItem>();
private LayoutInflater mInflater;
//private TreeSet mSeparatorsSet = new TreeSet();
private Context context;
public MyCustomAdapter(Context context) {
mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.context = context;
}
public void addItem(final OddListItem item) {
mData.add(item);
//The notification is not necessary since the items are not added dynamically
//notifyDataSetChanged();
}
public void addSeparatorItem(final OddListItem item) {
mData.add(item);
//The notification is not necessary since the items are not added dynamically
//notifyDataSetChanged();
}
#Override
public int getItemViewType(int position) {
/*if ((position%2) == 0){
type = TYPE_ITEM;
} else {
type = TYPE_SEPARATOR;
}
return type;*/
return position%2;
}
#Override
public int getViewTypeCount() {
return TYPE_MAX_COUNT;
}
#Override
public int getCount() {
return mData.size();
}
#Override
public OddListItem getItem(int position) {
return mData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
int type = getItemViewType(position);
Log.d(TAG, "getView " + position + " " + convertView + " type = " + type);
if (convertView == null) {
holder = new ViewHolder();
switch (type) {
case TYPE_ITEM:
//inflate the new layout
convertView = mInflater.inflate(R.layout.detail_list_row_odd, parent, false);
holder.tv_time_from = (TextView) convertView.findViewById(R.id.tv_time_from);
holder.tv_time_to = (TextView) convertView.findViewById(R.id.tv_time_to);
holder.tv_current_location_odd = (TextView) convertView.findViewById(R.id.tv_current_location_odd);
//fill the layout with values
/*holder.tv_time_from.setText("12:34");
holder.tv_time_to.setText("12:37");
holder.tv_current_location_odd.setText("Aktueller Standort");*/
holder.tv_time_from.setText(mData.get(position).getTimeStart());
holder.tv_time_to.setText(mData.get(position).getTimeEnd());
holder.tv_current_location_odd.setText(mData.get(position).getLocation());
break;
case TYPE_SEPARATOR:
//inflate the new layout
convertView = mInflater.inflate(R.layout.detail_list_row_even, parent, false);
holder.tv_current_location_even = (TextView) convertView.findViewById(R.id.tv_current_location_even);
holder.img_transport = (ImageView) convertView.findViewById(R.id.img_transport);
//fill the layout with values
holder.tv_current_location_even.setText("Hauptbahnhof");
holder.img_transport.setImageDrawable(context.getResources().getDrawable(R.drawable.rollator));
break;
default:
break;
}
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
return convertView;
}
private static class ViewHolder {
public TextView tv_time_from;
public TextView tv_time_to;
public TextView tv_current_location_odd;
public TextView tv_current_location_even;
public ImageView img_transport;
}
}
Here I generate the data and call the adapter:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detailed_connection);
generateData();
//fill ListView with custom content from MyCustomAdapter class
mAdapter = new MyCustomAdapter(getApplicationContext());
for (int i = 1; i < odd_items.size(); i++) {
mAdapter.addItem(odd_items.get(i));
if (i % 1 == 0) {
mAdapter.addSeparatorItem(odd_items.get(i));
}
}
setListAdapter(mAdapter);
//set duration text
tv_duration = (TextView)findViewById(R.id.tv_duration);
tv_duration.setText("Dauer: 22 Minuten");
}
private void generateData() {
odd_items = new ArrayList<OddListItem>();
odd_items.add(new OddListItem("12:34", "", "Aktueller Standort"));
odd_items.add(new OddListItem("12:37", "12:37", "TUM"));
odd_items.add(new OddListItem("12:42", "12:42", "Hauptbahnhof Nord"));
odd_items.add(new OddListItem("12:48", "12:48", "Hauptbahnhof"));
even_items = new ArrayList<EvenListItem>();
even_items.add(new EvenListItem("R.drawable.rollator", "3 Minuten Fußweg"));
even_items.add(new EvenListItem("R.drawable.bus", "Richtung Hauptbahnhof Nord"));
even_items.add(new EvenListItem("R.drawable.rollator", "6 Minuten Fußweg"));
mData = new Data(odd_items, even_items);
}
Any help would be great. Maybe there is also a better approach then please let me know.
I would create a Single list of Items
public class Items {
private String time_start;
private String time_end;
private String location;
private int image;
private String locationeven;
private int oddoreven;
public String getTime_start() {
return time_start;
}
public void setTime_start(String time_start) {
this.time_start = time_start;
}
public String getTime_end() {
return time_end;
}
public void setTime_end(String time_end) {
this.time_end = time_end;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public int getImage() {
return image;
}
public void setImage(int image) {
this.image = image;
}
public String getLocationeven() {
return locationeven;
}
public void setLocationeven(String locationeven) {
this.locationeven = locationeven;
}
public int getOddoreven() {
return oddoreven;
}
public void setOddoreven(int oddoreven) {
this.oddoreven = oddoreven;
}
}
In onCreate of Activity call
generateData() ;
Then
ArrayList<Items> oddorevenlist = new ArrayList<Items>();
private void generateData() {
Items item1 = new Items();
item1.setTime_start("12:34");
item1.setTime_end("");
item1.setLocation("Aktueller Standort");
item1.setOddoreven(0);
oddorevenlist.add(item1);
Items item2 = new Items();
item2.setImage(R.drawable.ic_launcher);
item2.setLocationeven("3 Minuten Fußweg");
item2.setOddoreven(1);
oddorevenlist.add(item2);
Items item3 = new Items();
item3.setTime_start("12:37");
item3.setTime_end("12:37");
item3.setLocation("Tum");
item3.setOddoreven(0);
oddorevenlist.add(item3);
Items item4 = new Items();
item4.setImage(R.drawable.ic_launcher);
item4.setLocationeven("Richtung Hauptbahnhof Nord");
item4.setOddoreven(1);
oddorevenlist.add(item4);
Items item5 = new Items();
item5.setTime_start("12:42");
item5.setTime_end("12:42");
item5.setLocation("Hauptbahnhof Nord");
item5.setOddoreven(0);
oddorevenlist.add(item5);
Items item6 = new Items();
item6.setImage(R.drawable.ic_launcher);
item6.setLocationeven("R6 Minuten Fußweg");
item6.setOddoreven(1);
oddorevenlist.add(item6);
Items item7 = new Items();
item7.setTime_start("12:48");
item7.setTime_end("12:48");
item7.setLocation("HHauptbahnhof");
item7.setOddoreven(0);
oddorevenlist.add(item7);
MyCustomAdapter mAdapter = new MyCustomAdapter(this,oddorevenlist);
setListAdapter(mAdapter);
}
Adapter code
public class MyCustomAdapter extends BaseAdapter {
// Tag for Logging
private static final String TAG = "MyCustomAdapter";
int type;
private static final int TYPE_ITEM = 0;
private static final int TYPE_SEPARATOR = 1;
private ArrayList<Items> oddorevenlist ;
private LayoutInflater mInflater;
private Context context;
public MyCustomAdapter(Context context, ArrayList<Items> oddorevenlist) {
mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.context = context;
this.oddorevenlist = oddorevenlist;
}
#Override
public int getItemViewType(int position) {
if (oddorevenlist.get(position).getOddoreven()==0){
type = TYPE_ITEM;
} else if (oddorevenlist.get(position).getOddoreven()==1) {
type = TYPE_SEPARATOR;
}
return type;
}
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public int getCount() {
return oddorevenlist.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
int type = getItemViewType(position);
Log.d(TAG, "getView " + position + " " + convertView + " type = " + type);
if (convertView == null) {
holder = new ViewHolder();
switch (type) {
case TYPE_ITEM:
//inflate the new layout
convertView = mInflater.inflate(R.layout.row_odd, parent, false);
holder.tv_time_from = (TextView) convertView.findViewById(R.id.tv_time_from);
holder.tv_time_to = (TextView) convertView.findViewById(R.id.tv_time_to);
holder.tv_current_location_odd = (TextView) convertView.findViewById(R.id.tv_current_location_odd);
holder.tv_time_from.setText(oddorevenlist.get(position).getTime_start());
holder.tv_time_to.setText(oddorevenlist.get(position).getTime_end());
holder.tv_current_location_odd.setText(oddorevenlist.get(position).getLocation());
break;
case TYPE_SEPARATOR:
//inflate the new layout
convertView = mInflater.inflate(R.layout.row_even, parent, false);
holder.tv_current_location_even = (TextView) convertView.findViewById(R.id.tv_current_location_even);
holder.img_transport = (ImageView) convertView.findViewById(R.id.img_transport);
//fill the layout with values
holder.tv_current_location_even.setText(oddorevenlist.get(position).getLocationeven());
holder.img_transport.setImageResource(R.drawable.ic_launcher);
break;
default:
break;
}
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
return convertView;
}
private static class ViewHolder {
public TextView tv_time_from;
public TextView tv_time_to;
public TextView tv_current_location_odd;
public TextView tv_current_location_even;
public ImageView img_transport;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
}
Snap