Ho to change ListView items count? - java

I have a ListView with the sections. And when there is a section, then it takes the place of another. That is, if the ListView items count 30, the section takes the place of the first paragraph, and it turns out that the show only 29 points.
Here is a picture, which shows clearly
Tried TYPE_MAX_COUNT = 2, 3. Without confusing.
#Override
public int getViewTypeCount() {
return TYPE_MAX_COUNT;
}
I think getViewTypeCount() is triggered after getView().
private List<VacancyModel> vacancyModelList;
private LayoutInflater inflater;
private SQLHelper sqlHelper;
private static final int TYPE_SEPARATOR = 1;
private static final int TYPE_ITEM = 0;
private int rowType;
public static String saveLastDate;
private int newRecs = 0;
public SuitableAdapter(Context context, int resource, List<VacancyModel> objects) {
super(context, resource, objects);
vacancyModelList = objects;
sqlHelper = new SQLHelper(getContext());
inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#NonNull
#Override
public View getView(final int position, View convertView, #NonNull final ViewGroup parent) {
ViewHolder holder = null;
rowType = getItemViewType(position);
if (convertView == null) {
holder = new ViewHolder();
switch (rowType) {
case TYPE_SEPARATOR:
convertView = inflater.inflate(R.layout.suitable_separator_layout, null);
holder.headerTv = (TextView) convertView.findViewById(R.id.section_header);
break;
case TYPE_ITEM:
convertView = inflater.inflate(R.layout.row_layout, null);
holder.tvProfession = (TextView) convertView.findViewById(R.id.tvProfession);
holder.tvHeader = (TextView) convertView.findViewById(R.id.tvHeader);
holder.tvSalary = (TextView) convertView.findViewById(R.id.tvSalary);
holder.tvDate = (TextView) convertView.findViewById(R.id.tvPostCr);
break;
}
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if (getItemViewType(position) == TYPE_SEPARATOR) {
holder.headerTv = (TextView) convertView.findViewById(R.id.section_header);
if (newRecs == 1) {
holder.headerTv.setText("Новые вакансии");
newRecs = 0;
} else {
holder.headerTv.setText("Ранее просмотренные");
}
}
if (getItemViewType(position) == TYPE_ITEM) {
final VacancyModel model = vacancyModelList.get(position);
holder.tvProfession.setText(model.getProfession());
holder.tvHeader.setText(model.getHeader());
holder.tvSalary.setText(model.getSalary());
holder.tvDate.setText(model.getDate());
Date date;
try {
if (saveLastDate == null) {
saveLastDate = model.getDate();
} else {
date = stringToDate(saveLastDate);
if (date.before(stringToDate(model.getDate()))) {
saveLastDate = model.getDate();
}
}
} catch (ParseException e) {
e.printStackTrace();
}
}
return convertView;
}
#Override
public int getItemViewType(int position) {
if (GlobalData.LoadDate(getContext()) == null) {
return TYPE_ITEM;
} else {
VacancyModel model = getItem(position);
if (model != null) {
String newString = model.getDate();
String lastString = GlobalData.LoadDate(getContext());
Date newDate = null;
Date lastDate = null;
try {
newDate = stringToDate(newString);
lastDate = stringToDate(lastString);
} catch (ParseException e) {
e.printStackTrace();
}
assert newDate != null;
if (newDate.equals(lastDate)) {
return TYPE_SEPARATOR;
} else if (position == 0 && newDate.after(lastDate)) {
newRecs = 1;
return TYPE_SEPARATOR;
} else {
return TYPE_ITEM;
}
} else {
return TYPE_ITEM;
}
}
}
#Override
public int getViewTypeCount() {
return 3;
}
#Override
public int getCount() {
return vacancyModelList.size();
}
private Date stringToDate(String string) throws ParseException {
return new SimpleDateFormat(("yyyy-MM-dd HH:mm:ss"), Locale.getDefault()).parse(string);
}
private static class ViewHolder {
private TextView tvProfession;
private TextView tvHeader;
private TextView tvSalary;
private TextView tvDate;
private TextView headerTv;
}
VacancyModel
public class VacancyModel implements Serializable{
private String profession;
private String header;
private String salary;
private String date;
public VacancyModel() {
}
public String getProfession() {
return profession;
}
public void setProfession(String profession) {
this.profession = profession;
}
public String getHeader() {
return header;
}
public void setHeader(String header) {
this.header = header;
}
public String getSalary() {
if (salary.equals("0") || salary.isEmpty() || salary.equals("null")){
return "empty";
}
else {
return salary;
}
}
public void setSalary(String salary) {
this.salary = salary;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
Question: What I am doing wrong and how to change ListView`s count?

The listItem you are sending in should have the type field as well. So what I am suggesting is instead of doing date check manipulation inside listview. you can do it prior before adding data to RecyclerView.
Adding two more Field to your Serializable Data:
public class VacancyModel implements Serializable{
private String profession;
private String header;
private String salary;
private String date;
// set setter and getter for both, by default isHeading will be false,
private boolean isHeading;
private String heading;
public VacancyModel() {
}
public String getProfession() {
return profession;
}
public void setProfession(String profession) {
this.profession = profession;
}
public String getHeader() {
return header;
}
public void setHeader(String header) {
this.header = header;
}
public String getSalary() {
if (salary.equals("0") || salary.isEmpty() || salary.equals("null")){
return "empty";
}
else {
return salary;
}
}
public void setSalary(String salary) {
this.salary = salary;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
Do the following thing inside your activity inside activity:
private void generateListHeading(List<VacancyModel> original_vacany_list)
{
List<VacancyModel> vacancy_type_new_record;
VacancyModel model = new vacacyModel();
model.setIsHeading(true);
model.setHeading("New Record");
vacancy_type_new_record.add(model);
List<VacancyModel> vacancy_type_watched;
model = new vacacyModel();
model.setIsHeading(true);
model.setHeading("Watched");
vacancy_type_watched.add(model);
List<VacancyModel> new_vacancy_list;
for(VacanyModel data:original_vacany_list)
{
//do your date condition check here
if(data.getDate==newDate)
{
vacancy_type_new_record.add(data)
} else
{
vacancy_type_watched.add(data)
}
}
//once the whole condition check is add both list to new list
new_vacancy_list.addAll(vacancy_type_new_record);
new_vacancy_list.addAll(vacancy_type_watched);
//now the item count will be 32. in the format heading ,data ,heading,data
adapter.setUpdateddata(new_vacancy_list);
}
Adapter.class:
vacanyModelList = new ArrayList<>();
public SuitableAdapter(Context context, int resource) {
super(context, resource, objects);
//don't set your object in constructor
sqlHelper = new SQLHelper(getContext());
inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#NonNull
#Override
public View getView(final int position, View convertView, #NonNull final ViewGroup parent) {
ViewHolder holder = null;
rowType = getItemViewType(position);
if (convertView == null) {
holder = new ViewHolder();
switch (rowType) {
case TYPE_SEPARATOR:
convertView = inflater.inflate(R.layout.suitable_separator_layout, null);
holder.headerTv = (TextView) convertView.findViewById(R.id.section_header);
break;
case TYPE_ITEM:
convertView = inflater.inflate(R.layout.row_layout, null);
holder.tvProfession = (TextView) convertView.findViewById(R.id.tvProfession);
holder.tvHeader = (TextView) convertView.findViewById(R.id.tvHeader);
holder.tvSalary = (TextView) convertView.findViewById(R.id.tvSalary);
holder.tvDate = (TextView) convertView.findViewById(R.id.tvPostCr);
break;
}
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if (getItemViewType(position) == TYPE_SEPARATOR) {
holder.headerTv = (TextView) convertView.findViewById(R.id.section_header);
if (newRecs == 1) {
holder.headerTv.setText("Новые вакансии");
newRecs = 0;
} else {
holder.headerTv.setText("Ранее просмотренные");
}
}
if (getItemViewType(position) == TYPE_ITEM) {
final VacancyModel model = vacancyModelList.get(position);
holder.tvProfession.setText(model.getProfession());
holder.tvHeader.setText(model.getHeader());
holder.tvSalary.setText(model.getSalary());
holder.tvDate.setText(model.getDate());
Date date;
try {
if (saveLastDate == null) {
saveLastDate = model.getDate();
} else {
date = stringToDate(saveLastDate);
if (date.before(stringToDate(model.getDate()))) {
saveLastDate = model.getDate();
}
}
} catch (ParseException e) {
e.printStackTrace();
}
}
return convertView;
}
#Override
public int getItemViewType(int position) {
VacancyModel model = getItem(position);
if (model.isHeading) {
return TYPE_SEPARATOR;
} else {
return TYPE_ITEM;
}
}
}
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public int getCount() {
return vacancyModelList.size();
}
private Date stringToDate(String string) throws ParseException {
return new SimpleDateFormat(("yyyy-MM-dd HH:mm:ss"), Locale.getDefault()).parse(string);
}
private static class ViewHolder {
private TextView tvProfession;
private TextView tvHeader;
private TextView tvSalary;
private TextView tvDate;
private TextView headerTv;
}
public void setUpdatedData(List<VacancyModel> updated_list)
{
this.vacancyModelList = updated_list;
notifyDataSetChanged();
}

Related

problem with scrolling up or down of listview

When I try to take all the values of the NumberPicker, it correctly returns the ones in the middle, while the first and last returns only the last one that has been modified between them. I don't understand where I'm wrong.
public class piatto {
String nome;
String Descrizione;
String prezzo;
String immagine;
String tag;
public piatto(String nome, String Descrizione, String prezzo, String immagine, String tag) {
this.nome= nome;
this.Descrizione= Descrizione;
this.prezzo= prezzo;
this.immagine=immagine;
this.tag=tag;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getDescrizione() {
return Descrizione;
}
public void setDescrizione(String descrizione) {
Descrizione = descrizione;
}
public String getPrezzo() {
return prezzo;
}
public void setPrezzo(String prezzo) {
this.prezzo = prezzo;
}
public String getImmagine() {
return immagine;
}
public void setImmagine(String immagine) {
this.immagine = immagine;
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
}
this is my adapeter
public class ProductListAdapterforListView extends BaseAdapter {
private Context mContext;
private List<piatto> mProductList;
public ProductListAdapterforListView(Context mContext, List<piatto> mProductList) {
this.mContext = mContext;
this.mProductList = mProductList;
}
#Override
public int getCount() {
return mProductList.size();
}
#Override
public piatto getItem(int position) {
return mProductList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View listitemview ;
if (convertView==null){
listitemview = View.inflate(mContext, R.layout.row_data_list, null);
ImageView i = (ImageView) listitemview.findViewById(R.id.imagepiatto);
com.shawnlin.numberpicker.NumberPicker numberPicker = (com.shawnlin.numberpicker.NumberPicker) listitemview.findViewById(R.id.number_picker);
TextView n=(TextView) listitemview.findViewById(R.id.namepiatto);
TextView p=(TextView) listitemview.findViewById(R.id.prezzopiatto);
n.setText(mProductList.get(position).getNome());
p.setText(mProductList.get(position).getPrezzo()+" €");
Picasso.get().load(mProductList.get(position).getImmagine()).into(i);
} else {
listitemview=convertView;
}
return listitemview;
}
}
And this is my Java class where I get the values of the NumberPicker of each Item
#Override
public void onClick(View view) {
if (view.getId()==R.id.buttonnext){
Float totale = (float) 0.0;
String listapiatti="";
for (int i = 0; i < listView.getChildCount(); i++) {
view = listView.getChildAt(i);
TextView n = view.findViewById(R.id.namepiatto);
String nome = n.getText().toString();
TextView p = view.findViewById(R.id.prezzopiatto);
String pricestr = p.getText().toString();
String[] prezzo = pricestr.split(" ");
Float price = Float.valueOf(prezzo[0]);
com.shawnlin.numberpicker.NumberPicker numberPicker = (com.shawnlin.numberpicker.NumberPicker) view.findViewById(R.id.number_picker);
int value = numberPicker.getValue();
if (value != 0) {
totale = totale + (price * value);
listapiatti = listapiatti + nome + ": " + value + ", ";
Toast.makeText(getApplicationContext(), String.valueOf(i)+" "+value,
Toast.LENGTH_LONG).show();
}
}
String finale=String.valueOf(totale);
startActivity(new Intent(carrello3.this, ordine.class));
}
if (view.getId()==R.id.buttonback){
onBackPressed();
}
}
it doesn't seem like a good idea to create an object on setOnScrollListener which gets called many many times during scrolling up/down. if you could provide more detail would be great.

Add different layout between item in RecyclerView-AndroidX

I want to add Different layout between item in my recyclerview, I have 3 item in first layout, and then I add second layout to item number 2, so It should have 4 item right now, (1-FirstLayout)-(2-SecondLayout)-(3FirstLayout)-(4FirstLayout), but I realize the position that I choose from my second layout replaced to the position first layout it becomes like this (1-FirstLayout)-(2-SecondLayout)-(3FirstLayout)
Iam not sure how to fix it
This is my Adapter
public class AdapterGameReview extends RecyclerView.Adapter{
public static final int TYPE_ITEM = 1;
public static final int TYPE_TOPREVIEWER = 2;
public static final int TYPE_ADSBANNER = 3;
private boolean mWithTopReviewer = true;
private boolean mWithAdsBanner = false;
private Context mContext;
private ArrayList<ModelGameReview> modelGameReviews;
private RecyclerViewClickListener mListener;
public AdapterGameReview(Context mContext, ArrayList<ModelGameReview> modelGameReviews, RecyclerViewClickListener mListener) {
this.mContext = mContext;
this.modelGameReviews = modelGameReviews;
this.mListener = mListener;
}
//Container
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View v = null;
if (viewType == TYPE_TOPREVIEWER) {
v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_gamereviewtopreviewer, null);
return new GameReviewTopReviewerViewHolder(v);
} else if (viewType == TYPE_ADSBANNER) {
v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_adsbannerdummy, null);
return new GameReviewAdsBannerViewHolder(v);
} else {
v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_gamereview, null);
return new GameReviewViewHolder(v, mListener);
}
}
//Fill Container with Model Setter Getter
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
if (holder instanceof AdapterGameReview.GameReviewTopReviewerViewHolder) {
AdapterGameReview.GameReviewTopReviewerViewHolder gameReviewTopReviewerViewHolder = (AdapterGameReview.GameReviewTopReviewerViewHolder) holder;
/*gameReviewTopReviewerViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});*/
}else if (holder instanceof AdapterGameReview.GameReviewAdsBannerViewHolder) {
AdapterFollowSavedGameReviewList.ShowmoreViewHolder showmoreViewHolder = (AdapterFollowSavedGameReviewList.ShowmoreViewHolder) holder;
} else {
final GameReviewViewHolder GameReviewViewHolder = (GameReviewViewHolder) holder;
final ModelGameReview modelGameReviewX = modelGameReviews.get(position);
RequestOptions requestOptions = new RequestOptions();
requestOptions.placeholder(R.mipmap.ic_launcher);
requestOptions.error(R.drawable.bug);
requestOptions.diskCacheStrategy(DiskCacheStrategy.ALL);
requestOptions.centerCrop();
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
date = inputFormat.parse(modelGameReviewX.getGamedate());
} catch (ParseException e) {
e.printStackTrace();
}
CharSequence niceDateStr = DateUtils.getRelativeTimeSpanString(date.getTime(), Calendar.getInstance().getTimeInMillis(), DateUtils.MINUTE_IN_MILLIS);
//Set
GameReviewViewHolder.TVGameDate.setText(niceDateStr);
GameReviewViewHolder.TVGameTitle.setText(modelGameReviewX.getGametitle());
GameReviewViewHolder.TVGameDescription.setText(modelGameReviewX.getGamedescription());
Glide.with(mContext).load(modelGameReviewX.getGameimage())
.apply(requestOptions)
.listener(new RequestListener<Drawable>() {
#Override
public boolean onLoadFailed(#Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
GameReviewViewHolder.ProgressLoadPhoto.setVisibility(View.GONE);
return false;
}
#Override
public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
GameReviewViewHolder.ProgressLoadPhoto.setVisibility(View.GONE);
return false;
}
})
.transition(DrawableTransitionOptions.withCrossFade())
.into(GameReviewViewHolder.IMGGameImage);
GameReviewViewHolder.TVSeenCounter.setText(String.valueOf(modelGameReviewX.getSeencounter()));
GameReviewViewHolder.TVCommentCounter.setText(String.valueOf(modelGameReviewX.getCommentcounter()));
GameReviewViewHolder.TVLikeCounter.setText(String.valueOf(modelGameReviewX.getLikecounter()));
if (modelGameReviewX.getIscomment() == 0) {
GameReviewViewHolder.IMGCommentView.setImageResource(R.drawable.comment_off);
} else if (modelGameReviewX.getIscomment() == 1) {
GameReviewViewHolder.IMGCommentView.setImageResource(R.drawable.comment_on);
}
if (modelGameReviewX.getIslike() == 0) {
GameReviewViewHolder.IMGLikeView.setImageResource(R.drawable.heart_off);
} else if (modelGameReviewX.getIslike() == 1) {
GameReviewViewHolder.IMGLikeView.setImageResource(R.drawable.heart_on);
}
if (modelGameReviewX.getIsbookmark() == 0) {
GameReviewViewHolder.IMGBookmarkView.setImageResource(R.drawable.saved_off);
GameReviewViewHolder.IMGBookmarkView.setVisibility(View.GONE);
} else if (modelGameReviewX.getIsbookmark() == 1) {
GameReviewViewHolder.IMGBookmarkView.setImageResource(R.drawable.saved_on);
}
GameReviewViewHolder.TVReviewer.setText(modelGameReviewX.getReviewer());
}
}
#Override
public int getItemCount() {
int itemCount = 0;
if(mWithTopReviewer == true){
itemCount++;
}
itemCount = modelGameReviews.size();
return itemCount;
}
//TYPE_ITEM
public class GameReviewViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView TVGameDate;
TextView TVGameTitle;
TextView TVGameDescription;
ImageView IMGGameImage;
TextView TVSeenCounter;
TextView TVCommentCounter;
TextView TVLikeCounter;
ImageView IMGSeenView;
ImageView IMGCommentView;
ImageView IMGLikeView;
TextView TVReviewer;
ProgressBar ProgressLoadPhoto;
ImageView IMGBookmarkView;
private RelativeLayout ROWGameReviewContainer;
private RecyclerViewClickListener mListener;
public GameReviewViewHolder(View itemView, RecyclerViewClickListener listener) {
super(itemView);
TVGameDate = itemView.findViewById(R.id.TV_GameDate);
TVGameTitle = itemView.findViewById(R.id.TV_GameTitle);
TVGameDescription = itemView.findViewById(R.id.TV_GameDescription);
IMGGameImage = itemView.findViewById(R.id.IMG_GameImage);
TVSeenCounter = itemView.findViewById(R.id.TV_SeenCounter);
TVCommentCounter = itemView.findViewById(R.id.TV_CommentCounter);
TVLikeCounter = itemView.findViewById(R.id.TV_LikeCounter);
IMGSeenView = itemView.findViewById(R.id.IMG_SeenView);
IMGCommentView = itemView.findViewById(R.id.IMG_CommentView);
IMGLikeView = itemView.findViewById(R.id.IMG_LikeView);
TVReviewer = itemView.findViewById(R.id.TV_Reviewer);
ProgressLoadPhoto = itemView.findViewById(R.id.Progress_LoadPhoto);
IMGBookmarkView = itemView.findViewById(R.id.IMG_BookmarkView);
ROWGameReviewContainer = itemView.findViewById(R.id.ROW_GameReviewContainer);
mListener = listener;
ROWGameReviewContainer.setOnClickListener(this);
IMGCommentView.setOnClickListener(this);
IMGLikeView.setOnClickListener(this);
IMGBookmarkView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.ROW_GameReviewContainer:
mListener.onRowGameReviewContainerClick(ROWGameReviewContainer, getAdapterPosition());
break;
case R.id.IMG_CommentView:
mListener.onRowCommentViewClick(IMGCommentView, getAdapterPosition());
break;
case R.id.IMG_LikeView:
mListener.onRowLikeViewClick(IMGLikeView, getAdapterPosition());
break;
case R.id.IMG_BookmarkView:
mListener.onRowBookmarkViewClick(IMGBookmarkView, getAdapterPosition());
break;
default:
break;
}
}
}
public interface RecyclerViewClickListener {
void onRowGameReviewContainerClick(View view, int position);
void onRowCommentViewClick(View view, int position);
void onRowLikeViewClick(View view, int position);
void onRowBookmarkViewClick(View view, int position);
}
//TYPE_TOPREVIEWER
public class GameReviewTopReviewerViewHolder extends RecyclerView.ViewHolder{
Button BTNToBeReviewer;
public GameReviewTopReviewerViewHolder(View itemView) {
super(itemView);
BTNToBeReviewer = itemView.findViewById(R.id.BTN_ToBeReviewer);
}
}
//TYPE_ADSBANNER
public class GameReviewAdsBannerViewHolder extends RecyclerView.ViewHolder{
public GameReviewAdsBannerViewHolder(View itemView) {
super(itemView);
}
}
#Override
public int getItemViewType(int position) {
if (mWithTopReviewer && isPositionTopReviewer(position))
return TYPE_TOPREVIEWER;
if (mWithAdsBanner && isPositionAdsBanner(position))
return TYPE_ADSBANNER;
return TYPE_ITEM;
}
public boolean isPositionTopReviewer(int position) {
return position == 1 && mWithTopReviewer;
}
public boolean isPositionAdsBanner(int position) {
return position == getItemCount() - 1 && mWithAdsBanner;
}
public void setWithTopReviewer(boolean value) {
mWithTopReviewer = value;
}
public void setWithAdsBanner(boolean value) {
mWithAdsBanner = value;
}
}
This is My Model
public class ModelGameReview implements Serializable {
private int contentpage;
private String idcontent;
private String gametitle;
private String gamedate;
private String gameimage;
private String gamedescription;
private int seencounter;
private int commentcounter;
private int likecounter;
private int iscomment;
private int islike;
private int isbookmark;
private String reviewer;
private String value;
private String message;
public ModelGameReview(int contentpage, String idcontent, String gametitle, String gamedate, String gameimage, String gamedescription, int seencounter, int commentcounter, int likecounter, int iscomment, int islike, int isbookmark, String reviewer, String value, String message) {
this.contentpage = contentpage;
this.idcontent = idcontent;
this.gametitle = gametitle;
this.gamedate = gamedate;
this.gameimage = gameimage;
this.gamedescription = gamedescription;
this.seencounter = seencounter;
this.commentcounter = commentcounter;
this.likecounter = likecounter;
this.iscomment = iscomment;
this.islike = islike;
this.isbookmark = isbookmark;
this.reviewer = reviewer;
this.value = value;
this.message = message;
}
public int getContentpage() {
return contentpage;
}
public void setContentpage(int contentpage) {
this.contentpage = contentpage;
}
public String getIdcontent() {
return idcontent;
}
public void setIdcontent(String idcontent) {
this.idcontent = idcontent;
}
public String getGametitle() {
return gametitle;
}
public void setGametitle(String gametitle) {
this.gametitle = gametitle;
}
public String getGamedate() {
return gamedate;
}
public void setGamedate(String gamedate) {
this.gamedate = gamedate;
}
public String getGameimage() {
return gameimage;
}
public void setGameimage(String gameimage) {
this.gameimage = gameimage;
}
public String getGamedescription() {
return gamedescription;
}
public void setGamedescription(String gamedescription) {
this.gamedescription = gamedescription;
}
public int getSeencounter() {
return seencounter;
}
public void setSeencounter(int seencounter) {
this.seencounter = seencounter;
}
public int getCommentcounter() {
return commentcounter;
}
public void setCommentcounter(int commentcounter) {
this.commentcounter = commentcounter;
}
public int getLikecounter() {
return likecounter;
}
public void setLikecounter(int likecounter) {
this.likecounter = likecounter;
}
public int getIscomment() {
return iscomment;
}
public void setIscomment(int iscomment) {
this.iscomment = iscomment;
}
public int getIslike() {
return islike;
}
public void setIslike(int islike) {
this.islike = islike;
}
public int getIsbookmark() {
return isbookmark;
}
public void setIsbookmark(int isbookmark) {
this.isbookmark = isbookmark;
}
public String getReviewer() {
return reviewer;
}
public void setReviewer(String reviewer) {
this.reviewer = reviewer;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
You have implemented this method wrong
#Override
public int getItemCount() {
int itemCount = 0;
if(mWithTopReviewer == true){
itemCount++;
}
itemCount = modelGameReviews.size();
return itemCount;
}
It should be something similar
#Override
public int getItemCount() {
int itemCount = modelGameReviews.size();
if(mWithTopReviewer == true){
itemCount++;
}
return itemCount;
}

Using getShortClassName() method in Android

I'm trying to modify an application to use the getShortClassName() method instead of displaying the full class name (e.g. "com.google.app.MainActivity" to simply ".MainActivity"). The current setup gives me no errors but doesn't display the text.
I presume the solution is not complicated, although I just don't have the experience to make it work. Help?
#Override
public View getChildView (int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
MyActivityInfo activity = (MyActivityInfo)getChild(groupPosition, childPosition);
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.all_activities_child_item, null);
TextView text1 = (TextView) view.findViewById(android.R.id.text1);
text1.setText(activity.getName());
//TextView text2 = (TextView) view.findViewById(android.R.id.text2);
//text2.setText(activity.getComponentName().getClassName());
TextView text2 = (TextView) view.findViewById(android.R.id.text2);
text2.setText(activity.getShortClassName());
ImageView icon = (ImageView) view.findViewById(android.R.id.icon);
icon.setImageDrawable(activity.getIcon());
return view;
}
public class MyActivityInfo implements Comparable<MyActivityInfo> {
public MyActivityInfo(ComponentName activity, PackageManager pm) {
this.component_name = activity;
ActivityInfo act;
try {
act = pm.getActivityInfo(activity, 0);
this.name = act.loadLabel(pm).toString();
try {
this.icon = (BitmapDrawable)act.loadIcon(pm);
}
catch(ClassCastException e) {
this.icon = (BitmapDrawable)pm.getDefaultActivityIcon();
}
this.icon_resource = act.getIconResource();
} catch (NameNotFoundException e) {
this.name = activity.getShortClassName();
this.icon = (BitmapDrawable)pm.getDefaultActivityIcon();
this.icon_resource = 0;
}
this.icon_resource_name = null;
if(this.icon_resource != 0) {
try {
this.icon_resource_name = pm.getResourcesForActivity(activity).getResourceName(this.icon_resource);
} catch (Exception e) {}
}
}
public ComponentName getComponentName() {
return component_name;
}
public BitmapDrawable getIcon() {
return icon;
}
public String getName() {
return name;
}
public String getIconResourceName() {
return icon_resource_name;
}
public String getShortClassName() {
return class_name;
}
protected ComponentName component_name;
protected BitmapDrawable icon;
protected int icon_resource;
protected String icon_resource_name;
protected String name;
protected String class_name;
#Override
public int compareTo(MyActivityInfo another) {
int cmp_name = this.name.compareTo(another.name);
if (cmp_name != 0) return cmp_name;
int cmp_component = this.component_name.compareTo(another.component_name);
return cmp_component;
}
#Override
public boolean equals(Object other) {
if(!other.getClass().equals(MyPackageInfo.class)) {
return false;
}
MyActivityInfo other_info = (MyActivityInfo)other;
return this.component_name.equals(other_info.component_name);
}
}
You could just use getSimpleName() method of class object:
String a = "Hello";
System.out.println(a.getClass().getSimpleName());
System.out.println(a.getClass().getName());
Output:
String
java.lang.String

how to use native admob ads inside recyclerview with resourcecursoradapter ((without replace any data items))

I trying to add admob native ads in recyclerview that uses resourcecursoradapter adapter .. the issues is
1 - it makes app crash
2 - it replaces recyclerview data item with admob ads
that is my code
public class EntriesCursorAdapter extends ResourceCursorAdapter {
private final Uri mUri;
private final boolean mShowFeedInfo;
private int mIdPos, mTitlePos, mMainImgPos, mDatePos, mIsReadPos, mFavoritePos, mFeedIdPos, mFeedNamePos;
public static final int Ads_view_type = 11;
public EntriesCursorAdapter(Context context, Uri uri, Cursor cursor, boolean showFeedInfo) {
super(context, PrefUtils.getInt(PrefUtils.NEWS_FORMAT_int,R.layout.item_entry_list2), cursor, 0);
mUri = uri;
mShowFeedInfo = showFeedInfo;
reinit(cursor);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
final int position = cursor.getPosition();
final int viewtype = getItemViewType(position);
View itemView ;
if(viewtype == Ads_view_type) {
final LayoutInflater inflater = LayoutInflater.from(context);
itemView = inflater.inflate(R.layout.native_ads, parent, false);
if (itemView.getTag(R.id.holder) == null) {
AdsHolder ads_holder = new AdsHolder();
ads_holder.adView = (NativeExpressAdView) itemView.findViewById(R.id.adView2);
itemView.setTag(R.id.holder, ads_holder);
} return itemView;
}
else {
final LayoutInflater inflater = LayoutInflater.from(context);
itemView = inflater.inflate(PrefUtils.getInt(PrefUtils.NEWS_FORMAT_int, R.layout.item_entry_list2), parent, false);
if (itemView.getTag(R.id.holder) == null) {
ViewHolder holder = new ViewHolder();
holder.titleTextView = (TextView) itemView.findViewById(android.R.id.text1);
holder.dateTextView = (TextView) itemView.findViewById(android.R.id.text2);
holder.mainImgView = (ImageView) itemView.findViewById(R.id.main_icon);
holder.starImgView = (ImageView) itemView.findViewById(R.id.favorite_icon);
itemView.setTag(R.id.holder, holder);
}
return itemView;
}
}
#Override
public int getItemViewType(int position) {
if(position % 6 ==0)
{return Ads_view_type;}
else {
return super.getItemViewType(position);
}
}
#Override
public void bindView(View view, final Context context, Cursor cursor) {
final int position = cursor.getPosition();
final int viewtype = getItemViewType(position);
if (viewtype == Ads_view_type) {
try {
AdsHolder adsHolder = (AdsHolder) view.getTag(R.id.holder);
AdRequest request = new AdRequest.Builder()
.addTestDevice("ca-app-pub-5647351014779121/8591922893")
.build();
adsHolder.adView.loadAd(request);
} catch (Exception e) {
}
} else {
try {
ViewHolder holder = (ViewHolder) view.getTag(R.id.holder);
String titleText = cursor.getString(mTitlePos);
holder.titleTextView.setText(titleText);
final long feedId = cursor.getLong(mFeedIdPos);
String feedName = cursor.getString(mFeedNamePos);
String mainImgUrl = cursor.getString(mMainImgPos);
mainImgUrl = TextUtils.isEmpty(mainImgUrl) ? null : NetworkUtils.getDownloadedOrDistantImageUrl(cursor.getLong(mIdPos), mainImgUrl);
ColorGenerator generator = ColorGenerator.DEFAULT;
int color = generator.getColor(feedId); // The color is specific to the feedId (which shouldn't change)
String lettersForName = feedName != null ? (feedName.length() < 2 ? feedName.toUpperCase() : feedName.substring(0, 2).toUpperCase()) : "";
TextDrawable letterDrawable = TextDrawable.builder().buildRect(lettersForName, color);
if (mainImgUrl != null) {
Glide.with(context).load(mainImgUrl).centerCrop().placeholder(letterDrawable).error(letterDrawable).into(holder.mainImgView);
} else {
Glide.clear(holder.mainImgView);
holder.mainImgView.setImageDrawable(letterDrawable);
}
holder.isFavorite = cursor.getInt(mFavoritePos) == 1;
holder.starImgView.setVisibility(holder.isFavorite ? View.VISIBLE : View.INVISIBLE);
if (mShowFeedInfo && mFeedNamePos > -1) {
if (feedName != null) {
holder.dateTextView.setText(Html.fromHtml("<font color='#247ab0'>" + feedName + "</font>" + Constants.COMMA_SPACE + StringUtils.getDateTimeString(cursor.getLong(mDatePos))));
} else {
holder.dateTextView.setText(StringUtils.getDateTimeString(cursor.getLong(mDatePos)));
}
} else {
holder.dateTextView.setText(StringUtils.getDateTimeString(cursor.getLong(mDatePos)));
}
if (cursor.isNull(mIsReadPos)) {
holder.titleTextView.setEnabled(true);
holder.dateTextView.setEnabled(true);
holder.isRead = false;
} else {
holder.titleTextView.setEnabled(false);
holder.dateTextView.setEnabled(false);
holder.isRead = true;
}
} catch (Exception e) {}
}
}
public void toggleReadState(final long id, View view) {
final ViewHolder holder = (ViewHolder) view.getTag(R.id.holder);
if (holder != null) { // should not happen, but I had a crash with this on PlayStore...
holder.isRead = !holder.isRead;
if (holder.isRead) {
holder.titleTextView.setEnabled(false);
holder.dateTextView.setEnabled(false);
} else {
holder.titleTextView.setEnabled(true);
holder.dateTextView.setEnabled(true);
}
new Thread() {
#Override
public void run() {
ContentResolver cr = MainApplication.getContext().getContentResolver();
Uri entryUri = ContentUris.withAppendedId(mUri, id);
cr.update(entryUri, holder.isRead ? FeedData.getReadContentValues() : FeedData.getUnreadContentValues(), null, null);
}
}.start();
}
}
public void toggleFavoriteState(final long id, View view) {
final ViewHolder holder = (ViewHolder) view.getTag(R.id.holder);
if (holder != null) { // should not happen, but I had a crash with this on PlayStore...
holder.isFavorite = !holder.isFavorite;
if (holder.isFavorite) {
holder.starImgView.setVisibility(View.VISIBLE);
} else {
holder.starImgView.setVisibility(View.INVISIBLE);
}
new Thread() {
#Override
public void run() {
ContentValues values = new ContentValues();
values.put(EntryColumns.IS_FAVORITE, holder.isFavorite ? 1 : 0);
ContentResolver cr = MainApplication.getContext().getContentResolver();
Uri entryUri = ContentUris.withAppendedId(mUri, id);
cr.update(entryUri, values, null, null);
}
}.start();
}
}
#Override
public void changeCursor(Cursor cursor) {
reinit(cursor);
super.changeCursor(cursor);
}
#Override
public Cursor swapCursor(Cursor newCursor) {
reinit(newCursor);
return super.swapCursor(newCursor);
}
#Override
public void notifyDataSetChanged() {
reinit(null);
super.notifyDataSetChanged();
}
#Override
public void notifyDataSetInvalidated() {
reinit(null);
super.notifyDataSetInvalidated();
}
private void reinit(Cursor cursor) {
if (cursor != null && cursor.getCount() > 0) {
mIdPos = cursor.getColumnIndex(EntryColumns._ID);
mTitlePos = cursor.getColumnIndex(EntryColumns.TITLE);
mMainImgPos = cursor.getColumnIndex(EntryColumns.IMAGE_URL);
mDatePos = cursor.getColumnIndex(EntryColumns.DATE);
mIsReadPos = cursor.getColumnIndex(EntryColumns.IS_READ);
mFavoritePos = cursor.getColumnIndex(EntryColumns.IS_FAVORITE);
mFeedNamePos = cursor.getColumnIndex(FeedColumns.NAME);
mFeedIdPos = cursor.getColumnIndex(EntryColumns.FEED_ID);
}
}
private static class ViewHolder {
public TextView titleTextView;
public TextView dateTextView;
public ImageView mainImgView;
public ImageView starImgView;
public boolean isRead, isFavorite;
}
private static class AdsHolder {
NativeExpressAdView adView;
}
}

How to setText to ArrayList<>?

I have a class Tweet with a get Mentions methods with it
But I don't know how to setText to the ArrayList<>.
Here is my code
public class Tweet {
public String body;
private long uid;
private String createAt;
private User user;
private String urlImageNews;
private static String url;
public ArrayList<User> mentions;
public ArrayList<User> getMentions()
{
return mentions;
}
public String getUrlImageNews()
{
return urlImageNews;
}
public String getBody() {
return body;
}
public long getUid() {
return uid;
}
public String getCreateAt() {
return createAt;
}
public User getUser() {
return user;
}
public String getUrl()
{
return url;
}
public String getRelativeTimeAgo() {
String twitterFormat = "EEE MMM dd HH:mm:ss ZZZZZ yyyy";
SimpleDateFormat sf = new SimpleDateFormat(twitterFormat, Locale.ENGLISH);
sf.setLenient(true);
String relativeDate = "";
try {
long dateMillis = sf.parse(getCreateAt()).getTime();
relativeDate = DateUtils.getRelativeTimeSpanString(dateMillis,
System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS).toString();
} catch (ParseException e) {
e.printStackTrace();
}
return relativeDate;
}
public static Tweet fromJSON(JSONObject jsonObject)
{
Tweet twt = new Tweet();
try {
twt.body = jsonObject.getString("text");
twt.uid = jsonObject.getLong("id");
twt.createAt = jsonObject.getString("created_at");
twt.user = User.fromJSON(jsonObject.getJSONObject("user"));
twt.mentions = LoadMentions(jsonObject);
JSONArray media = jsonObject.getJSONObject("entities").optJSONArray("media");
if (media != null) {
for (int i = 0; i < media.length(); i++) {
JSONObject a = media.getJSONObject(i);
if (a.getString("type").equals("photo")) {
twt.urlImageNews = a.getString("media_url_https");
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return twt;
}
private static ArrayList<User> LoadMentions(JSONObject object) throws JSONException{
if (!object.getJSONObject("entities").has("user_mentions")) {
return null;
}
ArrayList<User> mentions = new ArrayList<User>();
JSONArray mentionsJSON = object.getJSONObject("entities").getJSONArray("user_mentions");
for (int i = 0; i < mentionsJSON.length(); i++) {
User user = User.fromJSON(mentionsJSON.getJSONObject(i));
mentions.add(user);
}
return mentions;
}
public static ArrayList<Tweet> fromJSONArray(JSONArray jsonArray)
{
ArrayList<Tweet> tweets = new ArrayList<>();
for ( int i = 0 ; i < jsonArray.length(); i++)
{
try {
JSONObject tweetjson = jsonArray.getJSONObject(i);
Tweet tweet = Tweet.fromJSON(tweetjson);
if(tweet != null)
{
tweets.add(tweet);
}
} catch (JSONException e) {
e.printStackTrace();
continue;
}
}
return tweets;
}
}
Here is my MentionsAdapter where I want to setText the Mentions Array
public class MentionsAdapter extends RecyclerView.Adapter<MentionsAdapter.ViewHolder> {
Context context;
View tweetView;
private List<Tweet> lTweets;
public MentionsAdapter(List<Tweet> tweets)
{
lTweets = tweets;
}
public void clear() {
lTweets.clear();
notifyDataSetChanged();
}
// Add a list of items
public void addAll(List<Tweet> list) {
lTweets.addAll(list);
notifyDataSetChanged();
}
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private ImageView ivProfile;
private TextView tvUsername;
private TextView tvMentions;
private TextView tvMentionsDate;
public ViewHolder(View view) {
super(view);
ivProfile = (ImageView) view.findViewById(R.id.ivAva);
tvUsername = (TextView) view.findViewById(R.id.tvName);
tvMentions = (TextView) view.findViewById(R.id.tvMentions);
tvMentionsDate = (TextView) view.findViewById(R.id.tvMentionsDate);
view.setOnClickListener(this);
}
#Override
public void onClick(View v) {
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
tweetView = inflater.inflate(R.layout.item_metions, parent, false);
ViewHolder viewHolder = new ViewHolder(tweetView);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Log.d("debug", "int:: " + position);
Tweet tweet = lTweets.get(position);
holder.tvMentionsDate.setText(tweet.getRelativeTimeAgo());
holder.tvUsername.setText(tweet.getUser().getName());
holder.tvMentions.setText(tweet)
holder.ivProfile.setImageResource(android.R.color.transparent);
Glide.with(context).load(tweet.getUser().getProfileImageUrl()).into(holder.ivProfile);
}
#Override
public int getItemCount() {
if(lTweets == null){
Log.d("debug", "null");
return 0;
}
else {
Log.d("debug", ":: " + lTweets.size());
return lTweets.size();
}
}
}
Thanks in advance.
you can get mentions data from tweet by following
User user = tweet.getMentions();
so that you can get user object from that.same way you can get all user instances from here by using
user.getMethodName()
just update the above code in onBindViewHolder().
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Log.d("debug", "int:: " + position);
Tweet tweet = lTweets.get(position);
User user = tweet.getMentions();
holder.tvMentionsDate.setText(tweet.getRelativeTimeAgo());
holder.tvUsername.setText(tweet.getUser().getName());
holder.tvMentions.setText(tweet)
holder.ivProfile.setImageResource(android.R.color.transparent);
Glide.with(context).load(tweet.getUser().getProfileImageUrl()).into(holder.ivProfile);
}
If i am not wrong u want to add data to your ArrayList which is of type Tweet this can be done like this
yourArrayList.add(new Tweet ("Parameters goes here");
hope this helps
if I understand correctly you just want to display the number of mentions.
you can do this:
holder.tvMentions.setText(Integer.toString(tweet.getMentions().size()));
Ahh Well I fix with my answer just by adding some line :
twt.textMentions = jsonObject.getString("text");
Anyway thanks everyone for the answers

Categories