Playing videos using textureview inside recyclerview with cardview in android - android

I done video playing inside recyclerview with cardview using sdcard path location. Also check sdcard not available then fetch recorded videos from internal memory. Its perfectly working in Lava iris x8 device, but in Samsung J5 and Samsung Note 2 only odd numbers(1,3,5,7) videos are playing not even(2,4,6,8) videos are playing and getting dialog like "Can't play this video" when scrolling and getting position of even(2,4,6,8) numbers of video. I am not able to know what is the problem? Below is my whole code about display and play video inside recyclerview and cardview in android.
display_video.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF"
android:orientation="vertical">
<RelativeLayout
android:id="#+id/mRelative_background"
android:layout_width="fill_parent"
android:layout_height="200dp"
android:background="#6FC298">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="15dp">
<RelativeLayout
android:id="#+id/mRelativeClick"
android:layout_width="50dp"
android:layout_height="30dp"
android:gravity="left">
<ImageView
android:id="#+id/mImage_back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:src="#mipmap/icon_back"></ImageView>
</RelativeLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="My Challenge"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:textStyle="italic" />
<ImageView
android:id="#+id/mImageView_setting"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:src="#mipmap/icon_setting"></ImageView>
</RelativeLayout>
<RelativeLayout
android:id="#+id/mRelative_circular_image"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="65dp">
<ImageView
android:id="#+id/mImageView_color1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:visibility="invisible"
android:layout_marginLeft="10dp"
android:src="#mipmap/color1"/>
<ImageView
android:id="#+id/mImageView_color2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="5dp"
android:visibility="invisible"
android:layout_toRightOf="#+id/mImageView_color1"
android:src="#mipmap/color2"/>
<ImageView
android:id="#+id/mImageView_color3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="5dp"
android:visibility="invisible"
android:layout_toRightOf="#+id/mImageView_color2"
android:src="#mipmap/color3"/>
<app.stakes.CircularImageView
android:id="#+id/mcircularImage"
android:layout_width="75dp"
android:layout_height="75dp"
android:layout_centerInParent="true"
android:background="#mipmap/camera_icon" />
<ImageView
android:id="#+id/mImageView_color4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="5dp"
android:visibility="invisible"
android:layout_toRightOf="#+id/mcircularImage"
android:src="#mipmap/color4"/>
<ImageView
android:id="#+id/mImageView_color5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="5dp"
android:visibility="invisible"
android:layout_toRightOf="#+id/mImageView_color4"
android:src="#mipmap/color5"/>
<ImageView
android:id="#+id/mImageView_color6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="5dp"
android:visibility="invisible"
android:layout_toRightOf="#+id/mImageView_color5"
android:src="#mipmap/color6"/>
</RelativeLayout>
<TextView
android:id="#+id/mTextViewUsername_VideoList"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/mRelative_circular_image"
android:layout_centerInParent="true"
android:layout_marginTop="25dp"
android:text="Text"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:textStyle="italic" />
<ImageView
android:id="#+id/mImageView_color_table"
android:src="#mipmap/color_table"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/mRelative_circular_image"
android:layout_marginTop="25dp"
android:layout_marginRight="15dp"
android:layout_alignParentRight="true"
/>
</RelativeLayout>
<RelativeLayout
android:id="#+id/mRelativeTab"
android:layout_below="#+id/mRelative_background"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/mImageViewtab2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#mipmap/list"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<ImageView
android:id="#+id/mImageViewtab1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#mipmap/view"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="40dp"
android:layout_marginStart="40dp" />
<ImageView
android:id="#+id/mImageViewtab3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#mipmap/showbook"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_marginRight="40dp"
/>
</RelativeLayout>
<RelativeLayout
android:layout_below="#+id/mRelativeTab"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<android.support.v7.widget.RecyclerView
android:id="#+id/my_recycler_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:scrollbars="vertical" />
</RelativeLayout>
</RelativeLayout>
cardview1.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
card_view:cardCornerRadius="5dp"
card_view:cardUseCompatPadding="true">
<RelativeLayout
android:background="#FFFFFF"
android:id="#+id/mRelativeMain"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<!--<ImageView
android:id="#+id/iconId"
android:layout_width="300dp"
android:layout_height="250dp"
android:layout_centerHorizontal="true"/>-->
<app.stakes.CircularImageView
android:id="#+id/circleImageview"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:background="#mipmap/camera_icon" />
<TextView
android:id="#+id/tvVersionName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:layout_toRightOf="#+id/circleImageview"
android:layout_marginLeft="5dp"
android:text="Auther"
android:textColor="#android:color/black"
android:textSize="7sp" />
<TextView
android:id="#+id/tvTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:layout_toRightOf="#+id/circleImageview"
android:layout_marginLeft="70dp"
android:textColor="#android:color/black"
android:textSize="10sp" />
<ImageView
android:id="#+id/mImageview_clock"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:layout_toLeftOf="#+id/tvSec"
android:src="#mipmap/timing"/>
<TextView
android:id="#+id/tvSec"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginRight="10dp"
android:layout_marginTop="35dp"
android:text="Lollipop"
android:textColor="#android:color/black"
android:textSize="5sp" />
<FrameLayout
android:id="#+id/video_frame"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#+id/circleImageview">
<com.sprylab.android.widget.TextureVideoView
android:id="#+id/mvideoView"
android:layout_width="300dp"
android:layout_height="300dp"
android:layout_marginTop="10dp"
android:layout_gravity="center_horizontal|center_vertical"
/>
<ImageView
android:id="#+id/mImageview_play"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|center_vertical"
android:src="#mipmap/play" />
<ImageView
android:id="#+id/mImageView_fav"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/mImageview_play"
android:layout_gravity="left|center_vertical"
android:layout_marginLeft="40dp"
android:layout_marginTop="130dp"
android:src="#mipmap/bookmark_video" />
<ImageView
android:id="#+id/mImageView_share"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_below="#+id/mImageview_play"
android:layout_gravity="right|center_vertical"
android:layout_marginRight="40dp"
android:layout_marginTop="130dp"
android:src="#mipmap/sharevideo" />
<!--</RelativeLayout>-->
</FrameLayout>
</RelativeLayout>
</android.support.v7.widget.CardView>
Display_Video1.java
public class Display_Video1 extends ActionBarActivity {
public RecyclerView recyclerView;
private ArrayList<FeddProperties> os_versions;
private Adapter mAdapter;
private Adapter fav_video_adapter;
CircularImageView mcircularImage;
static DisplayMetrics dm;
static MediaController media_Controller;
RelativeLayout mRelativeClick;
static boolean isViewWithCatalog;
RelativeLayout mRelative_background;
static File OldFile;
static String[] fileList = null;
static String[] fileListOld = null;
/*static String FILE_PATH = newFile.getAbsolutePath();*/
static String FILEPATH_OLD;
static String videoOldFilePath;
static String replaceOldString;
String MiME_TYPE = "video/mp4";
static String videoFilePath;
static String replaceStr;
static String[] fav_video_list = null;
CallbackManager callbackManager;
public static String facebook_user_id;
public static String username;
Boolean isSDPresent;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.display_video);
isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
if(isSDPresent) {
OldFile = new File(Environment.getExternalStorageDirectory(), "/Stakes_Download");
MEDIA_PATHOLD = new String(OldFile.getAbsolutePath());
FILEPATH_OLD = OldFile.getAbsolutePath();
}
else{
OldFile = new File(this.getFilesDir(), "Stakes_Download");
MEDIA_PATHOLD = new String(OldFile.getAbsolutePath());
FILEPATH_OLD = OldFile.getAbsolutePath();
}
recyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
os_versions = new ArrayList<FeddProperties>();
if (fileList != null) {
for (int i = 0; i < fileList.length; i++) {
if (fileList[i].length() == 0) {
ArrayList<Integer> alist = new ArrayList<Integer>();
alist.add(fileList.length);
Toast.makeText(getApplicationContext(), "File Zero: " + Arrays.toString(fileList), Toast.LENGTH_LONG).show();
}
}
}
if (fileListOld != null) {
for (int i = 0; i < fileListOld.length; i++) {
if (fileListOld[i].length() == 0) {
ArrayList<Integer> alist = new ArrayList<Integer>();
alist.add(fileListOld.length);
Toast.makeText(getApplicationContext(), "File Zero: " + Arrays.toString(fileListOld), Toast.LENGTH_LONG).show();
}
}
}
recyclerView.setHasFixedSize(true);
// ListView
recyclerView.setLayoutManager(new LinearLayoutManager(Display_Video1.this));
// create an Object for Adapter
if (fileList != null) {
mAdapter = new CardViewDataAdapter(Display_Video1.this, fileList);
// set the adapter object to the Recyclerview
recyclerView.setAdapter(mAdapter);
} else {
/*Toast.makeText(getApplicationContext(),"No File Exist",Toast.LENGTH_LONG).show();*/
}
updateSongList();
updateSongListOld();
initContrls();
}
public void updateSongList() {
File videoFiles = new File(MEDIA_PATHOLD);
Log.d("**Value of videoFiles**", videoFiles.toString());
if (videoFiles.isDirectory()) {
fileList = videoFiles.list();
}
if (fileList == null) {
System.out.println("File doesnot exit");
Toast.makeText(this, "There is no file", Toast.LENGTH_SHORT).show();
} else {
System.out.println("fileList****************" + fileList);
for (int i = 0; i < fileList.length; i++) {
Log.e("Video:" + i + " File name", fileList[i]);
}
}
}
public void updateSongListOld() {
File videoFiles = new File(MEDIA_PATHOLD);
Log.d("**Value of videoFiles**", videoFiles.toString());
if (videoFiles.isDirectory()) {
fileListOld = videoFiles.list();
}
if (fileListOld == null) {
System.out.println("File doesnot exit");
Toast.makeText(this, "There is no file", Toast.LENGTH_SHORT).show();
} else {
System.out.println("fileList****************" + fileListOld);
for (int i = 0; i < fileListOld.length; i++) {
Log.e("Video:" + i + " File name", fileListOld[i]);
}
}
}
private void initContrls() {
recyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
os_versions = new ArrayList<FeddProperties>();
if (fileList != null) {
/*gridView.setAdapter(new ImageAdapter(this, fileList));*/
for (int i = 0; i < fileList.length; i++) {
if (fileList[i].length() == 0) {
ArrayList<Integer> alist = new ArrayList<Integer>();
alist.add(fileList.length);
Toast.makeText(getApplicationContext(), "File Zero: " + Arrays.toString(fileList), Toast.LENGTH_LONG).show();
/* FeddProperties feed = new FeddProperties();
feed.setTitle(fileList[i]);
*//*feed.setThumbnail(icons[i]);*//*
os_versions.add(feed);*/
}
}
}
if (fileListOld != null) {
/*gridView.setAdapter(new ImageAdapter(this, fileList));*/
for (int i = 0; i < fileListOld.length; i++) {
if (fileListOld[i].length() == 0) {
ArrayList<Integer> alist = new ArrayList<Integer>();
alist.add(fileListOld.length);
Toast.makeText(getApplicationContext(), "File Zero: " + Arrays.toString(fileListOld), Toast.LENGTH_LONG).show();
/* FeddProperties feed = new FeddProperties();
feed.setTitle(fileList[i]);
*//*feed.setThumbnail(icons[i]);*//*
os_versions.add(feed);*/
}
}
}
recyclerView.setHasFixedSize(true);
// ListView
recyclerView.setLayoutManager(new LinearLayoutManager(this));
//Grid View
/* recyclerView.setLayoutManager(new GridLayoutManager(this,2,1,false));*/
//StaggeredGridView
/*recyclerView.setLayoutManager(new StaggeredGridLayoutManager(2,1));*/
// create an Object for Adapter
if (fileList != null) {
mAdapter = new CardViewDataAdapter(Display_Video1.this, fileList);
// set the adapter object to the Recyclerview
recyclerView.setAdapter(mAdapter);
} else {
/*Toast.makeText(getApplicationContext(),"No File Exist",Toast.LENGTH_LONG).show();*/
}
recyclerView.addOnItemTouchListener(new CardViewDataAdapter(Display_Video1.this, new CardViewDataAdapter.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
}
}));
}
Recyclerview Adapter
public static class CardViewDataAdapter extends Adapter<CardViewDataAdapter.ViewHolder> implements OnItemTouchListener {
private ArrayList<FeddProperties> dataSet;
private OnItemClickListener mListener;
GestureDetector mGestureDetector;
private Context context;
private String[] VideoValues;
private int position = 0;
public interface OnItemClickListener {
public void onItemClick(View view, int position);
}
public CardViewDataAdapter(Context context, String[] VideoValues) {
/*dataSet = os_versions;*/
this.context = context;
this.VideoValues = VideoValues;
}
public CardViewDataAdapter(Context context, OnItemClickListener listener) {
mListener = listener;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
// create a new view
View itemLayoutView = LayoutInflater.from(viewGroup.getContext()).inflate(
R.layout.card_view1, null);
ViewHolder viewHolder = new ViewHolder(itemLayoutView);
return viewHolder;
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
public void onBindViewHolder(final ViewHolder viewHolder, final int i) {
videoFilePath = FILEPATH_OLD + "/" + fileList[i];
Toast.makeText(context,"Path: "+videoFilePath,Toast.LENGTH_LONG).show();
viewHolder.tvVersionName.setText(fileList[i]);
System.out
.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>> file path>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
+ fileList[i]);
viewHolder.mvideoView.setVideoPath(videoFilePath);
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
retriever.setDataSource(context, Uri.parse(videoFilePath));
final String time = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
long timeInMillisec = Long.parseLong(time);
final long duration = timeInMillisec / 1000;
long hours = duration / 3600;
long minutes = (duration - hours * 3600) / 60;
final long seconds = duration - (hours * 3600 + minutes * 60);
viewHolder.tvSec.setText(String.valueOf(seconds) + "s");
viewHolder.mImageview_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (viewHolder.mvideoView!= null) {
if (viewHolder.mvideoView.isPlaying()) {
viewHolder.mvideoView.pause();
viewHolder.mImageview_play.setImageResource(R.mipmap.play);
} else {
viewHolder.mvideoView.start();
viewHolder.mImageview_play.setImageResource(R.mipmap.play_click);
}
}
viewHolder.mvideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
viewHolder.mImageview_play.setImageResource(R.mipmap.play);
}
});
}
});
viewHolder.str = fileList;
}
#Override
public int getItemCount() {
return VideoValues.length;
}
#Override
public boolean onInterceptTouchEvent(RecyclerView recyclerView, MotionEvent e) {
View childView = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
mListener.onItemClick(childView, recyclerView.getChildAdapterPosition(childView));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean b) {
}
// inner class to hold a reference to each item of RecyclerView
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView tvVersionName;
public TextView tvTitle;
public TextView tvSec;
/*public ImageView iconView;*/
/*public RelativeLayout mvideoView;*/
public TextureVideoView mvideoView;
public ImageView mImageview_play;
public CircularImageView circleImageview;
public ImageView mImageView_fav;
public ImageView mImageView_share;
public FeddProperties feed;
public String[] str;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
tvVersionName = (TextView) itemLayoutView
.findViewById(R.id.tvVersionName);
/*iconView = (ImageView) itemLayoutView
.findViewById(R.id.iconId);*/
tvSec = (TextView) itemLayoutView.findViewById(R.id.tvSec);
tvTitle = (TextView) itemLayoutView.findViewById(R.id.tvTitle);
mvideoView = (TextureVideoView) itemLayoutView.findViewById(R.id.mvideoView);
mImageview_play = (ImageView) itemLayoutView.findViewById(R.id.mImageview_play);
}
}
}

Related

RecyclerView displays only one item

Am trying to build my first app and my recyclerView only displays the first item from the json.I have tried changing the layout height to wrap_content but its still not working
Here is the xml layout for the recyclerview activity
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.aleky.carrental.cars">
<RelativeLayout
android:id="#+id/relativeLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<android.support.v7.widget.RecyclerView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/rv"
android:clickable="false"
/>
</RelativeLayout>
</RelativeLayout>
the cardview xml layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:cardview="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
cardview:cardCornerRadius="2dp"
cardview:cardElevation="3dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#fff"
android:paddingBottom="15dp">
<TextView
android:id="#+id/car_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="2dp"
android:layout_marginTop="2dp"
android:fontFamily="sans-serif-smallcaps"
android:text="Car Name"
android:textColor="#996515"
android:textSize="24sp"
android:textStyle="bold" />
<com.android.volley.toolbox.NetworkImageView
android:id="#+id/Car_image"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_below="#+id/car_name"
android:layout_marginBottom="2dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="2dp" />
<TextView
android:id="#+id/tvfeature"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="90dp"
android:layout_marginTop="25dp"
android:layout_toRightOf="#+id/car_name"
android:text="Features"
android:textColor="#000"
android:textSize="22sp" />
<View
android:layout_width="100dp"
android:layout_height="1dp"
android:layout_below="#+id/tvfeature"
android:layout_marginLeft="20dp"
android:layout_toRightOf="#+id/Car_image"
android:background="#000" />
<ImageView
android:id="#+id/ac"
android:layout_width="40dp"
android:layout_height="20dp"
android:layout_below="#+id/tvfeature"
android:layout_marginLeft="20dp"
android:layout_marginTop="10dp"
android:layout_toRightOf="#+id/Car_image"
android:src="#drawable/air_conditioner" />
<TextView
android:id="#+id/feature1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tvfeature"
android:layout_marginTop="10dp"
android:layout_toRightOf="#+id/ac"
android:text="Air conditioner"
android:textColor="#000"
android:textSize="16sp" />
<ImageView
android:id="#+id/tr"
android:layout_width="40dp"
android:layout_height="20dp"
android:layout_below="#+id/feature1"
android:layout_marginLeft="20dp"
android:layout_marginTop="10dp"
android:layout_toRightOf="#+id/Car_image"
android:src="#drawable/transmission" />
<TextView
android:id="#+id/feature2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/feature1"
android:layout_marginLeft="2dp"
android:layout_marginTop="10dp"
android:layout_toRightOf="#+id/tr"
android:text="Manual"
android:textColor="#333333"
android:textSize="16sp" />
<ImageView
android:id="#+id/pass"
android:layout_width="40dp"
android:layout_height="20dp"
android:layout_below="#+id/tr"
android:layout_marginLeft="20dp"
android:layout_marginTop="5dp"
android:layout_toRightOf="#+id/Car_image"
android:src="#drawable/passengers" />
<TextView
android:id="#+id/feature3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/feature2"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:layout_toRightOf="#id/pass"
android:text="6 Passengers"
android:textColor="#333333"
android:textSize="16sp" />
<TextView
android:id="#+id/pricetxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/Car_image"
android:text="Price :"
android:textColor="#333333"
android:textSize="22sp"
android:textStyle="bold" />
<TextView
android:id="#+id/car_price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/Car_image"
android:layout_marginLeft="2dp"
android:layout_toRightOf="#+id/pricetxt"
android:text="KSH.2000"
android:textColor="#996515"
android:textSize="22sp" />
<TextView
android:id="#+id/organiser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/pricetxt"
android:layout_marginTop="5dp"
android:text="Owner :"
android:textColor="#333333"
android:textSize="14sp" />
<TextView
android:id="#+id/crAgent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/pricetxt"
android:layout_marginLeft="2dp"
android:layout_marginTop="5dp"
android:layout_toEndOf="#+id/organiser"
android:layout_toRightOf="#+id/organiser"
android:text="Supercars Rentals"
android:textColor="#05056c"
android:textSize="14sp" />
<Button
android:id="#+id/btn_rent"
style="#style/AppTheme.ButtonCorners"
android:layout_width="150dp"
android:layout_height="40dp"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/Car_image"
android:layout_marginRight="12dp"
android:clickable="true"
android:text="Rent"
android:textColor="#eef525" />
<TextView
android:id="#+id/car_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="invisible" />
</RelativeLayout>
</android.support.v7.widget.CardView>
The cars.java class to load items into the recyclerview
public class cars extends AppCompatActivity {
String url = "http://192.168.43.201/Car_rental/retrievecars.php";
Context context = null;
ProgressDialog dialog;
private List<CarsItem> array_cars = new ArrayList<>();
AdapterClass adapter;
NetworkImageView carsImageview;
private String user_Location = "cLocation";
private String Category = "category";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cars);
adapter = new AdapterClass(cars.this, array_cars);
RecyclerView recycler = (RecyclerView) findViewById(R.id.rv);
recycler.setHasFixedSize(true);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recycler.setLayoutManager(layoutManager);
recycler.setItemAnimator(new DefaultItemAnimator());
recycler.setAdapter(adapter);
setCars();
recycler.addOnItemTouchListener(new RecyclerTouchListener(this, recycler, new ClickListener() {
#Override
public void onClick(View view, int position) {
}
#Override
public void onLongClick(View view, int position) {
}
}));
}
public void setCars() {
dialog = new ProgressDialog(this);
dialog.setMessage("Loading cars...");
dialog.show();
if (array_cars != null) {
array_cars.clear();
}
StringRequest request = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
try {
hideDialog();
Log.d("Sever Message", s);
JSONObject cars = new JSONObject(s);
JSONArray jsonArray = cars.getJSONArray("Cars");
JSONObject jobject = null;
int len = jsonArray.length();
for (int i = 0; i < len; i++) {
jobject = jsonArray.getJSONObject(i);
CarsItem carsdata = new CarsItem();
carsdata.setId(jobject.getString("0"));
carsdata.setCarname(jobject.getString("1"));
carsdata.setImages(jobject.getString("car_image"));
carsdata.setfeature1(jobject.getString("5"));
carsdata.setfeature2(jobject.getString("6"));
carsdata.setfeature3(jobject.getString("7"));
carsdata.setPrice(jobject.getString("8"));
array_cars.add(carsdata);
}
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
//Getting Image Location & category
String Location = "";
String Ccategory = "cars";
//Creating parameters
Map<String, String> params = new Hashtable<String, String>();
//Adding parameters
params.put(Category, Ccategory);
params.put(user_Location, Location);
//returning parameters
return params;
}
};
//RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding our request to the queue
// requestQueue.add(request);
AppController.getmInstance().addToRequestQueue(request);
}
public void hideDialog() {
if (dialog != null) {
dialog.dismiss();
dialog = null;
}
}
public interface ClickListener {
void onClick(View view, int position);
void onLongClick(View view, int position);
}
public static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
GestureDetector gestureDetector;
cars.ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final cars.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.getChildPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView recycler, MotionEvent e) {
View child = recycler.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, recycler.getChildPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView recycler, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
}
and finally my adapter class
public class AdapterClass extends RecyclerView.Adapter<AdapterClass.CustomViewHolder> {
private List<CarsItem> Array_cars;
private ImageLoader imageLoader;
private Context mContext;
public AdapterClass(Context context, List<CarsItem> array_cars) {
this.Array_cars = array_cars;
this.mContext = context;
}
#Override
public CustomViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.cars_design, null);
return new CustomViewHolder(view);
}
#Override
public void onBindViewHolder(CustomViewHolder holder,final int i) {
final CarsItem carsItem = Array_cars.get(i);
holder.imageUrl = carsItem.getImages();
imageLoader = AppController.getmInstance().getmImageLoader();
holder.Carname.setText(carsItem.getCarname());
holder.feature1.setText(carsItem.getfeature1());
holder.feature2.setText(carsItem.getfeature2());
holder.feature3.setText(carsItem.getfeature3());
holder.price.setText(carsItem.getPrice());
holder.agent.setText(carsItem.getcarowner());
holder.carid.setText(carsItem.getId());
holder.carimage.setImageUrl("http://192.168.43.201/Car_rental/cars/"+carsItem.getImages(), imageLoader);
holder.rent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext, HireCar.class);
intent.putExtra("carname",carsItem.getCarname());
intent.putExtra("car_rate",carsItem.getPrice());
intent.putExtra("car_image", carsItem.getImages());
intent.putExtra("car_id", carsItem.getId());
intent.putExtra("c_owner", carsItem.getcarowner());
mContext.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return (null != Array_cars ? Array_cars.size() : 0);
}
class CustomViewHolder extends RecyclerView.ViewHolder {
String imageUrl;
TextView Carname, feature1, feature2, feature3, price,agent,carid;
NetworkImageView carimage;
Button rent;
public CustomViewHolder(View view) {
super(view);
this.Carname = (TextView) view.findViewById(R.id.car_name);
this.feature1 = (TextView) view.findViewById(R.id.feature1);
this.feature3 = (TextView) view.findViewById(R.id.feature3);
this.price = (TextView) view.findViewById(R.id.car_price);
this.feature2=(TextView) view.findViewById(R.id.feature2);
this.carimage = (NetworkImageView) view.findViewById(R.id.Car_image);
this.rent=(Button)view.findViewById(R.id.btn_rent);
this.agent=(TextView)view.findViewById(R.id.crAgent);
this.carid=(TextView)view.findViewById(R.id.car_id);
}
}
}
I think the problem is that you are not adding the elements to the adapter. You need to have a method in the adapter to add items after the adapter has been created. Inside that method you need to notify. Example:
void addItems(List<CarItem> carItems){
Array_cars.addAll(carItems);
notifyDataSetChanged();
}
However, I would go a bit far and find the number of items and try to notify only for the newly inserted ones(in case there is something already).
This can be done like this:
void addItems(List<CarItem> carItems){
int position = Array_cars.size();
Array_cars.addAll(carItems);
notifyItemRangeChanged(position, Array_cars.size() - position);
}
EDIT
Look at this example below:
RecycleView
Here is the xml layout for the recyclerview activity
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.aleky.carrental.cars">
<RelativeLayout
android:id="#+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/rv"
android:clickable="false"
/>
</RelativeLayout>
</RelativeLayout>
You have added match_parent height of "RecyclerView" please change to wrap_content.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.aleky.carrental.cars">
<RelativeLayout
android:id="#+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/rv"
android:clickable="false"
/>
</RelativeLayout>
</RelativeLayout>

Why does my RecyclerView contain only 1 item?

I am creating a weather forecast aplication. For this I want to use RecyclerView to show items. The problem is that my RecyclerView is showing only one item instead of all. I am using the OpenWeatherMap API forecast.
This is my layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:background="#drawable/weather_background2"
android:orientation="vertical"
android:padding="5dp">
<TextView
android:id="#+id/txt_close_weather"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_gravity="end"
android:layout_marginRight="2dp"
android:layout_marginTop="2dp"
android:background="#drawable/circle"
android:gravity="center"
android:text="X"
android:textColor="#color/blackTransparent"
android:textStyle="bold" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="8"
android:orientation="vertical">
<TextView
android:id="#+id/city_country_weather"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="0dp"
android:text="KOTA"
android:textColor="#color/blackTransparent"
android:textSize="24dp"
android:textStyle="bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="2dp"
android:text="Today"
android:textColor="#color/blackTransparent"
android:textSize="16dp" />
<TextView
android:id="#+id/current_date_weather"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="4dp"
android:textColor="#color/blackTransparent"
android:textSize="16dp" />
<ImageView
android:id="#+id/weather_icon"
android:layout_width="160dp"
android:layout_height="160dp"
android:layout_gravity="center|center_horizontal"
android:layout_marginTop="8dp"
android:contentDescription="#string/app_name"
android:src="#drawable/img_02d" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="2dp"
android:gravity="center_horizontal"
android:orientation="horizontal"
android:weightSum="3">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="#+id/tv_description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hummidity"
android:textColor="#color/blackTransparent"
android:textSize="14dp"
android:textStyle="bold" />
<TextView
android:id="#+id/wind_result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:text="#string/app_name"
android:textColor="#color/blackTransparent"
android:textSize="14dp" />
<TextView
android:id="#+id/temperature_result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:text="#string/app_name"
android:textColor="#color/blackTransparent"
android:textSize="16dp" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:gravity="center_horizontal"
android:background="#color/whiteTr"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="2.5"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="#+id/weather_daily_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:orientation="horizontal"
android:scrollbars="none" />
</LinearLayout>
</LinearLayout>
This my code in activity :
public class DialogWeather extends android.app.DialogFragment {
public static final int WIDTH = 60;
public static final int HEIGHT = 80;
public static final String DATE_FORMAT_WITHOUT_TIME = "dd/MM";
private static final String ICON_PREFIX = "img_";
private static final String API_KEY = "2fc56d498a3b4d87ba298c232e65e6b0";
private static final String UNITS = "metric";
final String q = "Jakarta";
PopupWindow myPopupWindow;
Dialog myDialog;
DialogWeather dialogWeather;
private TextView txtCloseWeather, txtCityCountry,
txtCurrentDate, tvDescription, tvWindResult, tvTemperatureResult;
private ImageView weatherIcon;
private RecyclerView mRecyclerViewWeather;
DialogWeatherAdapter dialogWeatherAdapter;
private ArrayList<Example2> weathers = new ArrayList<>();
Example2 example2List;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_dialog_weather,
container, false);
getDialog().getWindow().setBackgroundDrawable(new
ColorDrawable(Color.TRANSPARENT));
tvDescription = rootView.findViewById(R.id.tv_description);
tvWindResult = rootView.findViewById(R.id.wind_result);
tvTemperatureResult = rootView.findViewById(R.id.temperature_result);
weatherIcon = rootView.findViewById(R.id.weather_icon);
txtCityCountry = rootView.findViewById(R.id.city_country_weather);
txtCityCountry.setTypeface(Typeface.DEFAULT_BOLD);
txtCurrentDate = rootView.findViewById(R.id.current_date_weather);
txtCloseWeather = rootView.findViewById(R.id.txt_close_weather);
txtCloseWeather.setTypeface(Typeface.DEFAULT_BOLD);
Fragment fragment = this;
txtCloseWeather.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), "Button Close",
Toast.LENGTH_LONG).show();
getActivity().getFragmentManager().beginTransaction()
.remove(fragment).commit();
}
});
mRecyclerViewWeather = rootView.findViewById(R.id.weather_daily_list);
LinearLayoutManager layoutManager = new
LinearLayoutManager(getApplicationContext());
layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
mRecyclerViewWeather.setLayoutManager(layoutManager);
mRecyclerViewWeather.setHasFixedSize(true);
dialogWeatherAdapter = new DialogWeatherAdapter(weathers);
mRecyclerViewWeather.setAdapter(dialogWeatherAdapter);
loadWeathers(q, API_KEY, UNITS);
return rootView;
}
private void loadWeathers(String q, String apiKey, String units) {
ApiServicesWeather weather = InitRetrofitWeather.getServicesWeather();
Call<Example2> exampleCall = weather.getDetailWeather(q, apiKey, units);
exampleCall.enqueue(new Callback<Example2>() {
#Override
public void onResponse(Call<Example2> call, Response<Example2>
response) {
if (response.isSuccessful()) {
Toast.makeText(getApplicationContext(), "Success",
Toast.LENGTH_LONG).show();
example2List = response.body();
weathers.addAll(Collections.singleton(example2List));
loadSetView();
dialogWeatherAdapter.updateList(weathers);
dialogWeatherAdapter.notifyDataSetChanged();
}
}
#Override
public void onFailure(Call<Example2> call, Throwable t) {
Toast.makeText(getApplicationContext(), "Gagal " +
t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
private void loadSetView() {
txtCityCountry.setText(weathers.get(getId()).getCity().getName());
txtCurrentDate.setText(Util.formatDate(weathers
.get(getId()).getList().get(getId()).getDtTxt(), "EEE MMM dd, yyyy"));
weatherIcon.setImageResource(Util
.getDrawableResourceIdByName(getApplicationContext(),ICON_PREFIX + weathers
.get(getId()).getList().get(getId()).getWeather().get(getId()).getIcon()));
tvDescription.setText(weathers.get(getId()).getList().get(getId())
.getWeather().get(getId()).getDescription());
tvWindResult.setText("Wind : " +
weathers.get(getId()).getList().get(getId()).getWind().getSpeed() + " m/s");
double mTemperature = (double)
weathers.get(getId()).getList().get(getId()).getMain().getTemp();
tvTemperatureResult.setText(String.valueOf(weathers
.get(getId()).getList().get(ge
tId()).getMain().getTemp()) + " °C");
}
#Override
public void onResume() {
super.onResume();
ViewGroup.LayoutParams params = getDialog().getWindow().getAttributes();
params.width = 700;
params.height = 1100;
getDialog().getWindow().setAttributes((WindowManager.LayoutParams)
params);
}
this My Adapter :
public class DialogWeatherAdapter extends
RecyclerView.Adapter<DialogWeatherAdapter.DialogViewHolder> {
ArrayList<Example2> data;
Context context;
Activity c;
public DialogWeatherAdapter(ArrayList<Example2> data, Context context,
Activity c) {
this.data = data;
this.context = context;
this.c = c;
}
public DialogWeatherAdapter(ArrayList<Example2> weathers) {
this.data = weathers;
}
#Override
public DialogViewHolder onCreateViewHolder(ViewGroup parent, int
viewType) {
LayoutInflater layoutInflater = (LayoutInflater)
parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.item_weathers, parent,
false);
return new DialogViewHolder(view);
}
#Override
public void onBindViewHolder(DialogViewHolder holder, int position) {
if (holder instanceof DialogViewHolder) {
final DialogViewHolder viewHolder = (DialogViewHolder) holder;
if (data != null) {
for (int i = 0; i < data.size(); i++) {
viewHolder.tvCurrentDateItem.setText(Util.formatDate(data
.get(position).getList()
.get(position).getDtTxt(), "dd/MM"));
viewHolder.ivIconItem.setImageResource(Util
.getDrawableResourceIdByName(getApplicationContext(), ICON_PREFIX + data
.get(getId()).getList().get(getId()).getWeather().get(getId()).getIcon()));
viewHolder.tvDescriptionItem.setText(data.get(position)
.getList().get(position).getWeather().get(position).getDescription());
viewHolder.tvTemperatureItem.setText(String.valueOf(weathers
.get(getId()).getList
().get(getId()).getMain().getTemp()) + " °C");
}
}
}
}
#Override
public int getItemCount() {
return data.size();
}
public void updateList(ArrayList<Example2> weathers) {
this.data = weathers;
}
public class DialogViewHolder extends RecyclerView.ViewHolder {
TextView tvCurrentDateItem, tvDescriptionItem, tvTemperatureItem;
ImageView ivIconItem;
public DialogViewHolder(View itemView) {
super(itemView);
tvCurrentDateItem = itemView.findViewById(R.id.current_date_weather_item);
tvDescriptionItem = itemView.findViewById(R.id.description_item);
tvTemperatureItem = itemView.findViewById(R.id.temperature_item);
ivIconItem = itemView.findViewById(R.id.icon_weather_item);
}
}
}
enter image description here
The reason for this is -
The Item file (R.layout.item_weathers) has height match parent. Change it to wrap_content as shown -
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
and it will show all the items.

How to update imageview from the parent recyclerview after click on nested recyclerview's imageview

Please check following screenshot, I want to update imageview from parent recyclerview when user click on imageview from nested recyclerview.
I have taken two individual adapters for for parent & nested recyclerview.I am not able to do the functionality for updating image, kindly help.
Parent Recyclerview Adapter:
public class RecyclerViewDataAdapter extends RecyclerView.Adapter<RecyclerViewDataAdapter.ItemRowHolder> {
private ArrayList<PLDModel> dataList;
private Context mContext;
public RecyclerViewDataAdapter(Context context, ArrayList<PLDModel> dataList) {
this.dataList = dataList;
this.mContext = context;
}
#Override
public ItemRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_card_view, null);
ItemRowHolder mh = new ItemRowHolder(v);
return mh;
}
#Override
public void onBindViewHolder(ItemRowHolder itemRowHolder, int i) {
final String itemTitle = dataList.get(i).getTitle();
final String itemDescription = dataList.get(i).getDescription();
ArrayList<SmallImages> singleSectionItems = dataList.get(i).getSmallImages();
itemRowHolder.itemTitle.setText(Html.fromHtml("<b>" + itemTitle + " </b> " + itemDescription));
SectionListDataAdapter itemListDataAdapter = new SectionListDataAdapter(mContext, singleSectionItems);
itemRowHolder.recyclerSmallImageList.setHasFixedSize(true);
itemRowHolder.recyclerSmallImageList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
itemRowHolder.recyclerSmallImageList.setAdapter(itemListDataAdapter);
}
#Override
public int getItemCount() {
return (null != dataList ? dataList.size() : 0);
}
public class ItemRowHolder extends RecyclerView.ViewHolder {
protected TextView itemTitle, expandImage;
protected ImageView bookmarkImage,largeImage;
protected RecyclerView recyclerSmallImageList;
protected Button btnMore;
public ItemRowHolder(View view) {
super(view);
this.itemTitle = (TextView) view.findViewById(R.id.title);
this.bookmarkImage = (ImageView) view.findViewById(R.id.bookmark);
this.largeImage = (ImageView) view.findViewById(R.id.large_image);
this.expandImage = (TextView) view.findViewById(R.id.expand);
this.recyclerSmallImageList = (RecyclerView) view.findViewById(R.id.recycler_small_image_list);
}
}
}
Nested Recyclerview Adapter:
public class SectionListDataAdapter extends RecyclerView.Adapter<SectionListDataAdapter.SingleItemRowHolder> {
private ArrayList<SmallImages> itemsList;
private Context mContext;
public SectionListDataAdapter(Context context, ArrayList<SmallImages> itemsList) {
this.itemsList = itemsList;
this.mContext = context;
}
#Override
public SingleItemRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.small_images_view, null);
SingleItemRowHolder mh = new SingleItemRowHolder(v);
return mh;
}
#Override
public void onBindViewHolder(SingleItemRowHolder holder, int i) {
SmallImages singleItem = itemsList.get(i);
}
#Override
public int getItemCount() {
return (null != itemsList ? itemsList.size() : 0);
}
public class SingleItemRowHolder extends RecyclerView.ViewHolder {
protected ImageView itemImage;
public SingleItemRowHolder(View view) {
super(view);
//this.tvTitle = (TextView) view.findViewById(R.id.tvTitle);
this.itemImage = (ImageView) view.findViewById(R.id.item_small_image);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(v.getContext(), tvTitle.getText(), Toast.LENGTH_SHORT).show();
}
});
}
}
}
Using two Recyclerview will be hard to control rather than use a Single adapter and control everything from there.I have just worked on this type of thing that's why I am posting my code there may be some unwanted code which u may need.
/////Adapter class
public class AdapterTodayTrip extends RecyclerView.Adapter<AdapterTodayTrip.VHItem> {
private Context mContext;
private int rowLayout;
private List<ModelRouteDetailsUp> dataMembers;
private ArrayList<ModelRouteDetailsUp> arraylist;
private ArrayList<ModelKidDetailsUp> arraylist_kids;
List<String> wordList = new ArrayList<>();
Random rnd = new Random();
int randomNumberFromArray;
private ModelRouteDetailsUp personaldata;
private ProgressDialog pDialog;
private ConnectionDetector cd;
String img_baseurl = "";
String item = "";
public AdapterTodayTrip(Context mcontext, int rowLayout, List<ModelRouteDetailsUp> tripList, String flag, String img_baseurl) {
this.mContext = mcontext;
this.rowLayout = rowLayout;
this.dataMembers = tripList;
wordList.clear();
this.img_baseurl = img_baseurl;
arraylist = new ArrayList<>();
arraylist_kids = new ArrayList<>();
arraylist.addAll(dataMembers);
cd = new ConnectionDetector(mcontext);
pDialog = KPUtils.initializeProgressDialog(mcontext);
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public AdapterTodayTrip.VHItem onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(rowLayout, viewGroup, false);
return new AdapterTodayTrip.VHItem(v);
}
#Override
public int getItemCount() {
return dataMembers.size();
}
#Override
public void onBindViewHolder(final AdapterTodayTrip.VHItem viewHolder, final int position) {
viewHolder.setIsRecyclable(false);
try {
personaldata = dataMembers.get(position);
if (!KPHashmapUtils.m_ride_route_details_up.get(position).getKidpool_route_id().isEmpty() && !KPHashmapUtils.m_ride_route_details_up.get(position).getKidpool_route_id().equals("null")) {
viewHolder.tv_trip_id.setText("#" + KPHashmapUtils.m_ride_route_details_up.get(position).getKidpool_route_id());
}
****///////inflate the child list here and onclick on the image below in the inflated view it will load the image in the main view****
if (personaldata.getKidlist().size() > 0) {
viewHolder.linear_childview.setVisibility(View.VISIBLE);
viewHolder.tv_total_count.setText(""+personaldata.getKidlist().size());
viewHolder.id_gallery.removeAllViews();
LinearLayout.LayoutParams buttonLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
buttonLayoutParams.setMargins(0, 0, 8, 0);
LayoutInflater layoutInflater = (LayoutInflater) this.mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
for (int i = 0; i < personaldata.getKidlist().size(); i++) {
View view = layoutInflater.inflate(R.layout.view_child_list, null);
view.setLayoutParams(buttonLayoutParams);
RelativeLayout rl_txt = (RelativeLayout)view.findViewById(R.id.rl_txt);
RelativeLayout rl_img = (RelativeLayout)view.findViewById(R.id.rl_img);
TextView tv_count = (TextView)view.findViewById(R.id.tv_count);
com.app.kidpooldriver.helper.CircularTextView tv_name = (com.app.kidpooldriver.helper.CircularTextView)view.findViewById(R.id.tv_name);
final CircleImageView iv_circular = (CircleImageView)view.findViewById(R.id.iv_circular);
int count = i + 1;
String count1 = "0";
if (count <= 10) {
count1 = "0" + count;
}
tv_count.setText(String.valueOf(count1));
viewHolder.id_gallery.addView(view);
final String baseurl = img_baseurl + "" + personaldata.getKidlist().get(i).getKid_image();
**/////set the url of the small image in the tag here**
if(!baseurl.isEmpty()) {
iv_circular.setTag(baseurl);
}
if (!personaldata.getKidlist().get(i).getKid_image().isEmpty()) {
GradientDrawable bgShape = (GradientDrawable) rl_img.getBackground();
bgShape.setColor(Color.parseColor("#A6b1a7a6"));
rl_txt.setVisibility(View.GONE);
//rl_img.setVisibility(View.VISIBLE);
tv_name.setVisibility(View.GONE);
Log.d("aimg_baseurl", baseurl);
try {
Picasso.with(mContext)
.load(baseurl)
.resize(60,60)
.centerCrop()
.into(iv_circular);
iv_circular.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String url=iv_circular.getTag().toString().trim();
if(!url.isEmpty())
KPUtils.showToastShort(mContext,url);
Picasso.with(mContext)
.load(url)
.resize(60,60)
.centerCrop()
.into(viewHolder.img_child);
}
});
} catch (Exception e) {
}
} else {
}
}
}else{
viewHolder.linear_childview.setVisibility(View.GONE);
}
} catch (Exception e) {
e.printStackTrace();
}
}
class VHItem extends RecyclerView.ViewHolder {
CardView cv_members;
ImageView img_child;
TextView tv_trip_id, tv_trip_status, tv_vehicle_number, tv_trip_start_time, tv_trip_end_time, tv_trip_way, tv_total_count;
LinearLayout id_gallery,linear_childview;
public VHItem(View itemView) {
super(itemView);
img_child= (ImageView) itemView.findViewById(R.id.img_child);
cv_members = (CardView) itemView.findViewById(R.id.cv_members);
tv_trip_id = (TextView) itemView.findViewById(R.id.tv_trip_id);
tv_trip_status = (TextView) itemView.findViewById(R.id.tv_trip_status);
tv_vehicle_number = (TextView) itemView.findViewById(R.id.tv_vehicle_number);
tv_trip_start_time = (TextView) itemView.findViewById(R.id.tv_trip_start_time);
tv_trip_end_time = (TextView) itemView.findViewById(R.id.tv_trip_end_time);
tv_trip_way = (TextView) itemView.findViewById(R.id.tv_trip_way);
tv_total_count = (TextView) itemView.findViewById(R.id.tv_total_count);
id_gallery = (LinearLayout) itemView.findViewById(R.id.id_gallery);
linear_childview= (LinearLayout) itemView.findViewById(R.id.linear_childview);
}
}
}
/////////////////////////// this layout is inflated in every row
view_child_list
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/iv_circular"
android:layout_width="60dp"
android:layout_height="60dp"
android:src="#mipmap/ic_launcher"
app:civ_border_color="#d27959"
app:civ_border_width="1dp" />
<RelativeLayout
android:id="#+id/rl_txt"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_gravity="center"
android:background="#drawable/gy_ring_circular"
android:gravity="center"
android:visibility="gone">
<com.app.kidpooldriver.helper.CircularTextView
android:id="#+id/tv_name"
fontPath="fonts/Poppins-Bold.ttf"
android:layout_width="70dp"
android:layout_height="70dp"
android:gravity="center"
android:text="01"
android:textColor="#color/white"
android:textSize="35sp"
tools:ignore="MissingPrefix" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/rl_img"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_gravity="center"
android:background="#drawable/gy_ring_circular"
android:gravity="center"
android:visibility="visible">
<TextView
android:id="#+id/tv_count"
fontPath="fonts/Poppins-Bold.ttf"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="01"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Medium"
android:textColor="#ffffff"
android:textStyle="bold"
tools:ignore="MissingPrefix" />
</RelativeLayout>
</FrameLayout>
///// this is the mianlayout which is inflated.
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/cv_members"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="#dimen/card_margin"
android:elevation="#dimen/elevation"
card_view:cardCornerRadius="5dp">
<LinearLayout
android:id="#+id/main_body"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone"
android:layout_marginTop="#dimen/fifteen"
android:orientation="horizontal"
android:paddingLeft="#dimen/ten">
<TextView
android:id="#+id/tv_trip_id"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#KD09201701"
android:textColor="#color/colorPrimary"
android:textSize="#dimen/twenty"
android:textStyle="bold" />
<TextView
android:id="#+id/tv_trip_status"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/light_green"
android:gravity="center"
android:padding="5dp"
android:text="In Progress"
android:textAppearance="#style/TextAppearance.AppCompat.Small"
android:textColor="#color/black" />
</LinearLayout>
<TextView
android:id="#+id/tv_vehicle_number"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="20dp"
android:text="Route 26U-26D"
android:visibility="gone"
android:textAppearance="#style/TextAppearance.AppCompat.Small"
android:textColor="#color/route_textcolor" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:orientation="horizontal">
<TextView
android:id="#+id/tv_trip_start_time"
android:layout_width="match_parent"
android:visibility="gone"
android:layout_height="match_parent"
android:layout_marginTop="#dimen/five"
android:paddingLeft="20dp"
android:text="06:30am"
android:textAppearance="#style/TextAppearance.AppCompat.Medium"
android:textColor="#color/grey_textcolor" />
<TextView
android:id="#+id/tv_trip_end_time"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="#dimen/five"
android:paddingLeft="20dp"
android:text="08:30am"
android:textAppearance="#style/TextAppearance.AppCompat.Medium"
android:textColor="#color/grey_textcolor"
android:visibility="gone" />
</LinearLayout>
<TextView
android:id="#+id/tv_trip_way"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="#dimen/five"
android:paddingLeft="20dp"
android:visibility="gone"
android:paddingRight="20dp"
android:text="Chingrighata > NiccoPark > SDF > College More > DLF 1 > Eco Space"
android:textAppearance="#style/TextAppearance.AppCompat.Small"
android:textColor="#color/grey_textcolor"
android:textStyle="normal" />
<ImageView
android:id="#+id/img_child"
android:layout_width="200dp"
android:layout_gravity="center"
android:layout_height="200dp" />
<LinearLayout
android:id="#+id/linear_childview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="#dimen/fifteen"
android:orientation="horizontal">
<HorizontalScrollView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_gravity="center_vertical"
android:layout_weight="1"
android:scrollbars="none">
<LinearLayout
android:id="#+id/id_gallery"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:orientation="horizontal" />
</HorizontalScrollView>
<LinearLayout
android:layout_width="70dp"
android:layout_height="70dp"
android:background="#drawable/ly_ring_circular"
android:gravity="center_vertical">
<TextView
android:id="#+id/tv_total_count"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
tools:ignore="MissingPrefix"
fontPath="fonts/Poppins-Bold.ttf"
android:text="+20"
android:textAppearance="#style/TextAppearance.AppCompat.Medium"
android:textColor="#color/white"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
/////POJO CLASS &json parsing & Adapter /////
public class ModelRouteDetailsUp {
String city_id;
String area_name;
String area_status;
String is_active;
String areas;
private ArrayList<ModelKidDetailsUp> kidlist;
///////this is the kid list
public ArrayList<ModelKidDetailsUp> getKidlist() {
return kidlist;
}
public void setKidlist(ArrayList<ModelKidDetailsUp> kidlist) {
this.kidlist = kidlist;
}
}
**///json parsing.......**
public boolean addRideDetails(JSONObject jsonObject) {
Boolean flag = false;
String isstatus = "";
if (jsonObject != null && jsonObject.length() > 0) {
try {
JSONArray mainArray = jsonObject.getJSONArray("schedules");
for (int i = 0; i < mainArray.length(); i++) {
ModelRouteDetailsUp modelRouteDetails = new ModelRouteDetailsUp();
JSONObject c = mainArray.getJSONObject(i);
////// For Route Details //////
JSONObject route_details = c.getJSONObject("route_details");
modelRouteDetails.setDs_id(route_details.optString("ds_id"));
modelRouteDetails.setDriver_id(route_details.optString("driver_id"));
modelRouteDetails.setTrip_id(route_details.optString("trip_id"));
modelRouteDetails.setRoute_id(route_details.optString("route_id"));
modelRouteDetails.setVehicle_id(route_details.optString("vehicle_id"));
modelRouteDetails.setStart_time(route_details.optString("start_time"));
modelRouteDetails.setEnd_time(route_details.optString("end_time"));
////// For Allotted Kids //////
JSONArray kidArray = c.getJSONArray("alloted_kids");
ArrayList<ModelKidDetailsUp> genre = new ArrayList<ModelKidDetailsUp>();
if (kidArray.length() > 0) {
for (int j = 0; j < kidArray.length(); j++) {
ModelKidDetailsUp kidDetailsUp = new ModelKidDetailsUp();
JSONObject kidObject = kidArray.getJSONObject(j);
kidDetailsUp.setKid_name(kidObject.getString("kid_name"));
kidDetailsUp.setKid_gender(kidObject.getString("kid_gender"));
kidDetailsUp.setKid_dob(kidObject.getString("kid_dob"));
kidDetailsUp.setKid_image(kidObject.getString("kid_image"));
genre.add(kidDetailsUp);
}
}
///////add the kidlist here
modelRouteDetails.setKidlist(genre);
////main array contains all the data i.e route details and kidlist for every row
KPHashmapUtils.m_ride_route_details_up.add(modelRouteDetails);
//}
}
} catch (Exception e) {
e.printStackTrace();
}
}
return flag;
}
**/////adapter callfrom class**
private void showData() {
if (KPHashmapUtils.m_ride_route_details_up.size() > 0){
adapterTodayTrip = new AdapterTodayTrip(mContext, R.layout.list_item_todaytrip, KPHashmapUtils.m_ride_route_details_up, "TodayTrip",img_baseurl);
rv_trip_list.setAdapter(adapterTodayTrip);
}else {
tv_msg.setVisibility(View.VISIBLE);
}
}
Generally, the solution is to pass custom interface listener into the nested adapter and than the nested adapter will report any time one of his item clicked.
1.
You can create interface like:
public interface INestedClicked {
onNestedItemClicked(Drawable drawble)
}
2.
Pass in the constructor of SectionListDataAdapter a INestedClicked:
SectionListDataAdapter itemListDataAdapter = newSectionListDataAdapter(mContext, singleSectionItems, new INestedClicked() {
#Override
void onNestedItemClicked(Drawable drawble) {
// Do whatever you need after the click, you get the drawable here
}
});
In the constructor of SectionListDataAdapter save the instance of the listener as adapter parameter
private INestedClicked listener;
4.
When nested item clicked report the listener:
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(listener != null){
listener.onNestedItemClicked(imageView.getDrawable());
}
}

Listview not displaying below RelativeLayout

ListView is not showing, any assistance is greatly appreciated! I am able to display products with ListView alone but I cannot figure out how to display it below my Relative Layout.
Cart.java:
public class Cart extends AppCompatActivity {
private String user;
static CartChangeListener cartChangeListener;
ProductsAdapter adaptCart;
ArrayList<Product> cartItems = new ArrayList<>();
Menu menu;
float total = (float)0.00;
float shipCost = 15;
float tax = (float)0.07;
String URI;
TextView subTotal;
TextView shipping;
TextView taxes;
TextView totals;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
View header = getLayoutInflater().inflate(R.layout.activity_cart, null);
//ListView.addHeaderView(headerView);
user = MainActivity.currentAccount.getUsername();
if(user == null || user.equals("Guest")) {
shipCost = (float)0.00;
tax = (float)0.00;
}
if(user != null && !(user.equals("Guest"))) {
new getCartIcon().execute();
//View header = getLayoutInflater().inflate(R.layout.activity_cart, null);
//View footer = getLayoutInflater().inflate(R.layout.activity_search, null);
ListView listView = (ListView) findViewById(R.id.list_cart_view);
new returnCartItems().execute();
//if (!(cartItems.isEmpty())) {
adaptCart = new ProductsAdapter(Cart.this, 0, cartItems);
listView.setOnItemClickListener(new ListView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
try {
ProductsAdapter.ViewHolder holder = new ProductsAdapter.ViewHolder();
holder.product_name = (TextView) v.findViewById(R.id.product_name);
holder.product_dept = (TextView) v.findViewById(R.id.product_dept);
holder.product_desc = (TextView) v.findViewById(R.id.product_desc);
holder.product_price = (TextView) v.findViewById(R.id.product_price);
holder.product_qty = (TextView) v.findViewById(R.id.product_qty);
holder.product_img = (ImageView) findViewById(R.id.icon);
URI = "http://www.michaelscray.com/Softwear/graphics/";
String dept = "Dept: ";
String money = "$";
String qty = "Qty: ";
URI += cartItems.get(position).getProduct_img();
Uri uris = Uri.parse(URI + cartItems.get(position).getProduct_img());
URI uri = java.net.URI.create(URI);
holder.product_name.setText(cartItems.get(position).getProduct_name());
holder.product_desc.setText(cartItems.get(position).getProduct_desc());
holder.product_dept.setText(dept + cartItems.get(position).getProduct_dept());
holder.product_price.setText(money + String.valueOf(cartItems.get(position).getPrice()));
holder.product_qty.setText(qty + String.valueOf(cartItems.get(position).getProduct_qty()));
Picasso.with(getApplicationContext()).load(URI).error(R.mipmap.ic_launcher).into(holder.product_img);
} catch (Exception e) {
e.printStackTrace();
}
}
});
listView.setAdapter(adaptCart);
//}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.menu_main, menu);
this.menu = menu;
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
return true;
}
public class getCartIcon extends AsyncTask<Void, Void, Void> {
String tempUser = user;
int cartNum = 0;
float tempTotal;
#Override
protected void onPreExecute() {
subTotal = (TextView) findViewById(R.id.textView_subTotal);
shipping = (TextView) findViewById(R.id.textView_shipping);
totals = (TextView) findViewById(R.id.textView_total);
taxes = (TextView) findViewById(R.id.textView_taxes);
}
#Override
protected Void doInBackground(Void... arg0) {
if(tempUser != null) {
try {
Connection conn = ConnectDB.getConnection();
String queryString = "SELECT * FROM Orders WHERE `User_Name` = '" + tempUser + "'";
PreparedStatement st = conn.prepareStatement(queryString);
//st.setString(1, tempUser);
final ResultSet result = st.executeQuery(queryString);
while (result.next()) {
try {
tempTotal += result.getFloat("Price");
//skus.add(result.getInt("SKU"));
} catch(SQLException e) {
e.printStackTrace();
}
cartNum++;
//setTotal(result.getFloat(String.valueOf("Price")));
}
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
protected void onPostExecute(Void result) {
getCartItems(cartNum);
subTotal.setText(String.valueOf(tempTotal));
shipping.setText(String.valueOf(shipCost));
tax = tempTotal * tax;
taxes.setText(String.valueOf(tax));
totals.setText(String.valueOf(tempTotal + shipCost + tax));
//setTotal(tempTotal);
//super.onPostExecute(result);
}
}
public class returnCartItems extends AsyncTask<Void, Void, Void> {
String tempUser = user;
Product product = null;
List<Integer> skus = new ArrayList<>();
//String descr = "DETAILS: \n\n";
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... arg0) {
if(tempUser != null) {
try {
Connection conn = ConnectDB.getConnection();
String queryString = "SELECT * FROM Orders WHERE `User_Name` = '" + tempUser + "'";
PreparedStatement st = conn.prepareStatement(queryString);
//st.setString(1, tempUser);
final ResultSet result = st.executeQuery(queryString);
while (result.next()) {
try {
skus.add(result.getInt("SKU"));
} catch(SQLException e) {
e.printStackTrace();
}
}
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
Connection conn = ConnectDB.getConnection();
String queryString = "SELECT * FROM Inventory";
PreparedStatement st = conn.prepareStatement(queryString);
//st.setString(1, tempUser);
final ResultSet result = st.executeQuery(queryString);
while (result.next()) {
for(int i=0; i < skus.size(); i++) {
if(skus.get(i) == result.getInt("SKU")) {
product = new Product();
product.setProduct_name(result.getString("Name"));
product.setProduct_dept(result.getString("Department"));
product.setProduct_desc(result.getString("Description"));
product.setPrice(result.getFloat("Price"));
product.setProduct_qty(result.getInt("Quantity"));
product.setProduct_img(result.getString("Image"));
cartItems.add(product);
/*
descr += "Product: " + result.getString("Name") + "\n" +
"Department: " + result.getString("Department") + "\n" +
"Price: $" + result.getFloat("Price") + "\n\n";
*/
}
}
}
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
public void setTotal(float total) {
this.total += total;
}
public float getTotal() {
return total;
}
public void getCartItems(int cart) {
MenuItem cartMenuItem = (MenuItem) menu.findItem(R.id.action_cart);
if (cart == 0) {
cartMenuItem.setIcon(R.drawable.cart0);
}
if (cart == 1) {
cartMenuItem.setIcon(R.drawable.cart1);
}
if (cart == 2) {
cartMenuItem.setIcon(R.drawable.cart2);
}
if (cart == 3) {
cartMenuItem.setIcon(R.drawable.cart3);
}
if (cart == 4) {
cartMenuItem.setIcon(R.drawable.cart4);
}
if (cart == 5) {
cartMenuItem.setIcon(R.drawable.cart5);
}
if (cart > 5) {
cartMenuItem.setIcon(R.drawable.cart5plus);
}
if (cart > 10) {
cartMenuItem.setIcon(R.drawable.cart10plus);
}
}
}
ProductsAdapter.java:
public class ProductsAdapter extends ArrayAdapter<Product> {
private Activity activity;
private ArrayList<Product> products;
private static LayoutInflater inflater = null;
String money = "$";
String dept = "Dept: ";
String qty ="Qty: ";
static String URI;
public ProductsAdapter(Activity activity, int textViewResourceId, ArrayList<Product> product) {
super(activity, textViewResourceId, product);
try {
this.activity = activity;
this.products = product;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//imageLoader = new ImageLoader(activity.getApplicationActivity());
} catch (Exception e) {
return;
}
}
#Override
public int getCount() {
return products.size();
}
public Product getItem(Product position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
public static class ViewHolder {
public TextView product_name;
public TextView product_desc;
public TextView product_dept;
public TextView product_price;
public TextView product_qty;
public ImageView product_img;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
final ViewHolder holder;
try {
if(convertView == null) {
vi = inflater.inflate(R.layout.activity_search, parent, false);
holder = new ViewHolder();
holder.product_name = (TextView) vi.findViewById(R.id.product_name);
holder.product_dept = (TextView) vi.findViewById(R.id.product_dept);
holder.product_desc = (TextView) vi.findViewById(R.id.product_desc);
holder.product_price = (TextView) vi.findViewById(R.id.product_price);
holder.product_qty = (TextView) vi.findViewById(R.id.product_qty);
holder.product_img = (ImageView) vi.findViewById(R.id.icon);
vi.setTag(holder);
}
else {
holder = (ViewHolder) vi.getTag();
}
URI = "http://www.michaelscray.com/Softwear/graphics/";
URI += products.get(position).getProduct_img();
Uri uri = Uri.parse(URI + products.get(position).getProduct_img());
holder.product_name.setText(products.get(position).getProduct_name());
holder.product_desc.setText(products.get(position).getProduct_desc());
holder.product_dept.setText(dept + products.get(position).getProduct_dept());
holder.product_price.setText(money + String.valueOf(products.get(position).getPrice()));
holder.product_qty.setText(qty + String.valueOf(products.get(position).getProduct_qty()));
Picasso.with(getContext()).load(URI).error(R.mipmap.ic_launcher).into(holder.product_img);
}
catch(Exception e) {
}
return vi;
}
}
And, activity_cart.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/llSliderCart"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#5e80ab"
android:orientation="vertical" >
<TextView
android:id="#+id/summary"
android:layout_width="254dp"
android:layout_height="55dp"
android:gravity="center"
android:text="CART SUMMARY"
android:textColor="#ffffff"
android:textSize="18sp"
android:textStyle="bold"
android:layout_alignParentStart="true"
android:layout_toStartOf="#+id/checkout_btn" />
<Button
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:text="Checkout"
android:id="#+id/checkout_btn"
android:background="#drawable/shape"
android:layout_alignParentBottom="false"
android:layout_alignParentEnd="false"
android:layout_alignParentRight="true"
android:paddingLeft="1dp"
android:paddingTop="1dp"
android:paddingRight="1dp"
android:paddingBottom="1dp"
android:textStyle="bold"
android:textColor="#ffffff" />
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="#dimen/cart_rows"
android:background="#ffffff"
android:orientation="horizontal" >
<TextView
android:layout_width="120dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:gravity="right"
android:paddingRight="20dp"
android:text="Subtotal"
android:textColor="#a4a4a4"
android:textSize="#dimen/text_normal" />
<View
android:layout_width="1dp"
android:layout_height="match_parent"
android:background="#color/vertical_divider_welcome" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:gravity="right"
android:paddingLeft="20dp"
android:text="#string/currency"
android:textColor="#a4a4a4"
android:textSize="#dimen/text_normal" />
<TextView
android:id="#+id/textView_subTotal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:gravity="right"
android:paddingRight="20dp"
android:text="0.00"
android:textColor="#a4a4a4"
android:textSize="#dimen/text_normal" />
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/vertical_divider_welcome" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="#dimen/cart_rows"
android:background="#ffffff"
android:orientation="horizontal" >
<TextView
android:layout_width="120dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:gravity="right"
android:paddingRight="20dp"
android:text="Shipping"
android:textColor="#a4a4a4"
android:textSize="#dimen/text_normal" />
<View
android:layout_width="1dp"
android:layout_height="match_parent"
android:background="#color/vertical_divider_welcome" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:gravity="right"
android:paddingLeft="20dp"
android:text="#string/currency"
android:textColor="#a4a4a4"
android:textSize="#dimen/text_normal" />
<TextView
android:id="#+id/textView_shipping"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:gravity="right"
android:paddingRight="20dp"
android:text="0.00"
android:textColor="#a4a4a4"
android:textSize="#dimen/text_normal" />
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/vertical_divider_welcome" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="#dimen/cart_rows"
android:background="#ffffff"
android:orientation="horizontal" >
<TextView
android:layout_width="120dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:gravity="right"
android:paddingRight="20dp"
android:text="Tax"
android:textColor="#a4a4a4"
android:textSize="#dimen/text_normal" />
<View
android:layout_width="1dp"
android:layout_height="match_parent"
android:background="#color/vertical_divider_welcome" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:gravity="right"
android:paddingLeft="20dp"
android:text="#string/currency"
android:textColor="#a4a4a4"
android:textSize="#dimen/text_normal" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:gravity="right"
android:paddingRight="20dp"
android:text="0"
android:textColor="#a4a4a4"
android:textSize="#dimen/text_normal"
android:id="#+id/textView_taxes" />
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/vertical_divider_welcome" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="#dimen/cart_rows"
android:background="#ffffff"
android:orientation="horizontal" >
<TextView
android:layout_width="120dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:gravity="right"
android:paddingRight="20dp"
android:text="Total"
android:textStyle="bold"
android:textColor="#color/blue"
android:textSize="#dimen/text_title" />
<View
android:layout_width="1dp"
android:layout_height="match_parent"
android:background="#color/vertical_divider_welcome" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:gravity="right"
android:paddingLeft="20dp"
android:text="#string/currency"
android:textStyle="bold"
android:textColor="#color/blue"
android:textSize="#dimen/text_title" />
<TextView
android:id="#+id/textView_total"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:gravity="right"
android:textStyle="bold"
android:paddingRight="20dp"
android:text="0.00"
android:textColor="#color/blue"
android:textSize="#dimen/text_title" />
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/vertical_divider_welcome" />
<!--
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Description"
android:id="#+id/textView" />
-->
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Cart contents:"
android:id="#+id/contents"
android:background="#color/vertical_divider_welcome"
android:textStyle="bold|italic"
android:layout_alignParentEnd="false"
android:layout_alignParentStart="false" />
</RelativeLayout>
<ListView
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="vertical"
android:id="#+id/list_cart_view">
</ListView>
</LinearLayout>
Thanks again!
While your RelativeLayout(the one just before the ListView) have match_parent as height, it will take the remaining space of the window... so there is no place for your ListView to be shown.
Try this..
Give id to the above Relative layout and use the same below.
<ListView
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="vertical"
android:layout_below="#id/"
android:id="#+id/list_cart_view">
</ListView>

Item missing from android grid view on scroll

I have grid view , on which each item consists of few images and text . When it loads for the first time , everything is fine but if I scroll to the bottom and the go back to top some two images are gone from a item , and it goes randomly .
here is the code for Grid view
<GridView
android:id="#+id/testR_grid"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:clickable="true"
android:columnWidth="#dimen/gridview_column_width"
android:horizontalSpacing="#dimen/grid_horizontal_spacing"
android:listSelector="#drawable/gridview_background"
android:numColumns="auto_fit"
android:scrollbarStyle="outsideOverlay"
android:scrollbars="vertical"
android:verticalScrollbarPosition="right"
android:verticalSpacing="#dimen/grid_vertical_spacing"
android:fastScrollEnabled="false"/>
Here the code for single item
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="250dp"
android:layout_marginTop="5dp"
android:descendantFocusability="blocksDescendants"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/blurry_shadow_rect">
<com.joooonho.SelectableRoundedImageView xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/item_image"
android:layout_width="match_parent"
android:layout_height="#dimen/gridview_column_width"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="5dp"
android:layout_marginTop="-5dp"
app:sriv_left_bottom_corner_radius="0dip"
app:sriv_left_top_corner_radius="4dip"
app:sriv_right_bottom_corner_radius="0dip"
app:sriv_right_top_corner_radius="4dip" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/item_image"
android:layout_marginBottom="5dp"
android:layout_marginLeft="2dp"
android:orientation="horizontal"
android:weightSum="100">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="35">
<TextView
android:id="#+id/item_text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_gravity="start"
android:layout_marginBottom="5dp"
android:ellipsize="end"
android:fontFamily="sans-serif-light"
android:maxLines="1"
android:text=""
android:textColor="#color/bodyText"
android:textSize="#dimen/GridHeader" />
<TextView
android:id="#+id/item_TestA_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/item_text"
android:layout_marginBottom="10dp"
android:alpha=".5"
android:ellipsize="end"
android:maxLines="1"
android:text=""
android:textColor="#color/bodyText"
android:textSize="#dimen/GridHeader2" />
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="2dp"
android:layout_weight="65">
<TextView
android:id="#+id/item_testR_free_text"
style="#style/textview_grid_free_banner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:fontFamily="sans-serif-light"
android:maxLines="1"
android:padding="2dp"
android:singleLine="true"
android:text=" FREE " />
<ImageView
android:layout_width="20dp"
android:layout_height="20dp"
android:id="#+id/already_owned"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:singleLine="true"
android:layout_marginLeft="20dp"
android:layout_marginBottom="5dp"
android:visibility="gone"
android:layout_marginEnd="10dp"
android:layout_marginRight="10dp"
android:src="#drawable/ic_testR_bought_36dp" />
<ImageButton
android:id="#+id/item_testR_more_options"
android:layout_width="#dimen/image_button_more"
android:layout_height="#dimen/image_button_more"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/item_testR_free_text"
android:alpha=".5"
android:background="#drawable/imagebutton_background"
android:clickable="true"
android:focusable="false"
android:src="#drawable/ic_more_vert_black_24dp" />
</RelativeLayout>
</LinearLayout>
</RelativeLayout>
</RelativeLayout>
The elements are randomly missing are text view which id is item_testR_free_text and imageview which id is already_owned . One thing also to be noted the visibility of these two items are conditional .
Here is my code for adapter
public class TestRGridViewAdapter extends ArrayAdapter<TestR> {
Context context;
int layoutResourceId;
List<TestR> data = new ArrayList<TestR>();
RecordHolder holder = null;
//DiskCache imgCache;
TestA TestA;
TestR item;
FragmentActivity mFragmentActivity;
boolean is_local = false;
List<Track> trackList;
public TestR getItem() {
return item;
}
public void setItem(TestR item) {
this.item = item;
}
public TestRGridViewAdapter(Context context, int layoutResourceId,
List<TestR> data, FragmentActivity mFragmentActivity, boolean is_local) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
this.mFragmentActivity = mFragmentActivity;
// imgCache = Parameters.imgCache;
this.is_local = is_local;
}
public TestRGridViewAdapter(Context context, int layoutResourceId,
List<TestR> data, FragmentActivity mFragmentActivity) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
this.mFragmentActivity = mFragmentActivity;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
//LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = LayoutInflater.from(context).inflate(layoutResourceId, null);
//row = inflater.inflate(layoutResourceId, parent, false);
holder = new RecordHolder();
holder.item_testR_free_text = (TextView) row.findViewById(R.id.item_testR_free_text);
holder.txtTitle = (TextView) row.findViewById(R.id.item_text);
holder.txtTestAName = (TextView) row.findViewById(R.id.item_TestA_name);
holder.imageItem = (SelectableRoundedImageView) row.findViewById(R.id.item_image);
holder.item_testR_more_options = (ImageButton) row.findViewById(R.id.item_testR_more_options);
holder.already_owned = (ImageView) row.findViewById(R.id.already_owned);
// holder.grid_swipe_refresh_layout = (SwipeRefreshLayout) row.findViewById(R.id.grid_swipe_refresh_layout);
row.setTag(holder);
} else {
holder = (RecordHolder) row.getTag();
}
item = data.get(position);
holder.txtTitle.setText(item.getName());
// else
// holder.txtArtitName.setText("");
//holder.imageItem.setImageBitmap(item.getImage());
try {
if (item.getTestA_id() == null)
item = new SaveData(context).get_online_testR(item.getTestR_id());
TestA = Helper.getDaoSession(context).getTestADao().load(item.getTestA_id());
if (TestA == null) {
TestA = new SaveData(context).get_save_TestA(item.getTestA_id());
}
// if (TestA != null)
holder.txtTestAName.setText((TestA != null) ? TestA.getName() : "");
// else
// TestA = new SaveData(context).get_save_TestA(item.getTestA_id());
if (!is_local) {
if(!DBQuery.is_owner(context,item.getTestR_id())) {
Log.d("test","not owner - "+item.getName());
holder.item_testR_free_text.setText(
UXHelper.getPriceFromString(Parameters.price_type.equals("local_price") ?
item.getLocal_price().toString() : item.getPrice().toString()));
holder.already_owned.setVisibility(View.INVISIBLE);
holder.item_testR_more_options.setOnClickListener(new testR_popup_onClick(context, item, holder.item_testR_more_options, mFragmentActivity, TestA));
}else {
Log.d("test","owner - "+item.getName());
holder.item_testR_free_text.setVisibility(View.INVISIBLE);
holder.already_owned.setVisibility(View.VISIBLE);
holder.item_testR_more_options.setOnClickListener(new testR_popup_onClick(context, item, holder.item_testR_more_options, mFragmentActivity, TestA));
}
} else {
Log.d("test","local - "+item.getName());
holder.already_owned.setVisibility(View.INVISIBLE);
boolean synced = true;
trackList = new ArrayList<Track>();
List<Track> trackListTmp = new SaveData(context).get_tracks_local(item.getTestR_id());
boolean testR_owner = DBQuery.is_owner(context, trackListTmp.get(0).getTestR_id());
for (Track t : trackListTmp) {
boolean track_owner = DBQuery.is_owner(context, t.getTrack_id(), t.getTestR_id());
if (track_owner)
trackList.add(t);
if (testR_owner || track_owner) {
if (t.getSynced_dir() == null) {
synced = false;
// break;
} else if (!new File(t.getSynced_dir()).exists()) {
synced = false;
// break;
}
}
}
if (synced) {
Log.d("test","synched - "+item.getName());
holder.item_testR_free_text.setVisibility(View.VISIBLE);
holder.item_testR_free_text.setText("Synced");
} else {
Log.d("test","not synched - "+item.getName());
holder.item_testR_free_text.setVisibility(View.INVISIBLE);
holder.item_testR_more_options.setOnClickListener(
new testR_popup_downloaded_onCLick(context, item, holder.item_testR_more_options, mFragmentActivity, TestA,
trackList.toArray(new Track[trackList.size()]), synced));
}
}
Target target = new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
holder.imageItem.setImageBitmap(bitmap);
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
holder.imageItem.setImageResource(R.drawable.ic_example_36);
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
holder.imageItem.setImageResource(R.drawable.ic_example_36);
}
};
if (Parameters.mPicasso == null)
Parameters.mPicasso = new Picasso.Builder(context)
.build();
Parameters.mPicasso.load("http://" + context.getString(R.string.ip) + "/" +
context.getString(R.string.TestRsController) + "/" + context.getString(R.string.TESTR_THUMB_URL)
+ "/" + item.getTestR_id()+"/"+Parameters.dpi)
.placeholder(R.drawable.ic_example_36)
.error(R.drawable.ic_example_36)
.into(holder.imageItem);
} catch (Exception ex) {
new Logger(context).appendLog("Error in TestR grid view item " + ex.getMessage());
}
return row;
}
static class RecordHolder {
// SwipeRefreshLayout grid_swipe_refresh_layout;
TextView txtTitle;
TextView txtTestAName;
SelectableRoundedImageView imageItem;
TextView item_testR_free_text;
ImageButton item_testR_more_options;
ImageView already_owned;
}
}

Categories

Resources