I am facing a issue in a horizontal recyclerview adapter.My adapter contains a imageview in postion 0 and remainings postion are empty.
When I do scroll from left to right, my images reappear from position 1 to 4 and 7.If I keeps on scrolling from left to right my imageview appears in all postion here is my adapter class.I have placed this Horizontal Recyclerview Adapter in a Vertical Recyclerview Adapter.
HomeBannerAdapter.Java
public class HomeBannerAdapter extends RecyclerView.Adapter {
private List<HomePageList> mHomepageList;
private Context mContext;
public HomeBannerAdapter(Context context, List<HomePageList> mHomepageList) {
this.mHomepageList = mHomepageList;
this.mContext = context;
}
#Override
public SingleItemRowHolder onCreateViewHolder(ViewGroup viewGroup, int position) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_single_card, viewGroup, false);
SingleItemRowHolder mh = new SingleItemRowHolder(v);
return mh;
}
#Override
public void onBindViewHolder(final SingleItemRowHolder holder, final int position) {
final HomePageList singleItem = mHomepageList.get(position);
holder.mTitle.setText(singleItem.getTitle());
if (!singleItem.getBannerUrl().isEmpty()) {
Glide.with(mContext).load(singleItem.getBannerUrl().get(0)).placeholder(R.drawable.placeholder).dontAnimate().into(holder.itemImage);
Log.e("Homebanner not empty", "url" + singleItem.getBannerUrl().toString() + "position" + position);
} else {
Log.e("Homebanner url empty", "url" + singleItem.getBannerUrl().toString() + "position" + position);
}
}
#Override
public int getItemCount() {
return (null != mHomepageList ? mHomepageList.size() : 0);
}
public class SingleItemRowHolder extends RecyclerView.ViewHolder {
public ImageView itemImage;
//int position = getAdapterPosition();
public TextView mTitle;
public HomePageList mHomePageList;
public SingleItemRowHolder(View view) {
super(view);
this.itemImage = (ImageView) view.findViewById(R.id.itemImage);
this.mTitle = (TextView) view.findViewById(R.id.tvTitle);
// mHomePageList = albumList.get(getPosition());
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), mTitle.getText().toString() + " position " + getPosition() + "getAdapterPosition" + getAdapterPosition(), Toast.LENGTH_SHORT).show();
}
});
}
}
}
Here is my Vertical Recyclerview Adapter
HomeDataAdapter.Java
public class HomeDataAdapter extends RecyclerView.Adapter {
private List<FormList> formList;
private Context mContext;
private List<HomePage> homePageList;
private List<ResourceType> resourceList;
final int VIEW_TYPE_HOMEPAGE = 0;
final int VIEW_TYPE_FORMPAGE = 1;
final int VIEW_TYPE_RESOURCEPAGE = 2;
public HomeDataAdapter(Context context, List<HomePage> homePageList) {
this.homePageList = homePageList;
this.mContext = context;
}
public HomeDataAdapter(Context context, List<HomePage> homePageList, List<FormList> formList) {
this.formList = formList;
this.homePageList = homePageList;
this.mContext = context;
}
public HomeDataAdapter(Context context, List<HomePage> homePageList, List<FormList> formList, List<ResourceType> resourceList) {
this.resourceList = resourceList;
this.formList = formList;
this.homePageList = homePageList;
this.mContext = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int position) {
switch (position) {
case VIEW_TYPE_HOMEPAGE:
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_item, null);
ViewHolder homeView = new ViewHolder(v);
return homeView;
case VIEW_TYPE_FORMPAGE:
View v1 = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_item, null);
ViewHolder formView = new ViewHolder(v1);
return formView;
case VIEW_TYPE_RESOURCEPAGE:
View v2 = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_item, null);
ViewHolder resourceView = new ViewHolder(v2);
return resourceView;
}
return null;
}
#Override
public void onBindViewHolder(final ViewHolder itemRowHolder, int position) {
if (position == VIEW_TYPE_HOMEPAGE) {
HomePage mHomePage = homePageList.get(position);
Log.e("albumList", "albumList" + homePageList.get(position).toString() + "position" + position);
itemRowHolder.itemTitle.setText(mHomePage.getHeaderTitle());
HomeBannerAdapter itemListDataAdapter = new HomeBannerAdapter(mContext, mHomePage.getResults());
itemRowHolder.mRecyclerview.setHasFixedSize(true);
itemRowHolder.mRecyclerview.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
itemRowHolder.mRecyclerview.getLayoutManager().scrollToPosition(position);
itemRowHolder.mRecyclerview.getHorizontalOffset();
//itemRowHolder.mRecyclerview.scrollToPositionWithOffset(2, 20);
// itemRowHolder.mRecyclerview.getLayoutManager().smoothScrollToPosition(itemRowHolder.mRecyclerview, null, recyclerAdapter.getItemCount() - 1);
itemRowHolder.mRecyclerview.setAdapter(itemListDataAdapter);
} else if (position == VIEW_TYPE_FORMPAGE) {
position = position - 1;
FormList mFormPage = formList.get(position);
itemRowHolder.itemTitle.setText(formList.get(position).getHeaderTitle());
JobBannerAdapter itemListDataAdapter = new JobBannerAdapter(mContext, mFormPage.getResults());
itemRowHolder.mRecyclerview.setHasFixedSize(true);
itemRowHolder.mRecyclerview.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
itemRowHolder.mRecyclerview.setAdapter(itemListDataAdapter);
} else if (position == VIEW_TYPE_RESOURCEPAGE) {
position = position - 2;
ResourceType mResourceType = resourceList.get(position);
itemRowHolder.itemTitle.setText(mResourceType.getHeaderTitle());
ResourceBannerAdapter itemListDataAdapter = new ResourceBannerAdapter(mContext, resourceList.get(position).getResults());
itemRowHolder.mRecyclerview.setHasFixedSize(true);
itemRowHolder.mRecyclerview.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
itemRowHolder.mRecyclerview.setAdapter(itemListDataAdapter);
}
}
#Override
public int getItemCount() {
int homePageListSize = 0;
int formPageListSize = 0;
int resourcePageListSize = 0;
if (homePageList == null && formList == null && resourceList == null) return 0;
if (resourceList != null)
resourcePageListSize = resourceList.size();
if (formList != null)
formPageListSize = formList.size();
if (homePageList != null)
homePageListSize = homePageList.size();
if (resourcePageListSize > 0 && formPageListSize > 0 && homePageListSize > 0)
return homePageListSize + formPageListSize + resourcePageListSize; // albumlist+formlist+resourceList
if (formPageListSize > 0 && homePageListSize > 0)
return homePageListSize + formPageListSize; // albumlist+formlist
else if (resourcePageListSize > 0 && homePageListSize == 0 && formPageListSize == 0)
return resourcePageListSize; // resourceList
else if (formPageListSize > 0 && homePageListSize == 0)
return formPageListSize; // formlist
else if (formPageListSize == 0 && homePageListSize > 0)
return homePageListSize; // albumlist
else return 0;
// return (null != albumList ? albumList.size()+mFormList.size() : 0);
}
#Override
public int getItemViewType(int position) {
int homePageListSize = 0;
int formPageListSize = 0;
int resourcePageListSize = 0;
if (homePageList == null && formList == null && resourceList == null)
return super.getItemViewType(position);
if (homePageList != null)
homePageListSize = homePageList.size();
if (formList != null)
formPageListSize = formList.size();
if (resourceList != null)
resourcePageListSize = resourceList.size();
if (formPageListSize > 0 && homePageListSize > 0) {
if (position == 0) return VIEW_TYPE_HOMEPAGE;
else if (position == formPageListSize)
return VIEW_TYPE_FORMPAGE;
} else if (formPageListSize == 0 && homePageListSize > 0) {
if (position == 0) return VIEW_TYPE_HOMEPAGE;
else return VIEW_TYPE_FORMPAGE;
} else if (resourcePageListSize > 0 && formPageListSize > 0 && homePageListSize > 0) {
if (position == 0) return VIEW_TYPE_HOMEPAGE;
else if (position == 1)
return VIEW_TYPE_FORMPAGE;
else if (position == 2)
return VIEW_TYPE_RESOURCEPAGE;
}
return super.getItemViewType(position);
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView itemTitle;
public CustomRecyclerView mRecyclerview;
public ViewHolder(View view) {
super(view);
this.itemTitle = (TextView) view.findViewById(R.id.itemTitle);
this.mRecyclerview = (CustomRecyclerView) view.findViewById(R.id.recycler_view_list);
}
}
}
I think some of your items bannerUrls is empty. So if they're empty you do not set a default empty image with Glide or manually. Here i modified your code a little. I think this'll help.
#Override
public void onBindViewHolder(final SingleItemRowHolder holder, final int position) {
final HomePageList singleItem = mHomepageList.get(position);
holder.mTitle.setText(singleItem.getTitle());
if (!TextUtils.isEmpty(singleItem.getBannerUrl())) {
Glide.with(mContext).load(singleItem.getBannerUrl().get(0)).placeholder(R.drawable.placeholder).dontAnimate().into(holder.itemImage);
Log.e("Homebanner not empty", "url" + singleItem.getBannerUrl().toString() + "position" + position);
} else {
holder.itemImage.setImageResource(R.drawable.your_place_holder_for_empty_url);
}
}
Note: Also it's a better choice to use TextUtils.isEmpty(string) to instead of string.isEmpty() to avoid Null Pointer Exception.
Edit:
Also you can let Glide to put placeholder to your ImageView by removing the if statement.
if (!TextUtils.isEmpty(singleItem.getBannerUrl()))
I think this solution'll work you for too. If you choose this way do not forget to set an empty image to Glide for your empty or null urls.
Related
when i use this
#Override
public int getItemViewType(int position) {
return position;
}
my RecyclerView work without problem
now i want to use multi layout on it i use this
#Override
public int getItemViewType(int position) {
int type = -1;
if(mMessages.get(position).getDir().equals("left")) type = 1;
else if(mMessages.get(position).getDir().equals("right")) type = 0;
else if(mMessages.get(position).getDir().equals("typing")) type = 2;
return type;
//return position;
}
the problem when i used it's and scroll to top and back to bottom or just scrolling
its reorder item in RecyclerView like make the first item on it the last one or on middle or every where not i the correct position
just if i back to the first code of getItemViewType its work without
problem but i cant use multi layout
my full code
public class MessageAdapter1 extends RecyclerView.Adapter<MessageAdapter1.ViewHolder> {
private List<MessageList> mMessages;
private int[] mUsernameColors;
private Context context;
public MessageAdapter1(Context context, List<MessageList> messages) {
mMessages = messages;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
int layout = -1;
switch (viewType) {
case 0:
layout = R.layout.right_message;
break;
case 1:
layout = R.layout.left_message;
break;
case 2:
layout = R.layout.message_left;
break;
}
View v = LayoutInflater.from(parent.getContext()).inflate(layout , parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
MessageList message = mMessages.get(position);
//viewHolder.setMessage(message.getMessage());
//viewHolder.setUsername(message.getUsername());
viewHolder.setGroupMessage(message);
}
#Override
public int getItemCount() {
return mMessages.size();
}
#Override
public int getItemViewType(int position) {
int type = -1;
if(mMessages.get(position).getDir().equals("left")) type = 1;
else if(mMessages.get(position).getDir().equals("right")) type = 0;
else if(mMessages.get(position).getDir().equals("typing")) type = 2;
return type;
//return position;
}
public class ViewHolder extends RecyclerView.ViewHolder {
private LinearLayout groupMessage;
//private ImageView typing;
public ViewHolder(View itemView) {
super(itemView);
groupMessage = (LinearLayout)itemView.findViewById(R.id.messages);
}
public void setGroupMessage(MessageList m) {
if (null == groupMessage) return;
int i = 0;
if(m.getMessageStatus() == false){
m.setMessageStatus(true);
for (String message : m.getMessageList()) {
//TextView text = new TextView(activity);
TextView text = new MyTextView(context);
LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
p.setMargins(0, 0, 0, 2);
if (m.getDir().equals("left")) {
text.setTextColor(Color.BLACK);
p.gravity = Gravity.LEFT;
if(m.getMessageList().size() == 1){
text.setBackgroundResource(R.drawable.message_left_default);
}
else if (i == 0) {
text.setBackgroundResource(R.drawable.message_left_first);
} else if (i + 1 == m.getMessageList().size()) {
text.setBackgroundResource(R.drawable.message_left_last);
} else {
text.setBackgroundResource(R.drawable.message_left);
}
} else{
p.gravity = Gravity.RIGHT;
text.setTextColor(Color.WHITE);
if(m.getMessageList().size() == 1){
text.setBackgroundResource(R.drawable.message_right_default);
}
else if (i == 0) {
text.setBackgroundResource(R.drawable.message_right_first);
} else if (i + 1 == m.getMessageList().size()) {
text.setBackgroundResource(R.drawable.message_right_last);
} else {
text.setBackgroundResource(R.drawable.message_right);
}
}
text.setLayoutParams(p);
text.setText(message);
text.setPadding(8, 8, 8, 8);
text.setTextSize(18f);
//text.setTextAppearance(context, android.R.style.TextAppearance_Large);
groupMessage.addView(text);
i++;
}
}
}
}
}
I solve it by remove
int type = -1;
if(mMessages.get(position).getDir().equals("left")) type = 1;
else if(mMessages.get(position).getDir().equals("right")) type = 0;
else if(mMessages.get(position).getDir().equals("typing")) type = 2;
return type;
from
getItemViewType
and return position
and put the first code
int type = -1;
if(mMessages.get(position).getDir().equals("left")) type = 1;
else if(mMessages.get(position).getDir().equals("right")) type = 0;
else if(mMessages.get(position).getDir().equals("typing")) type = 2;
return type;
in onCreateViewHolder and use viewType as the current position
I am setting the adapter of gridview on a fragment. this fragment is attached on the layout of view pager and viewpager is attached in an activity.
I have checked my arraylist data is refreshed but view is not refreshing.
My code is:
Setting the adapter in the onCreate of Activity::
for(ArrayList<Item> newLst : updateList){
newPropertySubList.add(newLst);
}
Log.e("newPropertySubList","newPropertySubList"+newPropertySubList.size());
adapter = new PropertyPagerAdapetr(getSupportFragmentManager());
//propertyViewPager.setAdapter(adapter);
adapter.notifyChangeInPosition(1);
propertyViewPager.setAdapter(adapter);
adapter.notifyDataSetChanged();
mIndicator.setViewPager(propertyViewPager);
PropertyPagerAdapetr is: in this code section GridviewFragment new instance is created when adapter is setting.
public class PropertyPagerAdapetr extends FragmentPagerAdapter {
private long baseId = 0;
public PropertyPagerAdapetr(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int arg0) {
return GridViewFragment.newInstance(newPropertySubList.get(arg0));
}
#Override
public long getItemId(int position) {
return baseId + position;
}
public void destroyAllItem(){
getSupportFragmentManager().getFragments().clear();
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public int getCount() {
if (newPropertySubList != null && newPropertySubList.size() > 0)
return newPropertySubList.size();
else
return 0;
}
public void notifyChangeInPosition(int n) {
// shift the ID returned by getItemId outside the range of all previous fragments
baseId += getCount() + n;
}
}
GridViewFragment: Gridview adapter is setting in this fragment
public class GridViewFragment extends Fragment {
public static final String PROPERTY_TYPE = "property_type";
private GridView mImageGrid;
private View view;
ArrayList<Item> itemList;
String forRentOrSale;
double belowheight;
private GridLayout gLayout;
//int count;
//static Context mContext;
public static GridViewFragment newInstance(ArrayList<Item> propertyList) {
GridViewFragment frag = new GridViewFragment();
Bundle bundle = new Bundle();
bundle.putSerializable("Property_item", propertyList);
frag.setArguments(bundle);
return frag;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.grid_view_fragmnet, container, false);
mImageGrid = (GridView) rootView.findViewById(R.id.gridview);
itemList = (ArrayList<Item>) getArguments().getSerializable(
"Property_item");
LoadPropertyAdapter adapter = new LoadPropertyAdapter(getActivity());
mImageGrid.setAdapter(adapter);
//mImageGrid.setAdapter(new MyAdapter());
return rootView;
//return (view = inflater.inflate(R.layout.grid_view_fragmnet, null));
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
belowheight = (((SearchForm) getActivity()).belowHeight / 2);
initView();
initData();
setListener();
}
private void setListener() {
mImageGrid.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// Toast.makeText(getActivity(),
// ""+itemList.get(position).getPID()+" "+itemList.get(position).getA2(),
// Toast.LENGTH_LONG).show();
if (Constants.g_Setttings.getApp_google_analytics() != null
&& !Constants.g_Setttings.getApp_google_analytics().equals("")) {
TVApplication dApp = (TVApplication) getActivity().getApplication();
Tracker tracker = dApp.getTracker(TrackerName.APP_TRACKER,
Constants.g_Setttings.getApp_google_analytics());
tracker.setScreenName("/Search Form");
tracker.set(Fields.SCREEN_NAME, "Search Form");
tracker.send(new HitBuilders.AppViewBuilder().build());
}
Intent intent = new Intent(getActivity(),
PropertyDetailActivity.class);
Item item = itemList.get(position);
intent.putExtra(Constants.ACCESS_DETAIL_PAGE_KEY,
item);
if (((SearchForm) getActivity()).boolSale) {
intent.putExtra(PROPERTY_TYPE, "for sale");
} else if (((SearchForm) getActivity()).boolRent) {
intent.putExtra(PROPERTY_TYPE, "to rent");
} else if (((SearchForm) getActivity()).boolStudentRent) {
intent.putExtra(PROPERTY_TYPE, "to rent");
}
startActivity(intent);
}
});
}
private void initView() {
//mImageGrid = (GridView) view.findViewById(R.id.gridview);
// gLayout=(GridLayout) view.findViewById(R.id.gridlayout);
/*itemList = (ArrayList<Item>) getArguments().getSerializable(
"Property_item");
LoadPropertyAdapter adapter = new LoadPropertyAdapter();
mImageGrid.setAdapter(adapter);*/
}
private void initData() {
if (itemList == null || itemList.size() == 0)
return;
// setUpGridLayout();
/*
* ViewGroup.LayoutParams layoutParams = mImageGrid.getLayoutParams();
* layoutParams.height = (int)
* (((SearchForm)getActivity()).belowHeight/2); //this is in pixels
* mImageGrid.setLayoutParams(layoutParams);
*/
}
}
public class LoadPropertyAdapter extends BaseAdapter {
private Item propertyItem;
Context mContext;
Holder holder = null;
DisplayImageOptions options;
ImageLoader imageLoader;
ImageLoaderConfiguration config;
public LoadPropertyAdapter(FragmentActivity activity) {
mContext = activity;
imageLoader = ImageLoader.getInstance();
config = new ImageLoaderConfiguration.Builder(mContext)
.memoryCache(new WeakMemoryCache())
.denyCacheImageMultipleSizesInMemory()
.threadPoolSize(1)
.build();
options = new DisplayImageOptions.Builder()
.cacheOnDisc()
.resetViewBeforeLoading()
.bitmapConfig(Bitmap.Config.RGB_565)
.imageScaleType(ImageScaleType.IN_SAMPLE_INT)
.build();
imageLoader.init(config);
}
#Override
public int getCount() {
if (itemList != null && itemList.size() > 0)
return itemList.size();
else
return 0;
}
#Override
public Object getItem(int arg0) {
return itemList.get(arg0);
}
#Override
public long getItemId(int arg0) {
return arg0;
}
public String imageUrl() {
String imageUrl = "";
/*
* if (nm_item.m_bIsAdvert) { imageUrl =
* Constants.advertContainer.getImages_url() + "&file=" +
* Constants.advertContainer.getGen_advert()
* .get(nm_item.m_nIndex).getsca_image(); } else {
*/
imageUrl = Constants.getRequestUrl(propertyItem.getPID(), 1,
Constants.FLOORPLANS_IMAGE_BIG_URL, "");
// }
return imageUrl;
}
public class Holder
{
TextView priceText,content, feesApply, cornerLabel;
ImageView imageview;
RelativeLayout propertyStatusBG, propertyInfoView, layout;
ProgressBar progressbar ;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View rowView = null;
propertyItem = itemList.get(position);
if (rowView == null) {
// If convertView is null then inflate the appropriate layout file
rowView = LayoutInflater.from(mContext).inflate( R.layout.grid_view_imageviewitem , null);
holder = new Holder();
rowView.setTag(holder);
}else{
holder = (Holder) rowView.getTag();
}
//rowView = new View(getActivity());
holder.imageview = (ImageView) rowView
.findViewById(R.id.img_property);
holder.priceText = (TextView) rowView
.findViewById(R.id.pricetext);
holder.content = (TextView) rowView
.findViewById(R.id.contenttext);
holder.feesApply = (TextView) rowView
.findViewById(R.id.txt_fees_rent);
holder.propertyStatusBG = (RelativeLayout) rowView
.findViewById(R.id.rel_status_bg);
holder.cornerLabel = (TextView) rowView
.findViewById(R.id.txt_property_offer);
holder.progressbar = (ProgressBar) rowView
.findViewById(R.id.progressbar);
holder.propertyInfoView = (RelativeLayout) rowView
.findViewById(R.id.property_info_view);
//holder.imageview.setTag(imageUrl());
if (Constants.filter_Parameter != null
&& (Constants.filter_Parameter.getGoal().equals("2")
|| Constants.filter_Parameter.getGoal().equals(
"3") || Constants.filter_Parameter
.getGoal().equals("5"))) {
if (Constants.g_Setttings != null
&& Constants.g_Setttings.getIncl_tenantfeesinfo() != null
&& Constants.g_Setttings.getIncl_tenantfeesinfo()
.equals("1")) {
if (propertyItem.getTenant_fee_exempt() != null
&& propertyItem.getTenant_fee_exempt().equals("0")) {
holder.feesApply.setVisibility(View.VISIBLE);
} else {
holder.feesApply.setVisibility(View.GONE);
}
} else {
holder.feesApply.setVisibility(View.GONE);
}
} else {
holder.feesApply.setVisibility(View.GONE);
}
if (holder.feesApply != null) {
holder.feesApply.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(),
TenentFeeDialogActivity.class);
startActivity(intent);
}
});
}
Util.setButtonBackgroundColor(holder.propertyStatusBG);
// propertyStatusBG.getBackground().setAlpha(88);
Util.setButtonBackgroundColor(holder.cornerLabel);
if (propertyItem.getStatus() != null && !propertyItem.getStatus().equals("")) {
updatePropertyStatus(propertyItem.getStatus(), holder.cornerLabel,
holder.propertyStatusBG);
} else {
holder.propertyStatusBG.setVisibility(View.GONE);
}
if (propertyItem.getPR() != null
&& !propertyItem.getPR().equals("")) {
double price = Math.round(Double.parseDouble(propertyItem
.getPR()));
NumberFormat format = NumberFormat.getCurrencyInstance();
format.setMinimumFractionDigits(0);
format.setCurrency(Currency.getInstance(Locale.UK));
if (propertyItem.getLetRentFrequency() != null
&& !propertyItem.getLetRentFrequency().equals("")
&& (Constants.filter_Parameter.getGoal().equals("2") || Constants.filter_Parameter
.getGoal().equals("3"))) {
if (Constants.OPTIONS_FREQUENCY.equals("")) {
holder.priceText.setText(format.format(price) + " "
+ Constants.OPTIONS_FREQUENCY
);
} else {
holder.priceText.setText(format.format(price) + " "
+ propertyItem.getLetRentFrequency());
}
}
else if (Constants.g_Setttings.getApp_property_commercial() != null
&& Constants.g_Setttings.getApp_property_commercial()
.equals("1")) {
if ((Constants.g_Setttings
.getIncl_property_commercial_sales() != null && Constants.g_Setttings
.getIncl_property_commercial_sales().equals("1"))
|| Constants.g_Setttings
.getIncl_property_commercial_rent() != null
&& Constants.g_Setttings
.getIncl_property_commercial_rent().equals(
"1")) {
if (Constants.OPTIONS_FREQUENCY.equals("")) {
holder.priceText.setText(format.format(price) + " "
+ Constants.OPTIONS_FREQUENCY
);
} else {
holder.priceText.setText(format.format(price) + " "
+ propertyItem.getLetRentFrequency());
}
}
} else {
holder.priceText.setText(format.format(price));
}
}
String contentText = "";
String propertyTypeCode = propertyItem.getPT();
String propertyType = "";
if (propertyTypeCode != null && !propertyTypeCode.equals("")
&& !propertyTypeCode.equals("null")
&& !propertyTypeCode.equals("0")) {
if (Constants.propertyTypeList != null
&& Constants.propertyTypeList.size() > 0) {
for (int i = 0; i < Constants.propertyTypeList.size(); i++) {
if (Constants.propertyTypeList.get(i).getId() == Integer
.parseInt(propertyTypeCode)) {
propertyType = Constants.propertyTypeList.get(i)
.getLabel();
break;
}
}
} else {
propertyType = "";
}
} else {
propertyType = "";
}
initRentOrSale();
if (propertyItem.getBD() != null
&& !propertyItem.getBD().equals("")) {
if (propertyItem.getBD().equals("0")) {
if (!propertyType.equals("")) {
contentText = propertyType + " " + forRentOrSale + " ";
} else {
contentText = forRentOrSale + " ";
}
} else {
if (!propertyType.equals("")) {
contentText += propertyItem.getBD() + " bed "
+ propertyType + " " + forRentOrSale + " ";
} else {
contentText += propertyItem.getBD() + " bed "
+ forRentOrSale + " ";
}
}
}
if (propertyItem.getA2() != null
&& !propertyItem.getA2().equals("")) {
contentText += "in "
+ Html.fromHtml(StringEscapeUtils
.unescapeHtml(propertyItem.getA2())) + " ";
}
if (contentText != null && !contentText.equals("")) {
holder.content.setText(contentText);
}
imageLoader.displayImage(imageUrl(), holder.imageview,options, new ImageLoadingListener(){
#Override
public void onLoadingStarted(String imageUri, View view) {
holder.progressbar.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingFailed(String imageUri, View view,
FailReason failReason) {
holder.progressbar.setVisibility(View.GONE);
}
#Override
public void onLoadingComplete(String imageUri, View view,
Bitmap loadedImage) {
holder.progressbar.setVisibility(View.GONE);
}
#Override
public void onLoadingCancelled(String imageUri, View view) {
holder.progressbar.setVisibility(View.GONE);
}
});
holder.layout = new RelativeLayout(getActivity());
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
(int) (belowheight / 1.1));
holder.layout.addView(rowView, params);
holder.propertyInfoView.getLayoutParams().height = (int) (belowheight / 4.60);
return holder.layout;
}
}
}
Could be you're mixing GridLayout and GridView. They are different entities.
In setUpGridLayout() you are inflating a grid_view_imageviewitem and adding it to a GridLayout, not GridView.
*
i have solve the issue using
Handler disconnectHandler = new Handler() {
public void handleMessage(Message msg) {
}
};
Runnable disconnectCallback = new Runnable() {
#Override
public void run() {
/////////// load data from here ////
}
}
};
disconnectHandler.postDelayed(disconnectCallback, 1000);*
*
I'm always getting this error when i'm setting the finish method inside adapter.
11-28 09:46:09.661 8636-8646/? E/art: Failed sending reply to debugger: Broken pipe
11-28 09:46:17.709 8636-8636/com.juandirection E/InputEventReceiver: Exception dispatching input event.
11-28 09:46:17.709 8636-8636/com.juandirection E/MessageQueue-JNI: Exception in MessageQueue callback: handleReceiveCallback
11-28 09:46:17.709 8636-8636/com.juandirection E/MessageQueue-JNI: java.lang.ClassCastException: com.juandirection.variables.Global cannot be cast to com.juandirection.ActivityCategorySelected
I tried to remove all item insde OnRatingChanged but the error remains the same.
public class AdapterPOI extends RecyclerView.Adapter<AdapterPOI.MainViewHolder> {
private List<ModelPoi> poiDatas;
private List<ModelImage> imageDatas;
private List<ModelComments> commentDatas;
private List<ModelFavorite> favoriteDatas;
private List<ModelAccounts> accountDatas;
private LayoutInflater inflater;
private Context context;
int viewType = 0;
int add;
int cCounter = 0;
int[] routeImg = {R.drawable.ic_resto_route, R.drawable.ic_sights_route, R.drawable.ic_transport_route, R.drawable.ic_hotel_route,
R.drawable.ic_gas_route, R.drawable.ic_school_route, R.drawable.ic_entertainment_route,
R.drawable.ic_shop_route, R.drawable.ic_atm_route, R.drawable.ic_bank_route, R.drawable.ic_hospital_route,
R.drawable.ic_pharmacy_route, R.drawable.ic_police_route, R.drawable.ic_toilet_route,};
public AdapterPOI(Context context, List<ModelPoi> poiDatas, List<ModelFavorite> favoriteDatas, List<ModelComments> commentDatas, List<ModelImage> imageDatas) {
inflater = LayoutInflater.from(context);
this.poiDatas = poiDatas;
this.context = context;
this.favoriteDatas = favoriteDatas;
this.imageDatas = imageDatas;
this.commentDatas = commentDatas;
}
#Override
public MainViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
int listViewItemType = getItemViewType(viewType);
if (listViewItemType == 0) {
return new TitleHolder(LayoutInflater.from(context).inflate(R.layout.custom_row_title, parent, false));
}
if (listViewItemType == 1 || listViewItemType == 4 || listViewItemType == 7) {
return new HeaderHolder(LayoutInflater.from(context).inflate(R.layout.headerinformation, parent, false));
}
if (listViewItemType == 2 || listViewItemType == 3 || listViewItemType == 6) {
return new MyViewHolder(LayoutInflater.from(context).inflate(R.layout.custom_row_pictext, parent, false));
}
if (listViewItemType == 5) {
return new GalleryHolder(LayoutInflater.from(context).inflate(R.layout.custom_row_photos, parent, false));
}
if (listViewItemType == 8) {
return new RatingHolder(LayoutInflater.from(context).inflate(R.layout.custom_row_rating, parent, false));
}
if (listViewItemType >= 9 && listViewItemType <= 8 + commentDatas.size()) {
return new CommentsHolder(LayoutInflater.from(context).inflate(R.layout.custom_row_comments, parent, false));
}
if (listViewItemType == 14) {
return new MyViewHolder(LayoutInflater.from(context).inflate(R.layout.custom_row_pictext, parent, false));
}
if (listViewItemType >= 9 + commentDatas.size()) {
return new TapHolder(LayoutInflater.from(context).inflate(R.layout.custom_row_taptorate, parent, false));
}
return null;
}
#Override
public void onBindViewHolder(MainViewHolder holder, int position) {
try {
if (position == 0) {
TitleHolder tHolder = (TitleHolder) holder;
tHolder.imgType.setBackgroundResource(routeImg[Global.getPosition]);
tHolder.txtTitle.setText(Global.selectedPOI);
ModelPoi poiData = (ModelPoi) getPOI(0);
tHolder.txtType.setText(poiData.POIType);
if (favoriteDatas.size() >= 1) {
tHolder.imgFavorite.setBackgroundResource(R.drawable.ic_favorite_yellow);
tHolder.txtID.setText("1");
} else {
tHolder.imgFavorite.setBackgroundResource(R.drawable.ic_favorite_white);
tHolder.txtID.setText("0");
}
float ratingBar = 0f;
for (int i = 0; i < commentDatas.size(); i++) {
ModelComments modelComments = (ModelComments) getComment(i);
ratingBar += Float.valueOf(modelComments.rating);
}
float finalRating;
finalRating = ratingBar / commentDatas.size();
tHolder.ratingBar.setRating(finalRating);
}
if (position == 1) {
HeaderHolder hHolder = (HeaderHolder) holder;
hHolder.txtInfo.setText("Information");
}
if (position == 2) {
MyViewHolder mHolder = (MyViewHolder) holder;
ModelPoi poiData = (ModelPoi) getPOI(0);
mHolder.icon.setImageResource(R.drawable.ic_information);
mHolder.title.setText(poiData.POIInfo);
mHolder.txtID.setText("0");
}
if (position == 3) {
MyViewHolder mHolder = (MyViewHolder) holder;
ModelPoi poiData = (ModelPoi) getPOI(0);
mHolder.icon.setImageResource(R.drawable.ic_place_black_36dp);
mHolder.title.setText(poiData.POIAddress);
mHolder.txtID.setText("1");
}
if (position == 4) {
HeaderHolder hHolder = (HeaderHolder) holder;
hHolder.txtInfo.setText("Photos");
}
if (position == 5) {
GalleryHolder gHolder = (GalleryHolder) holder;
AdapterGalleryViewPoi galleryViewAdapter;
galleryViewAdapter = new AdapterGalleryViewPoi(context, imageDatas);
gHolder.gallery.setAdapter(galleryViewAdapter);
final WindowManager display = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics metrics = new DisplayMetrics();
display.getDefaultDisplay().getMetrics(metrics);
ViewGroup.MarginLayoutParams mlp = (ViewGroup.MarginLayoutParams) gHolder.gallery.getLayoutParams();
mlp.setMargins(-((metrics.widthPixels * 2 + 200) / 3), mlp.topMargin,
mlp.rightMargin, mlp.bottomMargin);
}
if (position == 6) {
MyViewHolder mHolder = (MyViewHolder) holder;
mHolder.icon.setImageResource(R.drawable.ic_local_see_black_24dp);
mHolder.title.setText("Add Photos");
mHolder.txtID.setText("2");
}
if (position == 7) {
HeaderHolder hHolder = (HeaderHolder) holder;
hHolder.txtInfo.setText("Reviews");
}
if (position == 8) {
RatingHolder mHolder = (RatingHolder) holder;
float ratingBar = 0f;
float getRate;
int progressbarE = 0, progressbarVG = 0, progressbarAVG = 0, progressbarP = 0, progressbarT = 0;
for (int i = 0; i < commentDatas.size(); i++) {
ModelComments modelComments = (ModelComments) getComment(i);
ratingBar += Float.valueOf(modelComments.rating);
getRate = Float.valueOf(modelComments.rating);
if (getRate >= 0 && getRate <= 1) {
progressbarT += getRate;
}
if (getRate > 1 && getRate <= 2) {
progressbarP += getRate;
}
if (getRate > 2 && getRate <= 3) {
progressbarAVG += getRate;
}
if (getRate > 3 && getRate <= 4) {
progressbarVG += getRate;
}
if (getRate > 4 && getRate <= 5) {
progressbarE += getRate;
}
}
mHolder.reviewTxt.setText(Global.selectedPOI);
float finalRatingBar;
finalRatingBar = ratingBar / commentDatas.size();
mHolder.ratingBarReview.setRating(finalRatingBar);
mHolder.progressbarE.setProgress(progressbarE);
mHolder.progressbarVG.setProgress(progressbarVG);
mHolder.progressbarAVG.setProgress(progressbarAVG);
mHolder.progressbarP.setProgress(progressbarP);
mHolder.progressbarT.setProgress(progressbarT);
}
if (position >= 9 && position <= 8 + commentDatas.size()) {
if (position == 9) {
cCounter = 0;
}
if (position == 10) {
cCounter = 1;
}
if (position == 11) {
cCounter = 2;
}
if (position == 12) {
cCounter = 3;
}
if (position == 13) {
cCounter = 4;
}
ModelComments modelComments = (ModelComments) getComment(cCounter);
CommentsHolder mHolder = (CommentsHolder) holder;
accountDatas = new Select().from(ModelAccounts.class)
.where(Condition.column(ModelAccounts$Table.GET_ID).is(modelComments.user_id)).queryList();
ModelAccounts modelAccounts = (ModelAccounts) getImg(0);
byte[] dataImg;
dataImg = Base64.decode(modelAccounts.img, Base64.DEFAULT);
Glide.with(context)
.load(dataImg)
.fitCenter()
.crossFade()
.into(mHolder.commentPhoto);
mHolder.commentTitle.setText(modelComments.title);
mHolder.commentDate.setText(modelComments.date);
mHolder.comments.setText(modelComments.comment);
mHolder.commentRatingbar.setRating(Float.valueOf(modelComments.rating));
mHolder.txtID.setText(modelComments.get_id);
}
if (commentDatas.size() == 5) {
if (position == 14) {
MyViewHolder mHolder = (MyViewHolder) holder;
mHolder.icon.setImageResource(R.drawable.ic_comment_black_24dp);
mHolder.title.setText("View More Comments");
mHolder.txtID.setText("3");
}
}
} catch (Exception e) {
Log.e("AdapterPOI", "" + e.toString());
}
}
public Object getImg(int position) {
return accountDatas.get(position);
}
public Object getPOI(int position) {
return poiDatas.get(position);
}
public Object getComment(int position) {
return commentDatas.get(position);
}
#Override
public int getItemCount() {
if (commentDatas.size() == 5) {
add = 16;
} else if (commentDatas.size() == 4) {
add = 14;
} else if (commentDatas.size() == 3) {
add = 13;
} else if (commentDatas.size() == 2) {
add = 12;
} else if (commentDatas.size() == 1) {
add = 11;
} else if (commentDatas.size() == 0) {
return add = 10;
}
return add;
}
#Override
public int getItemViewType(int position) {
if (position == 0) {
viewType = 0;
} else if (position == 1) {
viewType = 1;
} else if (position == 2) {
viewType = 2;
} else if (position == 3) {
viewType = 3;
} else if (position == 4) {
viewType = 4;
} else if (position == 5) {
viewType = 5;
} else if (position == 6) {
viewType = 6;
} else if (position == 7) {
viewType = 7;
} else if (position == 8) {
viewType = 8;
} else if (position == 9) {
viewType = 9;
} else if (position == 10) {
viewType = 10;
} else if (position == 11) {
viewType = 11;
} else if (position == 12) {
viewType = 12;
} else if (position == 13) {
viewType = 13;
} else if (position == 14) {
viewType = 14;
} else if (position == 15) {
viewType = 15;
}
return viewType;
}
class MyViewHolder extends MainViewHolder {
TextView title, txtID;
ImageView icon;
public MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.poiName);
txtID = (TextView) itemView.findViewById(R.id.txtID);
icon = (ImageView) itemView.findViewById(R.id.poiIcon);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String getText = txtID.getText().toString();
String getTitle = title.getText().toString();
if (getText.equalsIgnoreCase("0")) {
Global.getInfo = getTitle;
Intent intent = new Intent(context, ViewInformation.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
if (getText.equalsIgnoreCase("1")) {
Log.e("Info", "Map");
}
if (getText.equalsIgnoreCase("2")) {
Log.e("Add Photo", "Add Photo");
}
if (getText.equalsIgnoreCase("3")) {
Global.getID = null;
Intent intent = new Intent(context, ViewComment.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
}
});
}
}
public class HeaderHolder extends MainViewHolder {
TextView txtInfo;
public HeaderHolder(View itemView) {
super(itemView);
this.txtInfo = (TextView) itemView.findViewById(R.id.txtinfo);
}
}
public class GalleryHolder extends MainViewHolder {
Gallery gallery;
public GalleryHolder(View itemView) {
super(itemView);
this.gallery = (Gallery) itemView.findViewById(R.id.gallery);
}
}
public class TapHolder extends MainViewHolder {
RatingBar ratingBar;
public TapHolder(View itemView) {
super(itemView);
this.ratingBar = (RatingBar) itemView.findViewById(R.id.tapToRate);
this.ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
#Override
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
Global.setRating = rating;
Intent intent = new Intent(context, ActivityReview.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
//((ActivityCategorySelected)context).finish();
}
});
}
}
public class TitleHolder extends MainViewHolder {
ImageView imgType, imgFavorite;
TextView txtTitle, txtID, txtType;
RatingBar ratingBar;
public TitleHolder(View itemView) {
super(itemView);
final View view;
view = itemView;
imgType = (ImageView) itemView.findViewById(R.id.imgType);
imgFavorite = (ImageView) itemView.findViewById(R.id.imgFavorite);
txtTitle = (TextView) itemView.findViewById(R.id.txtTitle);
txtType = (TextView) itemView.findViewById(R.id.txtType);
txtID = (TextView) itemView.findViewById(R.id.txtID);
ratingBar = (RatingBar) itemView.findViewById(R.id.ratingBar);
imgFavorite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String getID = txtID.getText().toString();
final String getType = txtType.getText().toString();
if (Global.getUserId == null) {
AlertDialog.Builder alertbox = new AlertDialog.Builder(v.getRootView().getContext());
alertbox.setTitle("Sign In");
alertbox.setMessage("Please Sign in your account first.");
alertbox.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0,
int arg1) {
Intent intent = new Intent(context, ActivityLogin.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
alertbox.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0,
int arg1) {
}
});
alertbox.show();
} else {
if (getID.equals("0")) {
AlertDialog.Builder alertbox = new AlertDialog.Builder(v.getRootView().getContext());
alertbox.setTitle("Add This place to your Favorites?");
alertbox.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0,
int arg1) {
if (CheckNetwork.isNetworkAvailable(context)) {
txtID.setText("1");
imgFavorite.setBackgroundResource(R.drawable.ic_favorite_yellow);
addToFavorite(getType);
Thread timerThread = new Thread() {
public void run() {
try {
new DatabaseAsyncFavorites(context).execute();
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
timerThread.start();
} else {
Snackbar.make(view, "No Internet Access. Pease Connect to the Internet.", Snackbar.LENGTH_LONG).show();
}
}
});
alertbox.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0,
int arg1) {
}
});
alertbox.show();
} else {
AlertDialog.Builder alertbox = new AlertDialog.Builder(v.getRootView().getContext());
alertbox.setTitle("Remove this place from your Favorites?");
alertbox.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0,
int arg1) {
if (CheckNetwork.isNetworkAvailable(context)) {
addToFavorite(getType);
new Delete()
.from(ModelFavorite.class)
.where(Condition.column(ModelFavorite$Table.USER_ID).is(Global.getUserId))
.and(Condition.column(ModelFavorite$Table.LATITUDE).is(Global.lat)).query();
txtID.setText("0");
imgFavorite.setBackgroundResource(R.drawable.ic_favorite_white_nav);
} else {
Snackbar.make(view, "No Internet Access. Pease Connect to the Internet.", Snackbar.LENGTH_LONG).show();
}
}
});
alertbox.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0,
int arg1) {
}
});
alertbox.show();
}
}
}
});
}
}
public void addToFavorite(final String getType) {
RequestQueue requestQueue = Volley.newRequestQueue(context);
StringRequest request = new StringRequest(Request.Method.POST, Global.INSERT_FAV_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("latitude", Global.lat);
parameters.put("user_id", Global.getUserId);
parameters.put("type", getType);
return parameters;
}
};
requestQueue.add(request);
}
public class RatingHolder extends MainViewHolder {
TextView reviewTxt;
RatingBar ratingBarReview;
ProgressBar progressbarE, progressbarVG, progressbarAVG, progressbarP, progressbarT;
public RatingHolder(View itemView) {
super(itemView);
this.reviewTxt = (TextView) itemView.findViewById(R.id.reviewTxt);
this.ratingBarReview = (RatingBar) itemView.findViewById(R.id.ratingBarReview);
this.progressbarE = (ProgressBar) itemView.findViewById(R.id.progressbarE);
this.progressbarVG = (ProgressBar) itemView.findViewById(R.id.progressbarVG);
this.progressbarAVG = (ProgressBar) itemView.findViewById(R.id.progressbarAVG);
this.progressbarP = (ProgressBar) itemView.findViewById(R.id.progressbarP);
this.progressbarT = (ProgressBar) itemView.findViewById(R.id.progressbarT);
}
}
public class CommentsHolder extends MainViewHolder {
ImageView commentPhoto;
TextView commentTitle, commentDate, comments, txtID;
RatingBar commentRatingbar;
public CommentsHolder(View itemView) {
super(itemView);
this.commentPhoto = (ImageView) itemView.findViewById(R.id.commentPhoto);
this.commentTitle = (TextView) itemView.findViewById(R.id.commentTitle);
this.commentDate = (TextView) itemView.findViewById(R.id.commentDate);
this.comments = (TextView) itemView.findViewById(R.id.comments);
this.txtID = (TextView) itemView.findViewById(R.id.txtID);
this.commentRatingbar = (RatingBar) itemView.findViewById(R.id.commentRatingbar);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Global.getID = txtID.getText().toString();
Intent intent = new Intent(context, ViewComment.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
}
}
public class MainViewHolder extends RecyclerView.ViewHolder {
public MainViewHolder(View itemView) {
super(itemView);
}
}
}
I don't know what's causing the problem. I can use the same method on my fragments but in this adapter it's not working.
Change
adapter = new AdapterPOI(getApplicationContext(), ....)
to
adapter = new AdapterPOI(this, ....)
in the code where you call the adapter's constructor. You get the error because getApplicationContext() cannot be casted to an ActivityCategorySelected. That's an Application context; whereas the adapter is expecting an Activity's context.
Let me explain in brief.
I have 2 Fragments:
1) Fragment A where user enters some text. here i have also defined 5 buttons each of different colors. From here, the entered text is added to database.
2) Fragment B which has a listview which populates data from that database using customadapter when user click the "Save" button in Fragment A.
Everything is working fine. Data is being saved, loaded into Listview and all. Now remember those 5 buttons with 5 different colors?
What I Want is that suppose while adding data in Fragment A, user selected button with color "Orange" suppose, then the row that will be inflated in getView() method of adapter should also have its background orange.
(Something ike Google Keep)
Is that possible?
My Adapter class :
public class notesAdapter extends BaseAdapter {
ArrayList<notesSingleRow> notes;
Context context;
View convertView;
private static final String TAG = "SampleAdapter";
private final LayoutInflater mLayoutInflater;
private final Random mRandom;
private SparseBooleanArray mSelectedItemsIds;
private static final SparseArray<Double> sPositionHeightRatios = new SparseArray<Double>();
public notesAdapter(Context context, ArrayList<notesSingleRow> notes) {
this.notes = notes;
this.context = context;
this.mLayoutInflater = LayoutInflater.from(context);
this.mRandom = new Random();
}
#Override
public int getCount() {
return notes.size();
}
#Override
public Object getItem(int position) {
return notes.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView,
final ViewGroup parent) {
this.convertView = convertView;
ViewHolder vh;
if (convertView == null) {
convertView = mLayoutInflater.inflate(R.layout.notes_single_row, parent, false);
vh = new ViewHolder();
convertView.setTag(vh);
} else {
vh = (ViewHolder) convertView.getTag();
}
vh.txtView = detail(convertView, R.id.notes_grid_text, notes.get(position).getNotes());
vh.notes_title = detail(convertView, R.id.note_title_added, notes.get(position).getNotesTitle());
int len = vh.txtView.length();
if (len == 1 || len ==2){
vh.txtView.setTextSize(100);
}
else if (len == 3){
vh.txtView.setTextSize(80);
}
else if (len == 4){
vh.txtView.setTextSize(60);
}
else if (len ==5){
vh.txtView.setTextSize(50);
}
else if (len == 8){
vh.txtView.setTextSize(60);
}
double positionHeight = getPositionRatio(position);
vh.txtView.setHeightRatio(positionHeight);
vh.notes_title.setHeightRatio(positionHeight);
vh.notes_title.setPaintFlags(vh.notes_title.getPaintFlags()| Paint.UNDERLINE_TEXT_FLAG);
/* if ((position == 0 || position == 5 || position == 10 || position ==15)) {
convertView.setBackgroundColor(Color.rgb(255, 112, 67));
} else if (position == 1 || position == 6 || position == 11 || position ==16) {
convertView.setBackgroundColor(Color.rgb(29, 233, 182));
} else if (position == 2 || position == 7 || position == 12 || position ==17) {
convertView.setBackgroundColor(Color.rgb(121, 134, 203));
} else if (position == 3 || position == 8 || position == 13 || position ==18) {
convertView.setBackgroundColor(Color.rgb(205, 220, 57));
} else if (position == 4 || position == 9 || position == 14 || position ==19) {
convertView.setBackgroundColor(Color.rgb(224, 64, 251));
}*/
return convertView;
}
public void changeColorToOrange() {
convertView.setBackgroundColor(Color.rgb(255, 112, 67));
}
static class ViewHolder {
DynamicHeightTextView txtView, notes_title;
}
private double getPositionRatio(final int position) {
double ratio = sPositionHeightRatios.get(position, 0.0);
if (ratio == 0) {
ratio = getRandomHeightRatio();
sPositionHeightRatios.append(position, ratio);
Log.d(TAG, "getPositionRatio:" + position + " ratio:" + ratio);
}
return ratio;
}
private double getRandomHeightRatio() {
return (mRandom.nextDouble() / 2.4) + 0.8;
}
private DynamicHeightTextView detail(View v, int resId, String text) {
DynamicHeightTextView tv = (DynamicHeightTextView) v.findViewById(resId);
tv.setText(text);
return tv;
}
public void toggleSelection(int position) {
selectView(position, !mSelectedItemsIds.get(position));
}
public void selectView(int position, boolean value) {
if (value)
mSelectedItemsIds.put(position, value);
else
mSelectedItemsIds.delete(position);
notifyDataSetChanged();
}
user add text in this fragment with buttons of different colors:
public class add_note_frag extends Fragment implements View.OnClickListener {
EditText note, noteTitle;
String user_note, user_note_title;
Button svenote;
ImageView ora, vio, yel, pin;
RelativeLayout rel;
ActionBar ab;
notesAdapter adapter;
private ArrayList<notesSingleRow> notes = new ArrayList<notesSingleRow>();
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.add_notes_fragment, container, false);
return view;
}
#Override
public void onResume() {
super.onResume();
ab = getActivity().getActionBar();
ab.setDisplayHomeAsUpEnabled(true);
rel = (RelativeLayout) getActivity().findViewById(R.id.notes_rel_lay);
note = (EditText) getActivity().findViewById(R.id.note);
noteTitle = (EditText) getActivity().findViewById(R.id.note_title);
svenote = (Button) getActivity().findViewById(R.id.savenote);
adapter = new notesAdapter(getActivity(), notes);
ora = (ImageView) getActivity().findViewById(R.id.orange);
vio = (ImageView) getActivity().findViewById(R.id.violet);
yel = (ImageView) getActivity().findViewById(R.id.yellow);
pin = (ImageView) getActivity().findViewById(R.id.pink);
ora.setOnClickListener(this);
vio.setOnClickListener(this);
yel.setOnClickListener(this);
pin.setOnClickListener(this);
svenote.setOnClickListener(this);
}
public void saveNote() {
tasks_Database_Operations tasksDatabaseOperations = new tasks_Database_Operations(getActivity());
user_note = note.getText().toString();
user_note_title = noteTitle.getText().toString();
long id1 = tasksDatabaseOperations.insertNote(user_note, user_note_title);
if (id1 < 0) {
Log.e("HirakDebug", "add_task_frag failed insertData operation");
} else {
Log.d("HirakDebug", "Data sent to be inserted");
}
}
#Override
public void onClick(View v) {
if (v == svenote) {
saveNote();
goBackToNoteFrag();
ab.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.actionbar)));
}
if (v == ora) {
rel.setBackgroundColor(getResources().getColor(R.color.orange));
ab.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.orange)));
adapter.changeColorToOrange();
}
if (v == vio) {
rel.setBackgroundColor(getResources().getColor(R.color.violet));
ab.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.violet)));
}
if (v == yel) {
rel.setBackgroundColor(getResources().getColor(R.color.yellow));
ab.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.yellow)));
}
if (v == pin) {
rel.setBackgroundColor(getResources().getColor(R.color.pinkk));
ab.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.pinkk)));
}
}
public void goBackToNoteFrag() {
notesListFrag nLF = new notesListFrag();
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.setCustomAnimations(R.anim.slide_up, R.anim.slide_down);
ft.remove(this);
ft.replace(R.id.dynamic_content, nLF, "nLF");
ft.commit();
}
#Override
public void onDetach() {
super.onDetach();
ab.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.actionbar)));
}
It is possible.
Pass that selected color to Fragment B on button click.
Pass that color as an argument to the adapter constructor from fragment B.
Now you know the color inside the adapter.
In getView() function of the adapter, based on the color, change the background color of the inflated view. using : view.setBackgroundColor(color);
See the sample here : https://github.com/vishalvijay/SampleColorListView
As far as I think all you have to do is to save color hex code also in your database alongwith your text. It is more simple and scaleable. when you fetch text from database, you should also fetch the color in the same ArrayList of custom objects and then in getView method of your adapter, just apply the corresponding Hex color code to your convertView.
Following is my listview adapter classes using AlphabetIndexer.
It does not work when I add unicode chars (for hebrew) togather with the english.
I get exception in: getSectionForPosition. getting to index -1....
Tries it with 2 entries in the DB - 1 starting with hebrew char (unicode) and one with english. The first char for AlphabetIndexer was the unicode char.
Really really need help in this one....
public abstract class RecipeListViewAdapter extends SimpleCursorAdapter implements SectionIndexer
{
protected Context mContext;
protected Cursor mCursor;
private LayoutInflater mInflater;
public static final int TYPE_HEADER = 1;
public static final int TYPE_NORMAL = 0;
private static final int TYPE_COUNT = 2;
private AlphabetIndexer indexer;
private int[] usedSectionNumbers;
private Map<Integer, Integer> sectionToOffset;
private Map<Integer, Integer> sectionToPosition;
protected ImageLoader mImageLoader = new ImageLoader( MyApp.Instance() );
public RecipeListViewAdapter( Context context,
int layout,
Cursor c,
String[] from,
int[] to )
{
super(context, layout, c, from, to);
mContext = context;
mCursor = c;
mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
indexer = new AlphabetIndexer(c, c.getColumnIndexOrThrow("NAME"), "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
sectionToPosition = new TreeMap<Integer, Integer>();
sectionToOffset = new HashMap<Integer, Integer>();
final int count = super.getCount();
int i;
for( i = count - 1 ; i >= 0; i-- )
{
sectionToPosition.put(indexer.getSectionForPosition(i), i);
}
i = 0;
usedSectionNumbers = new int[sectionToPosition.keySet().size()];
for( Integer section : sectionToPosition.keySet() )
{
sectionToOffset.put(section, i);
usedSectionNumbers[i] = section;
i++;
}
for(Integer section: sectionToPosition.keySet())
{
sectionToPosition.put(section, sectionToPosition.get(section) + sectionToOffset.get(section));
}
}
#Override
public int getCount()
{
if( super.getCount() != 0 )
{
return super.getCount() + usedSectionNumbers.length;
}
return 0;
}
#Override
public Object getItem(int position)
{
if (getItemViewType(position) == TYPE_NORMAL) //we define this function later
{
return super.getItem( GetItemPosition( position ) );
}
return null;
}
public int GetItemPosition( final int position )
{
return position - sectionToOffset.get(getSectionForPosition(position)) - 1;
}
public int getPositionForSection(int section) {
if (! sectionToOffset.containsKey(section)){
int i = 0;
int maxLength = usedSectionNumbers.length;
while (i < maxLength && section > usedSectionNumbers[i]){
i++;
}
if (i == maxLength) return getCount();
return indexer.getPositionForSection(usedSectionNumbers[i]) + sectionToOffset.get(usedSectionNumbers[i]);
}
return indexer.getPositionForSection(section) + sectionToOffset.get(section);
}
public int getSectionForPosition(int position) {
int i = 0;
int maxLength = usedSectionNumbers.length;
while (i < maxLength && position >= sectionToPosition.get(usedSectionNumbers[i])){
i++;
}
return usedSectionNumbers[i-1];
}
public Object[] getSections() {
return indexer.getSections();
}
//nothing much to this: headers have positions that the sectionIndexer manages.
#Override
public int getItemViewType(int position) {
if (position == getPositionForSection(getSectionForPosition(position))){
return TYPE_HEADER;
} return TYPE_NORMAL;
}
#Override
public int getViewTypeCount() {
return TYPE_COUNT;
}
#Override
public View getView( int position,
View convertView,
ViewGroup parent )
{
final int type = getItemViewType(position);
if (type == TYPE_HEADER)
{
if (convertView == null)
{
convertView = mInflater.inflate(R.layout.header, parent, false);
}
((TextView)convertView.findViewById(R.id.header)).setText((String)getSections()[getSectionForPosition(position)]);
return convertView;
}
else
{
ViewHolder holder = new ViewHolder();
if (convertView == null)
{
convertView = mInflater.inflate(R.layout.recipes_list_view_entry, null);
holder.name = (TextView) convertView.findViewById( R.id.name_entry );
holder.author = (TextView) convertView.findViewById( R.id.username_entry );
holder.ratingBar = (RatingBar) convertView.findViewById( R.id.list_RatingBarId );
holder.userRatingBar = (RatingBar) convertView.findViewById( R.id.list_userRatingBarId );
holder.diffculty = (ImageView) convertView.findViewById( R.id.list_DifficultyImageViewId );
holder.preparationTime = (ImageView) convertView.findViewById( R.id.list_TimeImageViewId );
holder.recipePic = new DisplayableImageView( (ImageView) convertView.findViewById( R.id.list_RecipeImageViewId ) );
holder.name.setTypeface( MyApp.Fonts.ARIAL );
holder.name.setTextSize( MyApp.Fonts.RUNNING_TEXT_SIZE );
holder.name.setTextColor( Color.BLACK );
}
else
{
holder = (ViewHolder) convertView.getTag();
}
if( super.getItem( GetItemPosition(position) ) != null )
{
// Check if single
if( getCount() == position+1 && position == 1 )
{
convertView.setBackgroundResource( R.drawable.list_single );
}
else if( getItemViewType(position-1) == TYPE_HEADER )
{
// Check if single item in the middle of the list
if( getItemViewType(position+1) == TYPE_HEADER )
{
convertView.setBackgroundResource( R.drawable.list_single );
}
else if( position == getCount() - 1 )
{
convertView.setBackgroundResource( R.drawable.list_single );
}
else
{
convertView.setBackgroundResource( R.drawable.list_up );
}
}
else
{
// Middle or bottom
convertView.setBackgroundResource( R.drawable.list_middle );
//If not last
if( getCount() != position + 1 )
{
// Check if middle or down
if( getItemViewType(position+1) == TYPE_HEADER )
{
convertView.setBackgroundResource( R.drawable.list_down );
}
else
{
convertView.setBackgroundResource( R.drawable.list_middle );
}
}
else
{
// If it is last - use list_down
convertView.setBackgroundResource( R.drawable.list_down );
}
}
FillRecipeDataToHolder( GetItemPosition(position), holder );
convertView.setTag(holder);
}
else
{
holder = (ViewHolder)convertView.getTag();
}
return convertView;
}
}
//these two methods just disable the headers
#Override
public boolean areAllItemsEnabled() {
return false;
}
#Override
public boolean isEnabled(int position) {
if (getItemViewType(position) == TYPE_HEADER){
return false;
}
return true;
}
protected abstract void FillRecipeDataToHolder(int position, ViewHolder holder);
static class ViewHolder
{
TextView separator;
DisplayableImageView recipePic;
TextView name;
TextView author;
RatingBar ratingBar;
RatingBar userRatingBar;
ImageView diffculty;
ImageView preparationTime;
TextView serveCount;
}
}