I have problem with Exoplayer to stopping after the app is closed down, or the fragment is changed from the BottomNavigationView, I get the data from my API that is cast to a Recyclerview/Adapter that handle the data, then the data with the images and video is gettting showed with a PagerAdapter.
I also tried in the fragment to set a onDestroy, but not working.
FeedAdapter.java
public class FeedAdapter extends RecyclerView.Adapter<FeedAdapter.ViewHolder> {
private final List<FeedData> feedList;
private Activity context;
private View.OnClickListener onClickListener;
private SimpleExoPlayer videoPlayer;
REST apiService =
RestClient.getClient().create(REST.class);
public FeedAdapter(Activity context, List<FeedData> feedList) {
this.context = context;
this.feedList = feedList;
this.onClickListener = onClickListener;
}
public List<FeedData> getFeedData(){
return feedList;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_feed_photo, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.mBinding.setFeed(feedList.get(position));
Boolean isLiked = holder.mBinding.getFeed().getIsLiked();
Boolean isSaved = holder.mBinding.getFeed().getIsSaved();
String username = holder.mBinding.getFeed().getUsername();
if (holder.mBinding.getFeed().getAvatar().length() > 0) {
Glide.with(context).load(holder.mBinding.getFeed().getAvatar())
.diskCacheStrategy(DiskCacheStrategy.NONE)
.into(holder.mBinding.userAvatar);
}
holder.mBinding.username.setText(username);
holder.mBinding.description.setHashtagModeColor(ContextCompat.getColor(context, R.color.fitnessm8_green));
holder.mBinding.description.addAutoLinkMode(AutoLinkMode.MODE_HASHTAG, AutoLinkMode.MODE_MENTION);
holder.mBinding.description.setAutoLinkText(holder.mBinding.getFeed().getDescription());
holder.mBinding.likecount.setText(holder.mBinding.getFeed().getLikes().toString());
holder.mBinding.likecounttext.setText(context.getResources().getString(R.string.likes));
holder.mBinding.commentcount.setText(holder.mBinding.getFeed().getComments().size() + " " + context.getResources().getString(R.string.comments));
holder.mBinding.viewMoreComment.setText(context.getResources().getString(R.string.view) + " " + holder.mBinding.getFeed().getComments().size() + " " + context.getResources().getString(R.string.comments));
holder.mBinding.viewMoreComment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
if (isLiked) {
holder.mBinding.like.setLiked(true);
} else {
holder.mBinding.like.setLiked(false);
}
if (isSaved) {
holder.mBinding.fav.setLiked(true);
} else {
holder.mBinding.fav.setLiked(false);
}
if (holder.mBinding.getFeed().getType().equals("image")) {
if (holder.mBinding.getFeed().getMediaSet().size() > 1) {
holder.mBinding.image.setVisibility(View.GONE);
MultiMediaAdapter pagerAdapter = new MultiMediaAdapter(context, holder.mBinding.getFeed().getMediaSet());
holder.mBinding.viewpagerId.setAdapter(pagerAdapter);
ScrollingPagerIndicator pagerIndicator = holder.mBinding.indicator;
pagerIndicator.attachToPager(holder.mBinding.viewpagerId);
} else {
holder.mBinding.viewpagerId.setVisibility(View.GONE);
Glide.with(context).load(holder.mBinding.getFeed().getMediaSet().get(0).getFile())
.placeholder(R.drawable.image_placeholder)
.error(R.drawable.image_placeholder)
.into(holder.mBinding.image);
}
}
if (holder.mBinding.getFeed().getType().equals("video")) {
holder.mBinding.image.setVisibility(View.GONE);
MultiMediaAdapter pagerAdapter = new MultiMediaAdapter(context, holder.mBinding.getFeed().getMediaSet());
holder.mBinding.viewpagerId.setAdapter(pagerAdapter);
ScrollingPagerIndicator pagerIndicator = holder.mBinding.indicator;
pagerIndicator.attachToPager(holder.mBinding.viewpagerId);
}
holder.mBinding.clickUser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(context, UserProfileActivity.class);
i.putExtra("profileUserID", holder.mBinding.getFeed().getUserId());
view.getContext().startActivity(i);
}
});
}
#Override
public int getItemCount() {
return feedList.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
ListItemFeedPhotoBinding mBinding;
public ViewHolder(View itemView) {
super(itemView);
mBinding = DataBindingUtil.bind(itemView);
}
}
#Override
public int getItemViewType(int position) {
return super.getItemViewType(position);
}
public interface ClickListener {
void onClick(View view, int position);
void onLongClick(View view, int position);
}
}
MultiMediaAdapter.java
public class MultiMediaAdapter extends PagerAdapter {
private PlayerView simpleExoPlayerView;
private SimpleExoPlayer player;
private ImageView image;
Context context;
List<FeedMediaSet> Media_list;
public MultiMediaAdapter(Context context, List<FeedMediaSet> Media_list) {
this.context = context;
this.Media_list = Media_list;
}
#Override
public int getCount() {
return Media_list.size();
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view == object;
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
FeedMediaSet mediaObj = Media_list.get(position);
if (mediaObj.getType().equals("image")) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.list_item_media_photo,container,false);
image = view.findViewById(R.id.image);
Glide.with(context).load(mediaObj.getFile())
.placeholder(R.drawable.image_placeholder)
.error(R.drawable.image_placeholder)
.into(image);
container.addView(view);
return view;
} else if (mediaObj.getType().equals("video")) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.list_item_media_video,container,false);
simpleExoPlayerView = view.findViewById(R.id.playerView);
image = view.findViewById(R.id.image);
image.setVisibility(View.GONE);
initializePlayer(mediaObj.getFile(), mediaObj.getExtra());
container.addView(view);
return view;
}
return null;
}
private void initializePlayer(String uri, String extra) {
player = ExoPlayerFactory.newSimpleInstance(context);
try {
Uri mp4VideoExtraUri = Uri.parse(uri);
InputStream inputStream = context.getContentResolver().openInputStream(mp4VideoExtraUri);
Drawable yourDrawable = Drawable.createFromStream(inputStream, extra);
simpleExoPlayerView.setDefaultArtwork(yourDrawable);
} catch (FileNotFoundException e) {
Drawable yourDrawable = context.getResources().getDrawable(R.drawable.image_attach);
simpleExoPlayerView.setDefaultArtwork(yourDrawable);
}
DataSource.Factory mediaDataSourceFactory = new DefaultDataSourceFactory(context, Util.getUserAgent(context, context.getResources().getString(R.string.app_name)));
MediaSource videoSource = new ProgressiveMediaSource.Factory(mediaDataSourceFactory)
.createMediaSource(Uri.parse(uri));
player.setPlayWhenReady(false);
player.prepare(videoSource);
if (simpleExoPlayerView != null) simpleExoPlayerView.setPlayer(player);
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((View) object);
releasePlayer();
}
private void releasePlayer() {
if (player != null) {
player.release();
player = null;
simpleExoPlayerView.setPlayer(null);
}
}
}
Related
I have two Fragments with tabLayout and I am trying to stop current sound of a fragment when i want to play sound in another fragment
this is my adapter class
public class Adapter extends RecyclerView.Adapter<Adapter.holder> {
public Context context;
String data[];
int images[];
int sound[];
holder h;
int playPosition = -1;
public Adapter() {
}
//constructor
public Adapter(String[] data, int[] images, int[] sound, Context context) {
this.data = data;
this.images = images;
this.sound = sound;
this.context = context;
h = null;
playPosition = -1;
}
//class holder
public class holder extends RecyclerView.ViewHolder {
AppCompatImageView imageView;
TextView textView;
MediaPlayer mPlayer;
public holder(#NonNull View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.text_view);
imageView = itemView.findViewById(R.id.img_view);
}
}
#NonNull
#Override
public holder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.singleview, parent, false);
return new holder(view);
}
#Override
public void onBindViewHolder(#NonNull final holder holder, final int position) {
holder.textView.setText(data[position]);
holder.imageView.setImageResource(images[position]);
holder.imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
if (holder.mPlayer != null) {
holder.mPlayer.release();
holder.mPlayer = null;
}
holder.mPlayer = MediaPlayer.create(context, sound[position]);
// stops the previous sound
if (h != null && playPosition != -1 && position != playPosition) {
h.mPlayer.stop();
h.mPlayer = MediaPlayer.create(context, sound[playPosition]);
}
holder.mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
holder.mPlayer.start();
Toast.makeText(context, "started", Toast.LENGTH_SHORT).show();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.stop();
mediaPlayer.release();
holder.mPlayer = null;
Toast.makeText(context, "Finished", Toast.LENGTH_SHORT).show();
// holder.playIcon.setVisibility(View.VISIBLE);
}
});
}
});
} catch (Exception e) {
e.printStackTrace();
}
h = holder;
playPosition = position;
}
});
}
#Override
public int getItemCount() {
return data.length;
}
}
and this is my fragment
public class NatureForest extends Fragment {
RecyclerView recyclerView;
public NatureForest() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_main, container, false);
String tab2Text[] = {"Forest forest","Forest creek","Forest leaves","Forest birds",
"Forest waterfall","Forest wind","Forest fire",
"Forest grasshopper", "Forest frogs"};
int tab2Images[] = {R.drawable.ic_rain2,R.drawable.ic_rain2,R.drawable.ic_rain2,R.drawable.ic_rain2,
R.drawable.ic_rain2,R.drawable.ic_rain2,R.drawable.ic_rain2,R.drawable.ic_rain2,R.drawable.ic_rain2};
int sound[]={R.raw.sounds,R.raw.sounds,R.raw.sounds,R.raw.sounds,R.raw.sounds,
R.raw.sounds,R.raw.sounds,R.raw.sounds,R.raw.sounds,R.raw.sounds,
R.raw.sounds};
recyclerView =view.findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(),3));
recyclerView.setAdapter(new Adapter(tab2Text,tab2Images,sound,getContext()));
return view;
}
}
here if a sound in one fragment is played and at the same time another sound played from 2nd fragment , the previous fragment sound is not stopped.
onPause()
: The system calls this method as the first indication that the user is leaving the fragment. This is usually where you should commit any changes that should be persisted beyond the current user session
Just override this method and pause the mediaplayer instance in that fragment
I want to pass a string value from my adapter class to my fragment. I tried storing the string in a bundle. To retrieve the value i used Bundle b = getArguments(); b.getString("key") the problem is im getting a null pointer exception. Below is the code that saves the string in a bundle. So my question is how can i pass a string value from adapterA to fragmentB.
Thanks in advance.
Adapter.java
public class ToDoRecyclerViewAdapter extends RecyclerView.Adapter<ToDoRecyclerViewAdapter.ViewHolder> {
private Context context;
private List<Aktivnost_> mValues;
private final OnListFragmentInteractionListener mListener;
public ToDoRecyclerViewAdapter td;
public ToDoRecyclerViewAdapter(List<Aktivnost_ > items, Context context, OnListFragmentInteractionListener listener) {
mValues = items;
mListener = listener;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.fragment_todo, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.mItem = mValues.get(position);
holder.mContentView.setText(mValues.get(position).getNaziv());
holder.mDateView.setText(mValues.get(position).getDatum());
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (null != mListener) {
mListener.onListFragmentInteraction(holder.mItem);
Intent i = new Intent(context.getApplicationContext(), PodrobnostiActivity.class);
i.putExtra("task_id", mValues.get(position).getId_());
context.getApplicationContext().startActivity(i);
Toast.makeText(v.getContext(), "task - " + mValues.get(position).getId_(), Toast.LENGTH_SHORT).show();
}
}
});
holder.mView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(final View v) {
AlertDialog.Builder adb = new AlertDialog.Builder(v.getContext());
CharSequence meni[] = new CharSequence[] {"DOING", "FINISHED"};
adb.setItems(meni, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if(i == 0) {
Bundle b = new Bundle();
DoingFragment d = new DoingFragment();
mValues.get(i).setStanje("doing");
b.putString("doing", mValues.get(i).getStanje());
d.setArguments(b);
} else {
mValues.get(i).setStanje("koncano");
}
}
});
AlertDialog alertDialog = adb.create();
alertDialog.setCancelable(true);
alertDialog.show();
return true;
}
});
}
#Override
public int getItemCount() {
return mValues.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final TextView mContentView;
public final TextView mDateView;
public long id;
public Aktivnost_ mItem;
public ViewHolder(View view) {
super(view);
mView = view;
this.id = id;
mDateView = (TextView) view.findViewById(R.id.Date);
mContentView = (TextView) view.findViewById(R.id.content);
}
#Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
}
}
And i want to get the value i set in bundle in this fragment.
Fragment.java
public class DoingFragment extends Fragment {
DoingFragmentRecyclerViewAdapter mAdapter;
private OnListFragmentInteractionListener mListener;
public DoingFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_doingfragment_list, container, false);
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.list_doing);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.addItemDecoration(new DividerItemDecoration(getContext(), LinearLayoutManager.VERTICAL));
mAdapter = new DoingFragmentRecyclerViewAdapter(listAktivnosti(),mListener);
recyclerView.setAdapter(mAdapter);
return view;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnListFragmentInteractionListener) {
mListener = (OnListFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnListFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnListFragmentInteractionListener {
void onListFragmentInteraction1(Aktivnost_ item);
}
AppDatabase db;
public void openDB() {
db = new AppDatabase(getContext());
db.open();
}
Aktivnost_ ak;
List<Aktivnost_> array;
public List<Aktivnost_> listAktivnosti() {
array = new ArrayList<>();
openDB();
Bundle b = getArguments();
Cursor cursor = db.getAllRows(b.getString("doing"));
while(cursor.moveToNext()) {
ak = new Aktivnost_();
ak.setId_(cursor.getLong(cursor.getColumnIndex("_id")));
ak.setNaziv(cursor.getString(cursor.getColumnIndex("naziv")));
ak.setDatum(cursor.getString(cursor.getColumnIndex("datum")));
ak.setFk_projekt(cursor.getInt(cursor.getColumnIndex("fk_projekt")));
ak.setUdeleženci(cursor.getString(cursor.getColumnIndex("udelezenci")));
ak.setStanje(cursor.getString(cursor.getColumnIndex("stanje")));
array.add(ak);
}
return array;
}
}
From the code, I can see you are only setting the Bundle parameters in Fragment object, but not using that fragment object further.
You need to display that fragment object first, then it will reflect into your target fragment.
my recyclerview is great in scrolling but when it contains more than two items and click on last item or the one before it gives me the wrong position this is
and throws a NullPointerException this is my whole code from adapter to the listener.
my code :
public class ListAdapter extends RecyclerView.Adapter<ViewHolder> {
private List<ItemView> items;
private Context context;
public ListAdapter(List<ItemView> items, Context context) {
this.items = items;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_style, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
ItemView i = items.get(position);
ViewHolder.setHeadText(i.getHead());
ViewHolder.setScoreText(i.getContent());
}
#Override
public int getItemCount() {
return items.size();
}
}
class ViewHolder extends RecyclerView.ViewHolder {
private RecyclerViewOnTouchItemListener.ClickListener clickListener;
private static TextView headText, urlText;
private ConstraintLayout itemLayout;
public ViewHolder(View itemView) {
super(itemView);
headText = (TextView) itemView.findViewById(R.id.list_item_header);
urlText = (TextView) itemView.findViewById(R.id.list_item_content);
itemLayout = (ConstraintLayout) itemView.findViewById(R.id.item_list);
// itemLayout.setOnClickListener(this);
}
public static void setHeadText(String headText) {
ViewHolder.headText.setText(headText);
}
public static void setScoreText(String scoreText) {
ViewHolder.urlText.setText(scoreText);
}
public static String getHeadText(){return headText.getText().toString();}
public static String getUrlText(){return urlText.getText().toString();}
}
class RecyclerViewOnTouchItemListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private ClickListener clickListener;
public RecyclerViewOnTouchItemListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildAdapterPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, rv.getChildAdapterPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) { }
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) { }
interface ClickListener {
void onClick(View view, int position);
void onLongClick(View view, int position);
}
}
and this is the activity that holds the recyclerview :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_url_list);
context = getApplicationContext();
database = new DatabaseHelper(context);
listOfUrl = (RecyclerView) findViewById(R.id.url_list);
find = (Button) findViewById(R.id.findBtn);
cancel = (Button) findViewById(R.id.cancelBtn);
makeItPopUp();
listOfUrl.setLayoutManager(new LinearLayoutManager(this));
listOfUrl.setHasFixedSize(true);
listOfUrl.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
adapter = new ListAdapter(fillList(), context);
listOfUrl.setAdapter(adapter);
adapter.notifyDataSetChanged();
selectedItems = new ArrayList<Boolean>(Arrays.asList(new Boolean[listOfUrl.getAdapter().getItemCount()]));
Collections.fill(selectedItems, Boolean.FALSE);
listOfUrl.addOnItemTouchListener(
new RecyclerViewOnTouchItemListener(this, listOfUrl
, new RecyclerViewOnTouchItemListener.ClickListener() {
#Override
public void onClick(View view, int position) {
if (selectedItems.get(position))
setItemSelectedState(false, position, Color.WHITE);
else
setItemSelectedState(true, position, Color.LTGRAY);
}
#Override
public void onLongClick(View view, int position) {}
private void setItemSelectedState(boolean isSelected, int position, int color) {
try {
listOfUrl.getChildAt(position).setBackgroundColor(color);
selectedItems.add(position, isSelected);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
})
);
find.setOnClickListener(this);
cancel.setOnClickListener(this); }
any on can tell me what i did wrong.
Simple solution, create interface class:
public interface ListListener {
void onClick(int pos);
void onLongClick(int pos);
}
Adjust the content of your RecyclerViewAdapter class:
public class ListAdapter extends RecyclerView.Adapter<ViewHolder> {
private ListListener listener;
private List<ItemView> items;
private Context context;
public ListAdapter(List<ItemView> items, Context context) {
this.items = items;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_style, parent, false);
return new ViewHolder(view);
}
public ItemView getItem(int pos) {
return items.get(pos);
}
public void setListener(ListListener listener) {
this.listener = listener;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
ItemView i = items.get(position);
holder.setHeadText(i.getHead());
holder.setScoreText(i.getContent());
holder.itemLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos = holder.getAdapterPosition();
if (listener != null && pos != RecyclerView.NO_POSITION) {
listener.onClick(pos);
}
}
});
holder.itemLayout.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
int pos = holder.getAdapterPosition();
if (pos != -1) {
if (listener != null) {
listener.onLongClick(getItem(pos));
}
}
return true;
}
});
}
And in your Activity class I edited some parts:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_url_list);
context = getApplicationContext();
database = new DatabaseHelper(context);
listOfUrl = (RecyclerView) findViewById(R.id.url_list);
find = (Button) findViewById(R.id.findBtn);
cancel = (Button) findViewById(R.id.cancelBtn);
makeItPopUp();
listOfUrl.setLayoutManager(new LinearLayoutManager(this));
listOfUrl.setHasFixedSize(true);
listOfUrl.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
adapter = new ListAdapter(fillList(), context);
adapter.setListener(new SelectCountryDialogListener() {
#Override
public void onClick(int pos) {
ItemView item = adapter.getItem(pos);
}
#Override
public void onLongClick(int pos) {
ItemView item = adapter.getItem(pos);
}
});
listOfUrl.setAdapter(adapter);
selectedItems = new ArrayList<Boolean>(Arrays.asList(new Boolean[listOfUrl.getAdapter().getItemCount()]));
Collections.fill(selectedItems, Boolean.FALSE);
find.setOnClickListener(this);
cancel.setOnClickListener(this);
}
I'm pretty sure, that now it is very easy for you. Just to implement the functionality in onClick and onLongClick methods.
I am a newbie in android app development and I am following this tutorial to create an image gallery.
https://deepshikhapuri.wordpress.com/2017/03/20/get-all-images-from-gallery-in-android-programmatically/.
It's working perfectly but now I want to display images in ViewPager for being able to display images by swiping left/right.I am using an adapter for doing it.
I have tried doing it but its not working I dont know why.I am not able to swipe images. Can anyone help me with it ? Am i using correct path for the images?
This project is available on github here :
https://github.com/avi003/MyApp0-master-master
ImageGallery.java:
public class ImageGallery extends AppCompatActivity {
public static ArrayList<Model_images> al_images = new ArrayList<>();
boolean boolean_folder;
Adapter_PhotosFolder obj_adapter;
GridView gv_folder;
private static final int REQUEST_PERMISSIONS = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_gallery);
gv_folder = (GridView)findViewById(R.id.gv_folder);
gv_folder.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getApplicationContext(), PhotosActivity.class);
intent.putExtra("value",i);
startActivity(intent);
}
});
if ((ContextCompat.checkSelfPermission(getApplicationContext(),
Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) && (ContextCompat.checkSelfPermission(getApplicationContext(),
Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
if ((ActivityCompat.shouldShowRequestPermissionRationale(ImageGallery.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)) && (ActivityCompat.shouldShowRequestPermissionRationale( ImageGallery.this,
Manifest.permission.READ_EXTERNAL_STORAGE))) {
} else {
ActivityCompat.requestPermissions( ImageGallery.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_PERMISSIONS);
}
}else {
Log.e("Else","Else");
fn_imagespath();
}
}
public ArrayList<Model_images> fn_imagespath() {
al_images.clear();
int int_position = 0;
Uri uri;
Cursor cursor;
int column_index_data, column_index_folder_name;
String absolutePathOfImage;
uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String[] projection = {MediaStore.MediaColumns.DATA, MediaStore.Images.Media.BUCKET_DISPLAY_NAME};
final String orderBy = MediaStore.Images.Media.DATE_TAKEN;
cursor = getApplicationContext().getContentResolver().query(uri, projection, null, null, orderBy + " DESC");
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);
Log.e("Column", absolutePathOfImage);
Log.e("Folder", cursor.getString(column_index_folder_name));
for (int i = 0; i < al_images.size(); i++) {
if (al_images.get(i).getStr_folder().equals(cursor.getString(column_index_folder_name))) {
boolean_folder = true;
int_position = i;
break;
} else {
boolean_folder = false;
}
}
if (boolean_folder) {
ArrayList<String> al_path = new ArrayList<>();
al_path.addAll(al_images.get(int_position).getAl_imagepath());
al_path.add(absolutePathOfImage);
al_images.get(int_position).setAl_imagepath(al_path);
} else {
ArrayList<String> al_path = new ArrayList<>();
al_path.add(absolutePathOfImage);
Model_images obj_model = new Model_images();
obj_model.setStr_folder(cursor.getString(column_index_folder_name));
obj_model.setAl_imagepath(al_path);
al_images.add(obj_model);
}
}
for (int i = 0; i < al_images.size(); i++) {
Log.e("FOLDER", al_images.get(i).getStr_folder());
for (int j = 0; j < al_images.get(i).getAl_imagepath().size(); j++) {
Log.e("FILE", al_images.get(i).getAl_imagepath().get(j));
}
}
obj_adapter = new Adapter_PhotosFolder(getApplicationContext(),al_images);
gv_folder.setAdapter(obj_adapter);
return al_images;
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_PERMISSIONS: {
for (int i = 0; i < grantResults.length; i++) {
if (grantResults.length > 0 && grantResults[i] == PackageManager.PERMISSION_GRANTED) {
fn_imagespath();
} else {
Toast.makeText(ImageGallery.this, "The app was not allowed to read or write to your storage. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show();
}
}
}
}
}
}
PhotosActivity.java:
public class PhotosActivity extends AppCompatActivity {
int int_position;
private GridView gridView;
GridViewAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_gallery);
gridView = (GridView)findViewById(R.id.gv_folder);
int_position = getIntent().getIntExtra("value", 0);
adapter = new GridViewAdapter(this, al_images,int_position);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String abc = "file://" + al_images.get(int_position).getAl_imagepath().get(position);
Intent i = new Intent(getApplicationContext(), FullImageActivity.class);
i.putExtra("id", position);
i.putExtra("abc",abc);
startActivity(i);
}
});
}
}
GridViewAdapter.java:
public class GridViewAdapter extends ArrayAdapter<Model_images> {
Context context;
ViewHolder viewHolder;
ArrayList<Model_images> al_menu = new ArrayList<>();
int int_position;
public GridViewAdapter(Context context, ArrayList<Model_images> al_menu,int int_position) {
super(context, R.layout.activity_adapter__photos_folder, al_menu);
this.al_menu = al_menu;
this.context = context;
this.int_position = int_position;
}
#Override
public int getCount() {
Log.e("ADAPTER LIST SIZE", al_menu.get(int_position).getAl_imagepath().size() + "");
return al_menu.get(int_position).getAl_imagepath().size();
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getViewTypeCount() {
if (al_menu.get(int_position).getAl_imagepath().size() > 0) {
return al_menu.get(int_position).getAl_imagepath().size();
} else {
return 1;
}
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = LayoutInflater.from(getContext()).inflate(R.layout.activity_adapter__photos_folder, parent, false);
viewHolder.tv_foldern = (TextView) convertView.findViewById(R.id.tv_folder);
viewHolder.tv_foldersize = (TextView) convertView.findViewById(R.id.tv_folder2);
viewHolder.iv_image = (ImageView) convertView.findViewById(R.id.iv_image);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.tv_foldern.setVisibility(View.GONE);
viewHolder.tv_foldersize.setVisibility(View.GONE);
Glide.with(context).load("file://" + al_menu.get(int_position).getAl_imagepath().get(position))
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.into(viewHolder.iv_image);
return convertView;
}
private static class ViewHolder {
TextView tv_foldern, tv_foldersize;
ImageView iv_image;
}
}
Adapter_PhotosFolder.java:
public class Adapter_PhotosFolder extends ArrayAdapter<Model_images> {
Context context;
ViewHolder viewHolder;
ArrayList<Model_images> al_menu = new ArrayList<>();
public Adapter_PhotosFolder(Context context, ArrayList<Model_images> al_menu) {
super(context, R.layout.activity_adapter__photos_folder, al_menu);
this.al_menu = al_menu;
this.context = context;
}
#Override
public int getCount() {
Log.e("ADAPTER LIST SIZE", al_menu.size() + "");
return al_menu.size();
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getViewTypeCount() {
if (al_menu.size() > 0) {
return al_menu.size();
} else {
return 1;
}
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = LayoutInflater.from(getContext()).inflate(R.layout.activity_adapter__photos_folder, parent, false);
viewHolder.tv_foldern = (TextView) convertView.findViewById(R.id.tv_folder);
viewHolder.tv_foldersize = (TextView) convertView.findViewById(R.id.tv_folder2);
viewHolder.iv_image = (ImageView) convertView.findViewById(R.id.iv_image);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.tv_foldern.setText(al_menu.get(position).getStr_folder());
viewHolder.tv_foldersize.setText(al_menu.get(position).getAl_imagepath().size()+"");
Glide.with(context).load("file://" + al_menu.get(position).getAl_imagepath().get(0))
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.into(viewHolder.iv_image);
return convertView;
}
private static class ViewHolder {
TextView tv_foldern, tv_foldersize;
ImageView iv_image;
}
}
Model_images.java:
public class Model_images {
String str_folder;
ArrayList<String> al_imagepath;
public String getStr_folder() {
return str_folder;
}
public void setStr_folder(String str_folder) {
this.str_folder = str_folder;
}
public ArrayList<String> getAl_imagepath() {
return al_imagepath;
}
public void setAl_imagepath(ArrayList<String> al_imagepath) {
this.al_imagepath = al_imagepath;
}
}
FullImageActivity.java:
public class FullImageActivity extends AppCompatActivity {
ImageView images;
int position;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_full_image);
Intent i = getIntent();
images = (ImageView) findViewById(R.id.fullImage);
// Selected image id
position = i.getExtras().getInt("id");
Bundle extras = getIntent().getExtras();
String value = extras.getString("abc");
Glide.with(FullImageActivity.this)
.load(value)
.skipMemoryCache(false)
.into(images);
ViewPager mViewPager = (ViewPager) findViewById(R.id.viewpager);
mViewPager.setAdapter(new TouchImageAdapter(this,al_images));
}
}
activity_full_image.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/jazzy_pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/fullImage"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:scaleType="centerCrop"
/>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
TouchImageAdapter.java:
class TouchImageAdapter extends PagerAdapter {
Context context;
String filename;
ArrayList<Model_images> al_menu = new ArrayList<>();
int position,int_position;
public TouchImageAdapter(Context context,ArrayList<Model_images> al_menu){
this.al_menu = al_menu;
this.context = context;
}
#Override
public int getCount() {
return al_menu.size();
}
#Override
public View instantiateItem(ViewGroup container, int position) {
ImageView img = new ImageView(container.getContext());
img.setImageDrawable(getImageFromSdCard(filename,position));
container.addView(img, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
return img;
}
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
public Drawable getImageFromSdCard(String imageName,int position) {
Drawable d = null;
try {
String path = al_menu.get(int_position).getAl_imagepath().get(position)
+ "/";
Bitmap bitmap = BitmapFactory.decodeFile(path + "/" + imageName
+ ".jpeg");
d = new BitmapDrawable(context.getResources(),bitmap);
} catch (IllegalArgumentException e) {
// TODO: handle exception
}
return d;
}
}
Here you are not passing count of images inside that folder, So in TouchImageAdapter you have passing the count of folder like :
al_menu.size() // it always give you size of folder,
al_menu.get(int_position).getAl_imagepath().size();
// passing the folder position so that correct folder images are to be shown.
public TouchImageAdapter(Context context,ArrayList<Model_images> al_menu, int position){
this.al_menu = al_menu;
this.context = context;
this.int_position = position;
}
#Override
public int getCount() {
return al_menu.get(int_position).getAl_imagepath().size();
}
Here is the updated code I pushed on
https://github.com/redviper00/game
try this
String[] filenames = new String[0];
File path = new File(Environment.getExternalStorageDirectory() + "/your folder");
if (path.exists()) {
filenames = path.list();
}
for (int i = 0; i < filenames.length; i++) {
imagesPathArrayList.add(path.getPath() + "/" + filenames[i]);
Log.e("FAV_Images", imagesPathArrayList.get(i));
adapter = new ImageAdapter(FavActivity.this, imagesPathArrayList);
myviewpager.setAdapter(adapter);
}
create adapter class like this
public class ImageAdapter extends PagerAdapter {
Context context;
ArrayList<String> arrayList;
ImageAdapter(Context context, ArrayList<String> arrayList) {
this.context = context;
this.arrayList = arrayList;
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
viewPagerImageView = new ImageView(context);
viewPagerImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
Bitmap bitmap = BitmapFactory.decodeFile(arrayList.get(position));
viewPagerImageView.setImageBitmap(bitmap);
((ViewPager) container).addView(viewPagerImageView, 0);
return viewPagerImageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
It seems like you are showing Imageview above view pager
images = (ImageView) findViewById(R.id.fullImage);
that is why when you are trying to swipe imageview handle your tocuh action instead of view pager. Remove it.
I'm in a bind here, I wanted to integrate OnItemClickListener in my CustomAdapter, so when an item is click, it'll show some message or something. But I am not sure where to set it. I've look at bunch of tutorials and some post here but it only make me more confuse. So I need guidance on how and where would I need to set it to make it work. Here is my code:
MainActivity.java
ListView listView;
listView = (ListView) findViewById(R.id.list_item);
new ReadRSS(MainActivity.this, listView, "http://malaysiakini.com/en/news.rss").execute();
ReadRSS.java
#Override
protected void onPostExecute(Void aVoid) {
//Dismiss progress dialog
super.onPostExecute(aVoid);
progressDialog.dismiss();
if (feedItems != null) {
CustomAdapter customAdapter = new CustomAdapter(context,R.layout.activity_listview,feedItems);
listView.setAdapter(customAdapter);
}
}
CustomAdapter.java
public class CustomAdapter extends ArrayAdapter<FeedItem> {
public CustomAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
public CustomAdapter(Context context, int resource, List<FeedItem> items) {
super(context, resource, items);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.activity_listview, null);
}
FeedItem p = getItem(position);
if (p != null) {
TextView tt1 = (TextView) v.findViewById(R.id.title_text);
TextView tt2 = (TextView) v.findViewById(R.id.date_text);
if (tt1 != null) {
tt1.setText(p.getTitle());
}
if (tt2 != null) {
tt2.setText(p.getPubDate());
}
}
return v;
}
}
Here is not the direct answer to your question, but my own code example so you can have a look at it and get the idea;
ListAdapter adapter = new ArrayAdapter<String>(this,R.layout.listword,R.id.wordView1, companies);
ListView listView = (ListView) findViewById(R.id.secondListView1);
listView.setAdapter(adapter);
// Item Click listener
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> ok, View v, int position, long id){
// Do your stuff here
}
});
You don't set it inside the adapter, but inside your activity where you define you ListView :
ListView listView = (ListView)findViewById(R.id.list_item);
new ReadRSS(MainActivity.this, listView, "http://malaysiakini.com/en/news.rss").execute();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// your code here
}
}
You can perform task on individual component of CustomAdapter class. Check below code.
public class CustomAdapter extends ArrayAdapter<FeedItem> {
public CustomAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
public CustomAdapter(Context context, int resource, List<FeedItem> items) {
super(context, resource, items);
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View v = convertView;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.activity_listview, null);
}
FeedItem p = getItem(position);
if (p != null) {
TextView tt1 = (TextView) v.findViewById(R.id.title_text);
TextView tt2 = (TextView) v.findViewById(R.id.date_text);
if (tt1 != null) {
tt1.setText(p.getTitle());
}
if (tt2 != null) {
tt2.setText(p.getPubDate());
}
tt1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Perform your task
});
tt2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Perform your task
});
}
return v;
}
}
Just like this,hope it helps:
public class CustomAdapter extends ArrayAdapter<FeedItem> implements OnClickListener{
private Context mContext;
public CustomAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
mContext = context;
}
public CustomAdapter(Context context, int resource, List<FeedItem> items) {
super(context, resource, items);
mContext = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.activity_listview, null);
}
FeedItem p = getItem(position);
v.setTag(p);
v.setOnClickListener(this);
if (p != null) {
TextView tt1 = (TextView) v.findViewById(R.id.title_text);
TextView tt2 = (TextView) v.findViewById(R.id.date_text);
if (tt1 != null) {
tt1.setText(p.getTitle());
}
if (tt2 != null) {
tt2.setText(p.getPubDate());
}
}
return v;
}
#Override
public void onClick(View v){
FeedItem p = (FeedItem) v.getTag();
// TODO,do something with p and mContext
}
}
But I think you should use listview.setOnItemClickListener(listener) to do this work.
Write this code on your activity below of your set adapter method.
Set Adapter Method
private void setAdapter() {
try {
DoctorAppointmentListAdapter doctorAppointmentListAdapter = new DoctorAppointmentListAdapter(getContext(), doctorAppointmentObjectArrayList, selectedItemClickListener, screen);
appointmentListView.setAdapter(doctorAppointmentListAdapter);
}catch (Exception e){}
}
Costume Click Methods
//ListAdapter Click Listener
DoctorAppointmentListAdapter.SelectItemClickListener selectedItemClickListener = new DoctorAppointmentListAdapter.SelectItemClickListener() {
#Override
public void itemClickedAtIndex(int index, String operation) {
if (operation.equalsIgnoreCase("00")) {
m_handler.removeCallbacks(m_handlerTask);
viewDetailsScreen(index);
} else if (operation.equalsIgnoreCase("11")) {
m_handler.removeCallbacks(m_handlerTask);
//Video Call Operation
patirntId = doctorAppointmentObjectArrayList.get(index).getAppointment_patient_id();
videocallService(doctorAppointmentObjectArrayList.get(index).getAppointment_patient_id(), doctorAppointmentObjectArrayList.get(index).getAppointment_id());
} else if (operation.equalsIgnoreCase("33")) {
m_handler.removeCallbacks(m_handlerTask);
//Video Call Operation
patirntId = doctorAppointmentObjectArrayList.get(index).getAppointment_patient_id();
videocallCompletedService(doctorAppointmentObjectArrayList.get(index).getAppointment_patient_id(), doctorAppointmentObjectArrayList.get(index).getAppointment_id());
} else if (operation.equalsIgnoreCase("22")) {
m_handler.removeCallbacks(m_handlerTask);
//Phone Call Operation
if (doctorAppointmentObjectArrayList.get(index).getPatient_contact_no().length() > 0) {
Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + doctorAppointmentObjectArrayList.get(index).getPatient_contact_no()));
startActivity(intent);
} else {
}
}
}
};
This is Adapter Class
public class DoctorAppointmentListAdapter extends BaseAdapter {
private LayoutInflater inflater = null;
private Context context;
private int screen;
private ArrayList<DoctorAppointmentObject> doctorAppointmentObjectArrayList;
private SelectItemClickListener itemClickListener;
public DoctorAppointmentListAdapter(Context context, ArrayList<DoctorAppointmentObject> doctorAppointmentObjectArrayList, SelectItemClickListener listener, int screen) {
this.context = context;
this.screen = screen;
this.doctorAppointmentObjectArrayList = doctorAppointmentObjectArrayList;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
try {
if (itemClickListener != null) {
itemClickListener = null;
}
itemClickListener = listener;
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public int getCount() {
return doctorAppointmentObjectArrayList.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
public interface SelectItemClickListener {
public void itemClickedAtIndex(int index, String operation);
}
private class ViewHolder {
private TextView doctorNameTextView, numberTextView, datetimeTextView, enteryTextView;
private TextView viewDetailTextView, videoCallTextView, phoneCallTextView;
private CircleImageView profile_image;
private ImageView onlineStatusImageView;
private CircularProgressView progress_view;
}
ViewHolder holder = null;
#Override
public View getView(final int i, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.adapter_doctor_appointment_list, parent, false);
holder = new ViewHolder();
holder.doctorNameTextView = (TextView) convertView
.findViewById(R.id.doctorNameTextView);
holder.numberTextView = (TextView) convertView
.findViewById(R.id.numberTextView);
holder.datetimeTextView = (TextView) convertView
.findViewById(R.id.datetimeTextView);
holder.enteryTextView = (TextView) convertView
.findViewById(R.id.enteryTextView);
holder.viewDetailTextView = (TextView) convertView
.findViewById(R.id.viewDetailTextView);
holder.videoCallTextView = (TextView) convertView
.findViewById(R.id.videoCallTextView);
holder.phoneCallTextView = (TextView) convertView
.findViewById(R.id.phoneCallTextView);
holder.profile_image = (CircleImageView) convertView
.findViewById(R.id.profile_image);
holder.progress_view = (CircularProgressView) convertView.findViewById(R.id.progress_view);
holder.onlineStatusImageView = (ImageView) convertView.findViewById(R.id.onlineStatusImageView);
holder.onlineStatusImageView.setVisibility(View.INVISIBLE);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if (screen == 1) {
holder.videoCallTextView.setVisibility(View.GONE);
}
try {
Picasso.with(context).load(doctorAppointmentObjectArrayList.get(i).getPatient_profile_pic()).into(holder.profile_image, new Callback() {
#Override
public void onSuccess() {
holder.progress_view.setVisibility(View.GONE);
}
#Override
public void onError() {
holder.progress_view.setVisibility(View.GONE);
holder.profile_image.setImageResource(R.mipmap.ic_launcher);
}
});
} catch (Exception e) {
holder.profile_image.setImageResource(R.mipmap.ic_launcher);
holder.progress_view.setVisibility(View.GONE);
e.printStackTrace();
}
holder.doctorNameTextView.setText(doctorAppointmentObjectArrayList.get(i).getPatient_display_name());
holder.numberTextView.setText(doctorAppointmentObjectArrayList.get(i).getPatient_contact_no());
if (doctorAppointmentObjectArrayList.get(i).getAppointment_time().equalsIgnoreCase("")) {
holder.numberTextView.setText("");
} else {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
Date testDate = null;
try {
testDate = sdf.parse(doctorAppointmentObjectArrayList.get(i).getAppointment_time());
} catch (Exception ex) {
ex.printStackTrace();
}
SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy hh:mm a");
String newFormat = formatter.format(testDate);
holder.numberTextView.setText("" + newFormat);
}
holder.datetimeTextView.setText(doctorAppointmentObjectArrayList.get(i).getAppointment_reason());
if (screen==0){
holder.enteryTextView.setText("Entry Time :" + doctorAppointmentObjectArrayList.get(i).getAppointment_entry_time());
}else {
holder.enteryTextView.setText("");
}
holder.viewDetailTextView.setId(i);
holder.viewDetailTextView.setOnClickListener(viewDetailSelectedListener);
holder.videoCallTextView.setId(i);
holder.videoCallTextView.setOnClickListener(videoCallSelectedListener);
holder.phoneCallTextView.setId(i);
holder.phoneCallTextView.setOnClickListener(phoneCallSelectedListener);
return convertView;
}
View.OnClickListener viewDetailSelectedListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
int index = (Integer) v.getId();
itemClickListener.itemClickedAtIndex(index, "00");
} catch (Exception e) {
e.printStackTrace();
}
}
};
View.OnClickListener videoCallSelectedListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
int index = (Integer) v.getId();
if (screen == 2) {
itemClickListener.itemClickedAtIndex(index, "33");
} else {
itemClickListener.itemClickedAtIndex(index, "11");
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
View.OnClickListener phoneCallSelectedListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
int index = (Integer) v.getId();
itemClickListener.itemClickedAtIndex(index, "22");
} catch (Exception e) {
e.printStackTrace();
}
}
};
}