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.
Related
For some reason the only thing displayed in my RecyclerView is com.stu54259.plan2cook.Model.Shopping_list#5cb7482 repeated with various end codes not the contents of the ArrayList. Any suggestions must be something with the recylerview adapter. Can add xml etc if need be but i'm sure I've just missed something stupid.
Shopping_List class
package com.stu54259.plan2cook.Model;
public class Shopping_List {
private int id;
private String ingredient_type;
private String ingredient_name;
private Double quantity;
private String measurement_name;
public Shopping_List() {
}
public Shopping_List(String ingredient_type, String ingredient_name, Double quantity, String measurement_name) {
this.ingredient_type = ingredient_type;
this.ingredient_name = ingredient_name;
this.quantity = quantity;
this.measurement_name = measurement_name;
}
public Shopping_List(int id, String ingredient_type, String ingredient_name, Double quantity, String measurement_name) {
this.id = id;
this.ingredient_type = ingredient_type;
this.ingredient_name = ingredient_name;
this.quantity = quantity;
this.measurement_name = measurement_name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getIngredient_type() {
return ingredient_type;
}
public void setIngredient_type(String ingredient_type) {
this.ingredient_type = ingredient_type;
}
public String getIngredient_name() {
return ingredient_name;
}
public void setIngredient_name(String ingredient_name) {
this.ingredient_name = ingredient_name;
}
public Double getQuantity() {
return quantity;
}
public void setQuantity(Double quantity) {
this.quantity = quantity;
}
public String getMeasurement_name() {
return measurement_name;
}
public void setMeasurement_name(String measurement_name) {
this.measurement_name = measurement_name;
}
}
Activity
public class ShoppingList extends MainActivity {
ShoppingListAdapter adapterRecipe;
List<Shopping_List> shopList = new ArrayList<>();
RecyclerView listIngredient;
SQLiteDatabase db;
Cursor c;
EditText edittext;
String search;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.shopping_list);
edittext = findViewById(R.id.editPlanName);
edittext.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
search = edittext.getText().toString();
Log.d("Search value", search);
if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode == KeyEvent.KEYCODE_ENTER)) {
loadIngredient();
adapterRecipe.notifyDataSetChanged();
return true;
}
return false;
}
});
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.home:
Intent a = new Intent(ShoppingList.this,MainActivity.class);
startActivity(a);
break;
case R.id.recipes:
Intent b = new Intent(ShoppingList.this,RecipeSearch.class);
startActivity(b);
break;
case R.id.shoppingList:
Intent c = new Intent(ShoppingList.this, ShoppingList.class);
startActivity(c);
break;
case R.id.mealPlan:
Intent d = new Intent(ShoppingList.this, MenuPlan.class);
startActivity(d);
break;
case R.id.reminder:
Intent e = new Intent(ShoppingList.this, Reminders.class);
startActivity(e);
break;
}
return false;
}
});
adapterRecipe = new ShoppingListAdapter(this, shopList);
listIngredient = findViewById(R.id.listIngredient);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this,
LinearLayoutManager.VERTICAL, false);
listIngredient.setLayoutManager(mLayoutManager);
listIngredient.setItemAnimator(new DefaultItemAnimator());
listIngredient.setAdapter(adapterRecipe);
}
public void loadIngredient() {
shopList.clear();
db = (new DatabaseManager(this).getWritableDatabase());
String RECIPE_SEARCH =
"SELECT SUM(A.ingredient_quantity) quantity, A.ingredient ingredient_name, A.recipe, B.ingredient_type, B.measurement_name, C.id, D.plan_name " +
"FROM " + DatabaseManager.TABLE_QUANTITY + " AS A JOIN " + DatabaseManager.TABLE_INGREDIENTS + " AS B ON A.ingredient = B.ingredient_name " +
"JOIN " + DatabaseManager.TABLE_PLAN_RECIPES + " AS C ON A.recipe = C.recipe_name " +
"JOIN " + DatabaseManager.TABLE_MEAL_PLAN + " AS D ON C.id = D.plan_recipe " +
"WHERE D.plan_name LIKE ? GROUP BY A.ingredient";
Log.d("Search query", RECIPE_SEARCH);
c = db.rawQuery(RECIPE_SEARCH, new String[]{"%" + search + "%"});
if (c.moveToFirst()) {
do {
Shopping_List shopping_list = new Shopping_List();
shopping_list.setQuantity(c.getDouble(c.getColumnIndex("quantity")));
shopping_list.setIngredient_name(c.getString(c.getColumnIndex("ingredient_name")));
shopping_list.setIngredient_type(c.getString(c.getColumnIndex("ingredient_type")));
shopping_list.setMeasurement_name(c.getString(c.getColumnIndex("measurement_name")));
shopList.add(shopping_list);
} while (c.moveToNext());
}
c.close();
db.close();
}
}
Adapter
public class ShoppingListAdapter extends RecyclerView.Adapter<com.stu54259.plan2cook.Adapters.ShoppingListAdapter.ViewHolder> {
private List<Shopping_List> shopList;
private LayoutInflater mInflater;
private com.stu54259.plan2cook.Adapters.RecyclerViewAdapter.ItemClickListener mClickListener;
// data is passed into the constructor
public ShoppingListAdapter(Context context, List<Shopping_List> data) {
this.mInflater = LayoutInflater.from(context);
this.shopList = data;
}
// inflates the row layout from xml when needed
#Override
public com.stu54259.plan2cook.Adapters.ShoppingListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.fragment_item, parent, false);
return new com.stu54259.plan2cook.Adapters.ShoppingListAdapter.ViewHolder(view);
}
// binds the data to the TextView in each row
#Override
public void onBindViewHolder(com.stu54259.plan2cook.Adapters.ShoppingListAdapter.ViewHolder holder, int position) {
if(shopList.get(position) != null)
{
holder.myTextView.setText(shopList.get(position).toString());
}
}
// total number of rows
#Override
public int getItemCount() {
return shopList.size();
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView myTextView;
ViewHolder(View itemView) {
super(itemView);
myTextView = itemView.findViewById(R.id.quantity);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
}
}
// allows clicks events to be caught
void setClickListener(com.stu54259.plan2cook.Adapters.RecyclerViewAdapter.ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
// parent activity will implement this method to respond to click events
public interface ItemClickListener {
void onItemClick(View view, int position);
}
}
Add this method in your Shopping_List class, so when you use toString() for a Shopping_List instance you will get all its properties separated by spaces:
public String toString() {
return ingredient_name + " " + ingredient_type + " " + quantity + " " + measurement_name;
}
You can change the order of the properties.
You have wrong code in onBindViewHolder method. You should set text with some field from Shopping_List object:
#Override
public void onBindViewHolder(com.stu54259.plan2cook.Adapters.ShoppingListAdapter.ViewHolder holder, int position) {
if(shopList.get(position) != null)
{
holder.myTextView.setText(shopList.get(position).toString());
}
}
You haven't put the Shopping_List object here, but if you have something like this:
public class Shopping_List {
public String title;
public String getTitle() {
return title;
}
}
Then you should do something like this:
#Override
public void onBindViewHolder(com.stu54259.plan2cook.Adapters.ShoppingListAdapter.ViewHolder holder, int position) {
if(shopList.get(position) != null)
{
holder.myTextView.setText(shopList.get(position).getTitle());
}
}
Although it doesn't give a direct solution, I would suggest that you use the groupie library. It will most likely remove your error and reduce boilerplate code and complexity.
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;
}
Good day. I need to implement parcelable in Model class.Currently it is Serializable. for now only setdate and set title if thare If any one can help. please edit code.
MainActivity.java
Document document = Jsoup.connect("http://feeds.bbci.co.uk/urdu/rss.xml").ignoreHttpErrors(true).get();
Elements itemElements = document.getElementsByTag("item");
for (int i = 0; i < itemElements.size(); i++) {
Element item = itemElements.get(i);
NewsItem newsItem = new NewsItem();
newsItem.setDate(item.child(4).text());
newsItem.setTitle(item.child(0).text());
newsItemsList.add(newsItem);
}
} catch (IOException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
#Override
public void run() {
adapter = new NewsAdaptor(Main2Activity.this,
newsItemsList);
lvRss.setAdapter(adapter);
}
});
return null;
}
NewsItem.java //model class
public class NewsItem implements Serializable {
String imagePath;
String title;
String link;
String date;
public NewsItem () {
}
public String getImagePath () {
return imagePath;
}
public void setImagePath ( String imagePath ) {
this.imagePath = imagePath;
}
public String getTitle () {
return title;
}
public void setTitle ( String title ) {
this.title = title;
}
public String getLink () {
return link;
}
public void setLink ( String link ) {
this.link = link;
}
public String getDate () {
return date;
}
public void setDate ( String date ) {
this.date = date;
}
NewsAdapter.java
public class NewsAdaptor extends BaseAdapter {
private int textSize;
TextView tvtitle;
private int color;
Context context;
public NewsAdaptor ( Context context, ArrayList <NewsItem> newsList ) {
this.context = context;
this.newsList = newsList;
this.color = Color.RED;
}
ArrayList<NewsItem> newsList;
#Override
public int getCount () {
return newsList.size();
}
#Override
public Object getItem ( int position ) {
return newsList.get(position);
}
#Override
public long getItemId ( int position ) {
return 0;
}
#Override
public View getView ( int position, View convertView, ViewGroup parent ) {
if (convertView == null){
convertView=View.inflate(context, R.layout.newsitemlist_layout,null);
}
NewsItem currentNews = newsList.get(position);
ImageView iv1 = (ImageView) convertView.findViewById(R.id.mainimg);
TextView tvdate = (TextView) convertView.findViewById(R.id.pubDateid);
Picasso.with(context).load(currentNews.getImagePath()).placeholder(R.drawable.expressimg).into(iv1);
tvdate.setText(currentNews.getDate());
tvtitle = (TextView) convertView.findViewById(R.id.textView1id);
tvtitle.setText(currentNews.getTitle());
tvtitle.setTextColor(color);
return convertView;
}
public void setTextColor(int color) {
this.color = color;
}
Check this Parcelable NewsItem:
public class NewsItem implements Parcelable {
String imagePath;
String title;
String link;
String date;
public NewsItem() {
}
protected NewsItem(Parcel in) {
imagePath = in.readString();
title = in.readString();
link = in.readString();
date = in.readString();
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(imagePath);
dest.writeString(title);
dest.writeString(link);
dest.writeString(date);
}
#Override
public int describeContents() {
return 0;
}
public static final Creator<NewsItem> CREATOR = new Creator<NewsItem>() {
#Override
public NewsItem createFromParcel(Parcel in) {
return new NewsItem(in);
}
#Override
public NewsItem[] newArray(int size) {
return new NewsItem[size];
}
};
public String getImagePath() {
return imagePath;
}
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
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
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();
}