Gridview scrolling images not working smoothly in android - android

Hi in the below displaying all the images into gridview.gridview images displaying correctly.default gridview will give scroll option,Now Scrolling images it's not scrolling smoothly.
Can any one help me .how to scroll smoothly all the images like normal scrolling.this is my below code any where i did mistake please help me
java
public class GridFragment2 extends Fragment {
private static final String TAG = GridFragment.class.getSimpleName();
public static boolean isSelectedGrid2;
private GridView mGridView;
private ProgressBar mProgressBar;
private GridViewAdapter2 mGridAdapter;
private ArrayList<GridItem> mGridData;
private String FEED_URL = "http://javatechig.com/?json=get_recent_posts&count=45", searchKey;
String vv;
LinearLayout top;
View hr;
String catid;
SharedPreferences imgSh;
SharedPreferences p, got;
public GridFragment2() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_gridview2, container, false);
mGridView = (GridView)rootView.findViewById(R.id.gridView);
mProgressBar = (ProgressBar)rootView.findViewById(R.id.progressBar);
top = (LinearLayout)rootView.findViewById(R.id.top);
hr = rootView.findViewById(R.id.hr);
top.setVisibility(View.GONE);
hr.setVisibility(View.GONE);
imgSh = this.getActivity().getSharedPreferences("data", Context.MODE_APPEND);
p = this.getActivity().getSharedPreferences("gridData", Context.MODE_APPEND);
got = this.getActivity().getSharedPreferences("gotData", Context.MODE_APPEND);
//Initialize with empty data
mGridData = new ArrayList<>();
mGridAdapter = new GridViewAdapter2(rootView.getContext(), R.layout.grid_item_layout2, mGridData);
mGridView.setAdapter(mGridAdapter);
//Grid view click event
mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
//Get item at position
isSelectedGrid2=true;
String catalogueID = p.getString("SelectedCatalogueIdFromGrid1", "");
GridItem item = (GridItem) parent.getItemAtPosition(position);
Intent intent = new Intent(getActivity(), ImageGallery.class);
ImageView imageView = (ImageView) v.findViewById(R.id.grid_item_image);
int[] screenLocation = new int[2];
imageView.getLocationOnScreen(screenLocation);
SharedPreferences prefPosition=getActivity().getSharedPreferences("positionPref", Context.MODE_PRIVATE);
SharedPreferences.Editor positionEditor=prefPosition.edit();
positionEditor.putInt("position", position);
positionEditor.commit();
//Pass the image title and url to DetailsActivity
intent.putExtra("left", screenLocation[0]).
putExtra("top", screenLocation[1]).
putExtra("width", imageView.getWidth()).
putExtra("height", imageView.getHeight()).
putExtra("title", item.getTitle()).
putExtra("image", item.getImage()).
putExtra("catid", catalogueID).putExtra("position",position);
// Log.d("image", (item.getImage()).toString());
//Start details activity
getActivity().finish();
startActivity(intent);
}
});
//Start download
new AsyncHttpTask().execute(FEED_URL);
mProgressBar.setVisibility(View.VISIBLE);
return rootView;
}
//Downloading data asynchronously
public class AsyncHttpTask extends AsyncTask<String, Void, Integer> {
#Override
protected Integer doInBackground(String... params) {
Integer result = 1;
parseResult();
return result;
}
#Override
protected void onPostExecute(Integer result) {
// Download complete. Lets update UI
if (result == 1) {
mGridAdapter.setGridData(mGridData);
} else {
Toast.makeText(getActivity().getBaseContext(), "Failed to fetch data!", Toast.LENGTH_SHORT).show();
}
//Hide progressbar
mProgressBar.setVisibility(View.GONE);
}
}
String streamToString(InputStream stream) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
String line;
String result = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
// Close stream
if (null != stream) {
stream.close();
}
return result;
}
private void parseResult() {
catid = p.getString("SelectedCatalogueIdFromGrid1", "");
int clickedPosn = p.getInt("clickedPosition", 0);
int count = p.getInt("numOfImagesInside"+catid+clickedPosn, 0);
Log.d("counterman-id", String.valueOf(count));
GridItem item;
for (int i = 0; i < count; i++) {
item = new GridItem();
item.setTitle("");
// item.setImage("file://" + Environment.getExternalStorageDirectory() + "/" + "thumbImage" + catid + i + ".jpg");
item.setImage("/data/data/com.example.adaptiz.tanishq/"+"thumbImage" + catid + i+".jpg");
// item.setImage(imgSh.getString("thumb" + i, ""));
mGridData.add(item);
}
}
Adapter
public class GridViewAdapter2 extends ArrayAdapter<GridItem> {
//private final ColorMatrixColorFilter grayscaleFilter;
private Context mContext;
private int layoutResourceId;
private ArrayList<GridItem> mGridData = new ArrayList<GridItem>();
public GridViewAdapter2(Context mContext, int layoutResourceId, ArrayList<GridItem> mGridData) {
super(mContext, layoutResourceId, mGridData);
this.layoutResourceId = layoutResourceId;
this.mContext = mContext;
this.mGridData = mGridData;
}
/**
* Updates grid data and refresh grid items.
*
* #param mGridData
*/
public void setGridData(ArrayList<GridItem> mGridData) {
this.mGridData = mGridData;
notifyDataSetChanged();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder;
if (row == null) {
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
Typeface type_normal = Typeface.createFromAsset(getContext().getAssets(), "HelveticaNeue-Light.otf");
holder = new ViewHolder();
holder.titleTextView = (TextView) row.findViewById(R.id.grid_item_title);
holder.titleTextView.setTypeface(type_normal);
holder.download=(ImageView)row.findViewById(R.id.img);
holder.imageView = (ImageView) row.findViewById(R.id.grid_item_image);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
GridItem item = mGridData.get(position);
holder.titleTextView.setText(Html.fromHtml(item.getTitle()));
File image = new File(item.getImage(), "");
BitmapFactory.Options options = new BitmapFactory.Options();
options.inTempStorage = new byte[16*1024];
options.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(), options);
// bitmap = Bitmap.createScaledBitmap(bitmap, 230, 230, true);
Log.d("the bitmap size", String.valueOf(bitmap.getWidth() + " " + bitmap.getHeight()));
holder.imageView.setImageBitmap(bitmap);
//bitmap=null;
// Picasso.with(mContext).load(item.getImage()).into(holder.imageView);
return row;
}
static class ViewHolder {
TextView titleTextView;
ImageView imageView;
ImageView download;
}
xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/toprel"
>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="30dp"
android:id="#+id/top"
android:orientation="horizontal"
android:layout_alignParentTop="true"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="30dp"
android:id="#+id/searchTitle"
android:layout_centerVertical="true"
android:text="Search"
android:textSize="15sp"
android:gravity="left"
android:layout_toRightOf="#+id/leftTitle"
android:layout_toEndOf="#+id/leftTitle" />
<EditText
android:inputType="text"
android:layout_centerVertical="true"
android:layout_width="200dp"
android:layout_height="30dp"
android:id="#+id/searchBox"
android:background="#drawable/searchbg2x"
android:layout_toRightOf="#+id/searchTitle"
android:layout_toEndOf="#+id/searchTitle"
android:layout_marginLeft="15dp"
android:singleLine="true"
android:imeOptions="actionSearch"
/>
</LinearLayout>
<View
android:layout_marginTop="5dp"
android:layout_width="match_parent"
android:layout_height="1dp"
android:id="#+id/hr"
android:background="#000000"
android:layout_below="#id/top"
/>
<GridView
android:layout_below="#+id/hr"
android:id="#+id/gridView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:columnWidth="200dp"
android:gravity="center"
android:numColumns="4"
android:stretchMode="columnWidth"
android:verticalSpacing="5dp"
android:listSelector="#android:color/transparent"
android:clickable="true"
android:fastScrollEnabled="true"/>
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/progressBar"
android:layout_centerInParent="true"
android:visibility="gone"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="20dp"
android:orientation="horizontal"
android:id="#+id/userlayout"
android:layout_alignParentTop="true"
android:visibility="gone"
android:layout_alignRight="#+id/gridView"
android:layout_alignEnd="#+id/gridView"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:textSize="18sp"
android:id="#+id/userView"
android:text="username"
/>
<ImageView
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_width="20dp"
android:layout_height="10dp"
android:background="#drawable/icon"
/>
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textSize="15sp"
android:layout_gravity="bottom"
android:layout_alignBottom="#+id/gridView"
android:layout_centerHorizontal="true" />
</RelativeLayout>

For that you have to use Image Loader to load image.
Refer below link for that.
http://www.androidhive.info/2012/07/android-loading-image-from-url-http/

Related

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

how to get radibutton Postion from listview On Button click in android

This is my screenshot:
This is my adapter class:
public class ListofAddressesAdapter extends ArrayAdapter<ListofAddressesDataModel> {
private Context context;
private int layoutResourceId;
HashMap<Integer, Integer> hashMap;
private List<ListofAddressesDataModel> data;
int selectedPosition = 0;
String name, phone, address;
String customeraddressid;
public ListofAddressesAdapter(Context context, int layoutResourceId,
List<ListofAddressesDataModel> data) {
super(context, R.layout.listofaddresses, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
hashMap = new HashMap<Integer, Integer>();
}
#Override
public View getView(final int position, final View convertView, ViewGroup parent) {
View row = convertView;
final ViewHolder holder;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ViewHolder();
holder.name = (TextView) row.findViewById(R.id.tvsubservices);
holder.description = (TextView) row.findViewById(R.id.tvdesc);
holder.fulladd = (TextView) row.findViewById(R.id.tvfulladdr);
holder.r = (RadioButton) row.findViewById(R.id.radioButton);
holder.delet = (ImageView) row.findViewById(R.id.ivdelete);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
final ListofAddressesDataModel item = data.get(position);
holder.name.setText(item.getName());
holder.description.setText(item.getPhone());
holder.fulladd.setText(item.getFulladdress());
holder.r.setChecked(position == selectedPosition);
holder.r.setTag(position);
holder.r.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectedPosition = (Integer) view.getTag();
name = data.get(selectedPosition).getName();
phone = data.get(selectedPosition).getPhone();
address = data.get(selectedPosition).getFulladdress();
customeraddressid = data.get(selectedPosition).getCustaddid();
notifyDataSetChanged();
}
});
return row;
}
static class ViewHolder {
TextView name;
TextView description;
TextView fulladd;
RadioButton r;
ImageView delet;
}
public Object getItemAtPosition(int position) {
// TODO Auto-generated method stub
return null;
}
}
This is my activity class:
public class testclass extends Activity implements View.OnClickListener{
List<ListofAddressesDataModel> lstDataModel;
ListView add;
JSONArray _jsonarray;
JSONObject jsonObject;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
add = (ListView) findViewById(R.id.add);
setContentView(R.layout.test);
add=(ListView)findViewById(R.id.add);
lstDataModel=new ArrayList<>();
button=(Button)findViewById(R.id.button);
button.setOnClickListener(this);
new manageaddresses().execute();
}
#Override
public void onClick(View v) {
if(v.getId()==R.id.button)
{
}
}
class manageaddresses extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... params) {
String response = JSONfunctions.getJSONfromURL("http://cpanel.smartindiaservice.com/api/CustomerAddresses?CustomerID=4");
try {
_jsonarray = new JSONArray(response);
for (int i = 0; i < _jsonarray.length(); i++) {
ListofAddressesDataModel datamodel = new ListofAddressesDataModel();
jsonObject = _jsonarray.getJSONObject(i);
String customeraddressid = jsonObject.getString("CustomerAddressID");
datamodel.setCustaddid(customeraddressid);
String fullname = jsonObject.getString("FullName");
datamodel.setName(fullname);
String housenumber = jsonObject.getString("HouseNumber");
String phonenumber = jsonObject.getString("PhoneNumber");
datamodel.setPhone(phonenumber);
String area = jsonObject.getString("Area");
String landmark = jsonObject.getString("Landmark");
String city = jsonObject.getString("City");
String fulladdress = housenumber + "," + " " + area + "," + " " + landmark + "," + " " + city;
datamodel.setFulladdress(fulladdress);
lstDataModel.add(datamodel);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
ListofAddressesAdapter adapter = new ListofAddressesAdapter(testclass.this, R.layout.listofaddresses, lstDataModel);
add.setAdapter(adapter);
adapter.notifyDataSetChanged();
super.onPostExecute(result);
}
}
}
This is my item.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:orientation="horizontal"
android:paddingBottom="20dp">
<RadioButton
android:id="#+id/radioButton"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginLeft="10dp"
android:buttonTint="#999999"
android:text="New RadioButton" />
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout4"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:layout_weight="1"
android:orientation="vertical"
android:paddingBottom="10dp">
<TextView
android:id="#+id/tvsubservices"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/radioButton"
android:layout_marginLeft="50dp"
android:layout_toRightOf="#+id/radioButton"
android:text="TextView"
android:textColor="#000000"
android:textSize="18dp" />
<TextView
android:id="#+id/tvdesc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tvsubservices"
android:layout_marginLeft="50dp"
android:layout_toRightOf="#+id/radioButton"
android:text="Description"
android:textColor="#000000"
android:textSize="14dp" />
<TextView
android:id="#+id/tvfulladdr"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tvdesc"
android:layout_marginLeft="50dp"
android:layout_toRightOf="#+id/radioButton"
android:text="New Text"
android:textColor="#000000"
android:textSize="14dp" />
<TextView
android:id="#+id/custaddidposition"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="position"
android:visibility="gone" />
</LinearLayout>
</RelativeLayout>
I want to get selected radio button position or value and id so that on button click I tried with but it always take first position. Can any one suggest me where am I doing wrong? I have to get selected radio button position so that I can get value from list of Objects. I have to send into next activity.
In adapter create a method which returns the object of selected position. Like :
public ListofAddressesDataModel getSelectedItem() {
return data.get(selectedPosition);
}
In activity, on click of the button call this method. Like :
#Override
public void onClick(View v) {
if(v.getId() == R.id.button) {
//Here you will get the selected item of which the radio button is checked
ListofAddressesDataModel selectedItem = ((ListofAddressesAdapter) add.getAdapter()).getSelectedItem();
}
}
EDIT :
Instead of below lines in getView() in adapter
holder.r.setTag(position);
holder.r.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectedPosition = (Integer) view.getTag();
name = data.get(selectedPosition).getName();
phone = data.get(selectedPosition).getPhone();
address = data.get(selectedPosition).getFulladdress();
customeraddressid = data.get(selectedPosition).getCustaddid();
notifyDataSetChanged();
}
});
just replace it with below line
holder.r.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectedPosition = position;
}
});

Custom Listview onClick not moving to Tab Fragments page

I have an activity with CustomAdapter ListView and TabLayout with three tabs TrainerTab1, TrainerTab2, TrainerTab3. While clicking on an item it should move to next page that is to TrainerTab1 Fragment.
I need to pass the id from ListView onClick() to fragment page. I have used Bundle to pass value but the items are not working. When I click on an item it's not responding and not showing any error.
My custom ListView Class is:
public class Trainer extends AppCompatActivity {
String tabUrl = "http://adoxsolutions.in/numuww/services/trainers";
private GridView gridView;
ArrayList<HashMap<String, String>> alist = new ArrayList<>();
private TrainAdapter adapter;
private ProgressDialog mprogress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_trainer);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
new Train().execute();
}
private class Train extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
mprogress = new ProgressDialog(Trainer.this);
mprogress.setMessage("Loading...");
mprogress.setIndeterminate(false);
mprogress.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
URL url = new URL(tabUrl);
HttpURLConnection connect = (HttpURLConnection) url.openConnection();
connect.setRequestMethod("POST");
//
System.out.println("Response Code:" + connect.getResponseCode());
InputStream in = new BufferedInputStream(connect.getInputStream());
String response = org.apache.commons.io.IOUtils.toString(in, "UTF-8");
System.out.println(response);
Log.d("VALUE:", response);
JSONObject obj = new JSONObject(response);
JSONArray jsArray = obj.optJSONArray("Trainers");
for (int k = 0; k < jsArray.length(); k++) {
HashMap<String, String> map = new HashMap<String, String>();
obj = jsArray.getJSONObject(k);
map.put("id", obj.getString("id"));
map.put("name", obj.getString("name"));
map.put("logo", obj.getString("img"));
alist.add(map);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
gridView = (GridView) findViewById(R.id.trainerGrid);
adapter = new TrainAdapter(getBaseContext(), alist);
gridView.setAdapter(adapter);
adapter.notifyDataSetChanged();
mprogress.dismiss();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.newc, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_search) {
return true;
}
else if(id == android.R.id.home){
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
}
class TrainAdapter extends BaseAdapter {
private Context context;
private ArrayList<HashMap<String, String>> MyArr = new ArrayList<HashMap<String, String>>();
public TrainAdapter(Context c, ArrayList<HashMap<String, String>> list){
context = c;
MyArr = list;
}
#Override
public int getCount() {
return MyArr.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if(convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.trainer_list, null);
}
TextView id= (TextView) convertView.findViewById(R.id.trainerId);
ImageView image = (ImageView) convertView.findViewById(R.id.trainerImage);
TextView text = (TextView) convertView.findViewById(R.id.trainerTexts);
try {
image.setImageBitmap(loadBitmap(MyArr.get(position).get("logo")));
text.setText(MyArr.get(position).get("name"));
id.setText(MyArr.get(position).get("id"));
if (((position - 9) / 3) % 9 == 0) {
ImageView adimg = (ImageView) convertView.findViewById(R.id.trainadBanner);
adimg.setScaleType(ImageView.ScaleType.FIT_XY);
adimg.getLayoutParams().height=150;
adimg.getLayoutParams().width=300;
adimg.setImageResource(R.drawable.mainad);
}
} catch (Exception e) {
e.printStackTrace();
}
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bundle h=new Bundle();
h.putString("id",MyArr.get(position).get("id"));
Fragment tt1=new TrainerTab1();
tt1.setArguments(h);
}
});
// }else{
// convertView=inflater.inflate(R.layout.trainer_list, parent,false);
// ImageView image= (ImageView) convertView.findViewById(R.id.trainerImage);
// TextView text= (TextView) convertView.findViewById(R.id.trainerTexts);
// try{
// image.setImageResource(R.drawable.ic_action_name);
// text.setText(MyArr.get(position).get("name"));
// if(position % 9 == 0){
// ImageView adimg= (ImageView) convertView.findViewById(R.id.trainadBanner);
// adimg.setImageResource(R.drawable.mainad);
// }
//
// } catch(Exception e){
// e.printStackTrace();
// }
return convertView;
}
private static final String TAG = "ERROR";
private static final int IO_BUFFER_SIZE = 4 * 1024;
private static Bitmap loadBitmap(String tabUrl) {
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new URL(tabUrl).openStream(), IO_BUFFER_SIZE);
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
copy(in, out);
out.flush();
final byte[] data = dataStream.toByteArray();
BitmapFactory.Options options = new BitmapFactory.Options();
//options.inSampleSize = 1;
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
} catch (IOException e) {
Log.e(TAG, "Could not load Bitmap from: " + tabUrl);
} finally {
closeStream(in);
closeStream(out);
}
return bitmap;
}
private static void closeStream(Closeable stream) {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
android.util.Log.e(TAG, "Could not close stream", e);
}
}
}
private static void copy(InputStream in, OutputStream out) throws IOException {
byte[] b = new byte[IO_BUFFER_SIZE];
int read;
while ((read = in.read(b)) != -1) {
out.write(b, 0, read);
}
}
}
My tab fragment:
public class TrainerTab1 extends Fragment {
String turl="http://adoxsolutions.in/numuww/services/trainer";
TextView tname,tplace,tsex;
public TrainerTab1() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView= inflater.inflate(R.layout.fragment_trainer_tab1, container, false);
final String tid=getArguments().getString("id");
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
tname= (TextView) rootView.findViewById(R.id.trainerCourse);
tplace= (TextView) rootView.findViewById(R.id.trainerPlace);
tsex= (TextView) rootView.findViewById(R.id.trainerSex);
ImageView photo= (ImageView) rootView.findViewById(R.id.trainer_photo);
}
}
Inside the onClickListener
after adding the bundle to the fragment.
FragmentManager fragmentManager = Trainer.this.getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.add(R.id.someIDForYourFrameLayout, tt1).commit();
can you just ellaborate where to use this exactly. I mean I don't understand how to add id of fragment to transaction.add(R.id.someIDForYourFrameLayout, tt1).commit();
I tried like this:
Bundle h=new Bundle();
h.putString("id",MyArr.get(position).get("id"));
Fragment tt1=new TrainerTab1();
tt1.setArguments(h);
FragmentTransaction transact=getSupportFragmentManager().beginTransaction();
transact.add(R.id.trainerFragment,tt1).commit();
This is my fragment_trainer_tab_1 layout:
<ScrollView 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:scrollbars="vertical"
android:scrollbarSize="1dp"
android:id="#+id/trainerFragment"
tools:context="com.example.anu.numuww.TrainerTab1">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="12dp"
android:background="#color/blue">
<ImageView
android:id="#+id/trainer_photo"
android:layout_width="120dp"
android:layout_height="120dp"
android:layout_gravity="center"
android:contentDescription="#string/trainers"
android:src="#mipmap/ic_launcher"
android:layout_marginTop="20dp"/>
<TextView
android:id="#+id/trainerCourse"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text=""
android:layout_marginTop="12dp"
android:textColor="#ffffff"
android:textSize="22sp"
android:gravity="center"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal">
<TextView
android:id="#+id/trainerSex"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:layout_marginTop="5dp"
android:textColor="#ffffff"
android:textSize="17sp"
android:layout_gravity="center"/>
<TextView
android:id="#+id/trainerPlace"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:textColor="#ffffff"
android:textSize="17sp"
android:gravity="center"/>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#F5F5F5"
android:gravity="center_horizontal"
android:padding="7dp"
android:orientation="horizontal">
<ImageView
android:layout_width="38dp"
android:layout_height="38dp"
android:padding="2dp"
android:src="#drawable/global"/>
<ImageView
android:layout_width="38dp"
android:layout_height="38dp"
android:padding="2dp"
android:src="#drawable/messenger"/>
<ImageView
android:layout_width="38dp"
android:layout_height="38dp"
android:padding="2dp"
android:src="#drawable/google_plus"/>
<ImageView
android:layout_width="38dp"
android:layout_height="38dp"
android:padding="2dp"
android:src="#drawable/inst_detail"/>
<ImageView
android:layout_width="38dp"
android:layout_height="38dp"
android:padding="2dp"
android:src="#drawable/telegram"/>
<ImageView
android:layout_width="38dp"
android:layout_height="38dp"
android:padding="2dp"
android:src="#drawable/facebook"/>
<ImageView
android:layout_width="38dp"
android:layout_height="38dp"
android:padding="2dp"
android:src="#drawable/twitter"/>
<ImageView
android:layout_width="38dp"
android:layout_height="38dp"
android:padding="2dp"
android:src="#drawable/inst_instagram"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="14dp"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="3dp"
android:text="About Trainer"
android:textColor="#color/blue"
android:textSize="19sp"
android:textStyle="bold"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/para"
android:layout_marginTop="4dp"
android:layout_marginBottom="2dp"
android:textSize="14sp"/>
</LinearLayout>
</LinearLayout>
</ScrollView>

Circular imageview dissappears in listview after fling

Im generating a feed full of images (similar to instagram post) using Glide for loading images and user's profile picture. After i get the data from server, i load the Url's of images inside the listitem. Initally All items are being loaded properly.
The issue is that when i fast scroll the listview, user profile picture dissappears and that view doesnt respond to onClick Events. Please explain why this happens and how can i resolve this?
XML layout of each list Item.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="20dp"
android:orientation="vertical" >
<RelativeLayout android:id="#+id/userheader"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginTop="10dp"
android:layout_weight="1">
<com.mikhaellopez.circularimageview.CircularImageView
android:id="#+id/realdp"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:src="#drawable/nodp"
android:scaleType="centerCrop"
android:adjustViewBounds="true"/>
<TextView
android:id="#+id/handle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/realdp"
android:text="handle"
android:layout_marginLeft="3dp"
android:gravity="center_vertical"
android:layout_alignTop="#+id/realdp"
android:layout_alignBottom="#+id/realdp"
android:textAppearance="?android:attr/textAppearanceMedium"/>
<TextView
android:id="#+id/uploadtime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/handle"
android:layout_marginRight="5dp"
android:layout_alignParentRight="true"
android:text="time"
android:textAppearance="?android:attr/textAppearanceSmall" />
<RelativeLayout android:id="#+id/rlimg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/handle">
<ImageView
android:id="#+id/imgpost"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="fitXY"
android:adjustViewBounds="true"
android:background="#ffffff"/>
</RelativeLayout>
<RelativeLayout android:id="#+id/bottom"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/rlimg"
android:layout_marginTop="5dp">
<com.sivaram.fishograph.FlipImageView
android:id="#+id/like"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#00000000"
android:layout_marginLeft="20dp"
android:src="#drawable/hook_unlike"/>
<ImageButton
android:id="#+id/comment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#00000000"
android:layout_toRightOf="#+id/likesnum"
android:layout_marginLeft="20dp"
android:src="#drawable/comment" />
<ImageButton
android:id="#+id/more"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="3dp"
android:layout_alignParentRight="true"
android:background="#00000000"
android:src="#drawable/more" />
<TextView
android:id="#+id/likesnum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/like"
android:layout_alignTop="#+id/like"
android:layout_marginLeft="5dp"
android:layout_toRightOf="#+id/like"
android:text="likes"
android:gravity="center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#440011" />
<TextView
android:id="#+id/comnum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/comment"
android:layout_alignTop="#+id/comment"
android:layout_marginLeft="10dp"
android:layout_toRightOf="#+id/comment"
android:gravity="center_vertical"
android:text="comments"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#440011" />
</RelativeLayout>
</RelativeLayout>
<TextView
android:id="#+id/caption"
android:layout_width="match_parent"
android:layout_height="0dp"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:layout_below="#+id/userheader"
android:gravity="center_horizontal"
android:layout_weight="1"
android:text="Caption"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/dummy"
android:layout_width="match_parent"
android:layout_height="0dp"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:layout_below="#+id/caption"
android:gravity="center_horizontal"
android:layout_weight="1"
android:text=""
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
Java Code for generating feed:
public class Feed extends Fragment implements OnScrollListener
{
String handle;
ListView lvposts;
Jsparser jp;
int width,height;
int maxMemory;
int currentFirstVisibleItem ;
int currentVisibleItemCount;
PostAdapter pa;
ArrayList<eachpost> posts;
int value = 1;
boolean isLoading = false;
int photoid;
private List<String> myData;
Boolean tapped = false, Loading= false;
SharedPreferences spf;
ArrayList<String> likes;
public Feed()
{
super();
}
Feed(String handle)
{
super();
photoid = 99999999;
this.handle = handle;
}
#Override
public void onCreate(Bundle b)
{
super.onCreate(b);
maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
final int cacheSize = maxMemory / 8;
spf = getActivity().getSharedPreferences("prefs",Context.MODE_PRIVATE);
likes = new ArrayList<String>();
}
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup vg, Bundle b)
{
View v = inflater.inflate(R.layout.allposts, vg, false);
ActionBar ab = ((ActionBarActivity) getActivity()).getSupportActionBar();
ab.setBackgroundDrawable(new ColorDrawable(Color.RED));
ab.hide();
lvposts = (ListView) v.findViewById(R.id.lvposts);
jp = new Jsparser();
Display d = getActivity().getWindowManager().getDefaultDisplay();
width = d.getWidth();
height = d.getHeight();
lvposts.setOnScrollListener(this);
posts = new ArrayList<eachpost>();
pa = new PostAdapter(getActivity(),R.layout.postcontent,posts,inflater);
Loading = true;
lvposts.setAdapter(pa);
new GetData(photoid).execute();
return v;
}
class GetData extends AsyncTask<String,String,String>
{
String msg;
Integer limit,success=0;
ProgressDialog pd;
Bitmap dpbm;
GetData(int l)
{
limit = l;
}
#Override
public void onPreExecute()
{
}
#Override
protected String doInBackground(String... params) {
List<NameValuePair> lp = new ArrayList<NameValuePair>();
lp.add(new BasicNameValuePair("handle",handle));
lp.add(new BasicNameValuePair("photoid",limit.toString()));
JSONObject job = jp.makeHttpRequest("server/getfeed.php", "POST", lp);
try
{
Log.d("json", job.toString());
success = job.getInt("success");
msg = job.getString("message");
if(success==1)
{
JSONArray ja = job.getJSONArray("posts");
for(int c = 0; c<ja.length(); c++)
{
JSONObject jb = ja.getJSONObject(c);
posts.add(new eachpost(jb.getString("handle"),jb.getString("url"), jb.getString("caption"),
jb.getString("uldatetime"), jb.getInt("likescount"), jb.getInt("comcount"), jb.getString("dpurl"), jb.getInt("isliked"),jb.getInt("photoid") ));
}
}
else
{
}
}
catch(Exception e)
{
e.printStackTrace();
}
return msg;
}
#Override
public void onPostExecute(String url)
{
Loading = false;
if(success==1)
{
photoid = posts.get(posts.size()-1).getPhotoid();
Log.d("last id",photoid+"");
Log.d("Length of posts",""+posts.size());
pa.notifyDataSetChanged();
}
}
}
class PostAdapter extends ArrayAdapter<eachpost>
{
ViewHolder vholder;
String root = Environment.getExternalStorageDirectory().toString();
File dir = new File (root + ".feed");
Map<Integer,View> myViews;
public PostAdapter(Context context, int resource, ArrayList<eachpost> list, LayoutInflater li) {
super(context, R.layout.postcontent, list);
myViews = new HashMap<Integer,View>();
}
#Override
public View getView(final int pos,View v,ViewGroup vg)
{
final eachpost post = posts.get(pos);
final String imgurl = post.getPhotoUrl();
String dpurl = post.getDpurl();
int isliked = post.getIsliked();
View row = myViews.get(pos);
if(row == null)
{
row = getActivity().getLayoutInflater().inflate(R.layout.postcontent,vg,false);
row.setMinimumHeight(height);
vholder = new ViewHolder();
vholder.handle = ((TextView) row.findViewById(R.id.handle));
vholder.caption = ((TextView) row.findViewById(R.id.caption));
vholder.likesnum = ((TextView) row.findViewById(R.id.likesnum));
vholder.comnum = ((TextView) row.findViewById(R.id.comnum));
vholder.uploadtime = ((TextView) row.findViewById(R.id.uploadtime));
vholder.photo = (ImageView) row.findViewById(R.id.imgpost);
vholder.feeddp = (CircularImageView) row.findViewById(R.id.realdp);
vholder.like = (FlipImageView) row.findViewById(R.id.like);
LayoutParams lp = vholder.photo.getLayoutParams();
lp.width = width;
lp.height = width;
vholder.handle.setText(post.getHandle());
vholder.caption.setText(post.getCaption());
vholder.likesnum.setText(post.getLikes()+"");
vholder.comnum.setText(post.getComments()+"");
vholder.uploadtime.setText(post.getUl());
Drawable d = getResources().getDrawable(R.drawable.hook_like);
vholder.like.setFlippedDrawable(d);
Glide.with(getActivity()).load("server/"+imgurl).into(vholder.photo);
if(dpurl.contains("http"))
Glide.with(getActivity()).load(dpurl).into(vholder.feeddp);
else
Glide.with(getActivity()).load("server/"+dpurl).into(vholder.feeddp);
Log.d("image loading", dpurl + "-" + imgurl);
if(isliked==1)
{
vholder.like.setFlipped(true,false);
likes.add(imgurl);
}
vholder.like.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View temp = myViews.get(pos);
final FlipImageView like = (FlipImageView) temp.findViewById(R.id.like);
final TextView likesnum = (TextView) temp.findViewById(R.id.likesnum);
like.toggleFlip();
if(!likes.contains(imgurl))
{
posts.get(pos).incrementLikes(handle);
likes.add(posts.get(pos).getPhotoUrl());
likesnum.setText(posts.get(pos).getLikes()+"");
}
else
{
likes.remove(posts.get(pos).getPhotoUrl());
posts.get(pos).decrementLikes(handle);
likesnum.setText(posts.get(pos).getLikes()+"");
}
}
});
row.setTag(vholder);
myViews.put(pos, row);
}
return row;
}
#Override
public boolean isEnabled(int position)
{
return true;
}
} //end of adapter class
static class ViewHolder {
TextView handle;
TextView caption;
TextView likesnum;
TextView comnum;
TextView uploadtime;
ImageView photo;
CircularImageView feeddp;
FlipImageView like;
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (this.currentVisibleItemCount > 0 && scrollState == SCROLL_STATE_FLING) {
/*** In this way I detect if there's been a scroll which has completed ***/
/*** do the work for load more date! ***/
if(currentFirstVisibleItem > (currentVisibleItemCount - 2) && Loading!=true)
{
new GetData(photoid).execute();
}
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
this.currentFirstVisibleItem = firstVisibleItem;
this.currentVisibleItemCount = visibleItemCount;
}
}
When loading multiple images there is always caching problem when using Async Tasks. I recommend an open source library Picasso. It will load the images and cache it. After that most probably, your fast scroll problem will solve.
The cause can also be the size of the images being received. Picasso has methods by which you can resize the image before putting it onto the image view
try with this modified getView
#Override
public View getView(final int pos,View v,ViewGroup vg)
{
final eachpost post = posts.get(pos);
final String imgurl = post.getPhotoUrl();
String dpurl = post.getDpurl();
int isliked = post.getIsliked();
View row = myViews.get(pos);
if(row == null)
{
row = getActivity().getLayoutInflater().inflate(R.layout.postcontent,vg,false);
row.setMinimumHeight(height);
vholder = new ViewHolder();
vholder.handle = ((TextView) row.findViewById(R.id.handle));
vholder.caption = ((TextView) row.findViewById(R.id.caption));
vholder.likesnum = ((TextView) row.findViewById(R.id.likesnum));
vholder.comnum = ((TextView) row.findViewById(R.id.comnum));
vholder.uploadtime = ((TextView) row.findViewById(R.id.uploadtime));
vholder.photo = (ImageView) row.findViewById(R.id.imgpost);
vholder.feeddp = (CircularImageView) row.findViewById(R.id.realdp);
vholder.like = (FlipImageView) row.findViewById(R.id.like);
LayoutParams lp = vholder.photo.getLayoutParams();
lp.width = width;
lp.height = width;
row.setTag(vholder); //changed here setTag()
}else{
vholder=(ViewHolder)row.getTag(); //changed here getTag()
}
vholder.handle.setText(post.getHandle());
vholder.caption.setText(post.getCaption());
vholder.likesnum.setText(post.getLikes()+"");
vholder.comnum.setText(post.getComments()+"");
vholder.uploadtime.setText(post.getUl());
Drawable d = getResources().getDrawable(R.drawable.hook_like);
vholder.like.setFlippedDrawable(d);
Glide.with(getActivity()).load("server/"+imgurl).into(vholder.photo);
if(dpurl.contains("http"))
Glide.with(getActivity()).load(dpurl).into(vholder.feeddp);
else
Glide.with(getActivity()).load("server/"+dpurl).into(vholder.feeddp);
Log.d("image loading", dpurl + "-" + imgurl);
if(isliked==1)
{
vholder.like.setFlipped(true,false);
likes.add(imgurl);
}
vholder.like.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View temp = myViews.get(pos);
final FlipImageView like = (FlipImageView) temp.findViewById(R.id.like);
final TextView likesnum = (TextView) temp.findViewById(R.id.likesnum);
like.toggleFlip();
if(!likes.contains(imgurl))
{
posts.get(pos).incrementLikes(handle);
likes.add(posts.get(pos).getPhotoUrl());
likesnum.setText(posts.get(pos).getLikes()+"");
}
else
{
likes.remove(posts.get(pos).getPhotoUrl());
posts.get(pos).decrementLikes(handle);
likesnum.setText(posts.get(pos).getLikes()+"");
}
}
});
myViews.put(pos, row);
}
return row;
}

Having an issue with a custom listview adapter

As the title states, I'm having some troubles getting my custom listView adapter to work. The app doesn't crash, but it also displays nothing on the list. I tested my data with a simple list I already have setup, and that worked just fine.
History.java
public class History {
public String score;
public String gametype;
public int icon;
public History() {
super();
}
public History(String score, String gametype, int icon) {
super();
this.score = score;
this.gametype = gametype;
this.icon = icon;
}
}
HistoryAdapter.java
public class HistoryAdapter extends ArrayAdapter<History> {
Context context;
int layoutResId;
History data[] = null;
public HistoryAdapter(Context context, int layoutResId, History[] data) {
super(context, layoutResId, data);
this.layoutResId = layoutResId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
HistoryHolder holder = null;
if(convertView == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
convertView = inflater.inflate(layoutResId, parent, false);
holder = new HistoryHolder();
holder.imageIcon = (ImageView)convertView.findViewById(R.id.icon);
holder.textTitle = (TextView)convertView.findViewById(R.id.gameType);
holder.textScore = (TextView)convertView.findViewById(R.id.score);
convertView.setTag(holder);
}
else
{
holder = (HistoryHolder)convertView.getTag();
}
History history = data[position];
holder.textScore.setText(history.score);
holder.textTitle.setText(history.gametype);
holder.imageIcon.setImageResource(history.icon);
return convertView;
}
static class HistoryHolder
{
ImageView imageIcon;
TextView textTitle;
TextView textScore;
}
}
Implementation
for(int i = 0; i < games.length(); i++) {
JSONObject c = games.getJSONObject(i);
JSONObject gameStats = games.getJSONObject(i).getJSONObject(TAG_STATS);
type[i] = c.getString(TAG_TYPE);
champId[i] = c.getString("championId");
cs[i] = gameStats.getString("minionsKilled");
kills[i] = gameStats.getString("championsKilled");
deaths[i] = gameStats.getString("numDeaths");
assists[i] = gameStats.getString("assists");
win[i] = gameStats.getString("win");
if(win[i].equals("true"))
win[i] = "Victory";
else
win[i] = "Defeat";
if(type[i].equals("RANKED_SOLO_5x5"))
type[i] = "Ranked (Solo)";
if(type[i].equals("CAP_5x5"))
type[i] = "TeamBuilder";
if(type[i].equals("NORMAL"))
type[i] = "Unranked";
score[i] = kills[i] +"/" + deaths[i] + "/" + assists[i];
historyData[i] = new History(score[i], champId[i], R.drawable.ic_launcher); // Placeholder image
}
adapter = new HistoryAdapter(MatchHistoryActivity.this,
R.layout.list_adapter,
historyData);
list.setAdapter(adapter);
listview.xml
<?xml version="1.0" encoding="utf-8"?>
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/list"
android:background="#111111">
</ListView>
list_item.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:background="#111111"
android:padding="6dip" >
<ImageView
android:id="#+id/icon"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true"
android:layout_marginRight="6dip"
android:contentDescription="TODO"
android:src="#drawable/ic_launcher" />
<TextView
android:id="#+id/score"
android:textColor="#C49246"
android:layout_width="fill_parent"
android:layout_height="26dip"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginLeft="5dp"
android:layout_toRightOf="#id/icon"
android:ellipsize="marquee"
android:singleLine="true"
android:text="0/0/0 KDA"
android:textSize="12sp" />
<TextView
android:id="#+id/gameType"
android:textColor="#C49246"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#id/score"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_alignWithParentIfMissing="true"
android:layout_marginLeft="5dp"
android:layout_toRightOf="#id/icon"
android:gravity="center_vertical"
android:textSize="16sp" />
</RelativeLayout>
You are creating a History object with this line:
new History(score[i], champId[i], R.drawable.ic_launcher); // Placeholder image
This just calls the constructor and creates an object for the garbage collector to take away again.
You are not actually adding this History object to the historyData array.
Before the loop, you should declare the historyData array as:
History[] historyData = new History[games.length();
And in the loop, you should assign the created object to the array
historyData[i] = new History(score[i], champId[i], R.drawable.ic_launcher); // Placeholder image

Categories

Resources