How do I convert my BaseAdapter to a RecyclerAdapter - java

So I wanted to change my GridView to a RecyclerView and with that I had to change my BaseAdapter to a RecyclerAdapter.
I already tried making changes, but I have no clue how to switch the code into the RecyclerAdapter.
Here is how my BaseAdapter looks like :
class AlbumAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap< String, String >> data;
public AlbumAdapter(Activity a, ArrayList < HashMap < String, String >> d) {
activity = a;
data = d;
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
AlbumViewHolder holder = null;
if (convertView == null) {
holder = new AlbumViewHolder();
convertView = LayoutInflater.from(activity).inflate(
R.layout.album_row, parent, false);
holder.galleryImage = (ImageView) convertView.findViewById(R.id.galleryImage);
holder.gallery_count = (TextView) convertView.findViewById(R.id.gallery_count);
holder.gallery_title = (TextView) convertView.findViewById(R.id.gallery_title);
convertView.setTag(holder);
} else {
holder = (AlbumViewHolder) convertView.getTag();
}
holder.galleryImage.setId(position);
holder.gallery_count.setId(position);
holder.gallery_title.setId(position);
HashMap < String, String > song = new HashMap < String, String > ();
song = data.get(position);
try {
holder.gallery_title.setText(song.get(Function.KEY_ALBUM));
holder.gallery_count.setText(song.get(Function.KEY_COUNT));
Glide.with(activity)
.load(new File(song.get(Function.KEY_PATH))) // Uri of the picture
.into(holder.galleryImage);
} catch (Exception e) {}
return convertView;
}
}
class AlbumViewHolder {
ImageView galleryImage;
TextView gallery_count, gallery_title;
}
And thanks in advance !

Simply use this, feel free to modify to suit your need, make sure to read the comments as they really will help you understand few things.
public class AlbumAdapter extends RecyclerView.Adapter<AlbumAdapter.ViewHolder> {
private static final String KEY_ALBUM = "KEY_ALBUM";
private static final String KEY_COUNT = "KEY_COUNT";
private static final String KEY_PATH = "KEY_PATH";
private itemClickInterface clickInterface;
//private List<String> data;
private ArrayList<HashMap<String, String >> data;
// public AlbumAdapter(itemClickInterface clickInterface, List<String> data) { // Forget about this if your data is not an array of Strings.
// public AlbumAdapter(itemClickInterface clickInterface, ArrayList<HashMap< String, String >> data) { // Forget about this if you're not ready to pass an onclick interface
public AlbumAdapter(ArrayList<HashMap< String, String >> data) {
this.data = data;
// this.clickInterface = clickInterface; //Simply ignore since you're not passing an interface of clicklister
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.album_row, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
try {
final String data_for_albums = this.data.get(position).get(KEY_ALBUM);
final String data_for_counts = this.data.get(position).get(KEY_COUNT);
final String data_for_paths = this.data.get(position).get(KEY_PATH);
holder.gallery_title.setText(data_for_albums);
holder.gallery_count.setText(data_for_counts);
Glide.with(activity)
.load(new File(data_for_paths)) // Uri of the picture
.into(holder.galleryImage);
/*
* You can modify this as you want.
* */
// holder.galleryImage.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// clickInterface.click(data_for_paths); // This depends on you.
// }
// });
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public int getItemCount() {
return data.size();
}
/*--------------------------------------------------------------------------------------
| GET REFERENCES TO VIEWS HERE
*--------------------------------------------------------------------------------------*/
class ViewHolder extends RecyclerView.ViewHolder {
ImageView galleryImage;
TextView gallery_count, gallery_title;
ViewHolder(View itemView) {
super(itemView);
galleryImage = itemView.findViewById(R.id.galleryImage);
gallery_count = itemView.findViewById(R.id.gallery_count);
gallery_title = itemView.findViewById(R.id.gallery_title);
}
}
}
How to call from our activity
ArrayList<HashMap<String, String >> data = new ArrayList<>();
//I'm assuming you already feed your data, so you're not passing null like me here.
cardlistview = findViewById(R.id.cardlistview);
albumAdapter = new AlbumAdapter(your_arraysOfHashMap);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
cardlistview.setLayoutManager(mLayoutManager);
cardlistview.setAdapter(albumAdapter);

Related

how to create method in activity to put it in custom adapter listview?

at first I got an error " The code of method getView(int, View, ViewGroup) is exceeding the 65535 bytes limit " because I typed too much code, finally I created a method, but the method is error because the variable inside is not detected
I created Method _Differ();
public void _Differ() {
if (_position == 5) {
full.setText("iiii");
}
}
i put method Differ(); in custom adapter listview
this is my code in listview custom adapter
public class Listview1Adapter extends BaseAdapter {
ArrayList<HashMap<String, Object>> _data;
public Listview1Adapter(ArrayList<HashMap<String, Object>> _arr) {
_data = _arr;
}
#Override
public int getCount() {
return _data.size();
}
#Override
public HashMap<String, Object> getItem(int _index) {
return _data.get(_index);
}
#Override
public long getItemId(int _index) {
return _index;
}
#Override
public View getView(final int _position, View _v, ViewGroup _container) {
LayoutInflater _inflater = getLayoutInflater();
View _view = _v;
if (_view == null) {
_view = _inflater.inflate(R.layout.ccc, null);
}
final LinearLayout linear1 = _view.findViewById(R.id.linear1);
final LinearLayout linear2 = _view.findViewById(R.id.linear2);
final LinearLayout linear3 = _view.findViewById(R.id.linear3);
final LinearLayout linear4 = _view.findViewById(R.id.linear4);
final TextView textview1 = _view.findViewById(R.id.textview1);
final TextView full = _view.findViewById(R.id.full);
final TextView textview2 = _view.findViewById(R.id.textview2);
final TextView shortt = _view.findViewById(R.id.shortt);
final TextView name = _view.findViewById(R.id.name);
final TextView email = _view.findViewById(R.id.email);
full.setText(mapList.get((int)_position).get("end").toString());
shortt.setText(mapList.get((int)_position).get("rule").toString());
email.setText(mapList.get((int)_position).get("start").toString());
_Differ();
return _view;
}
}
//This is your method which will go in your activity >>
public void _Differ(TextView txt, int _position) {
if (_position == 5) {
txt.setText("iiii");
}
}
// This Code Goes in your ListAdpater >>
full.setText(mapList.get((int)_position).get("end").toString());
shortt.setText(mapList.get((int)_position).get("rule").toString());
email.setText(mapList.get((int)_position).get("start").toString());
_Differ(full, _position);
I think this can help you, By the way, Are you using Sketchware Pro 🤔

Where to manipulate the data in Recyclerview Adapter (Android)

My datetime is currently stored as UNIX time stamp. I want to display it as h:mm a in my Recyclerview.
Where should I convert the UNIX time stamp into normal time in the RecyclerView Adapter/Viewholder (in terms of the best performance)?
Should I do it in the getItemViewType(int position) of the RecyclerView.Adapter, or the onBindViewHolder or the bind function of the ViewHolder class?
Edit: My code
public class ChatListAdapter extends RecyclerView.Adapter {
private final LayoutInflater mInflater;
private List<Chat> mChats;
private final String ownerMe = "OWNER_ME";
private static final int VIEW_TYPE_MESSAGE_ME = 1;
private static final int VIEW_TYPE_MESSAGE_ME_CORNER = 2;
private static final int VIEW_TYPE_MESSAGE_BF = 3;
private static final int VIEW_TYPE_MESSAGE_BF_CORNER = 4;
ChatListAdapter(Context context) {mInflater = LayoutInflater.from(context);}
#Override
public int getItemViewType(int position) {
Chat chat = mChats.get(position);
if(chat.getUser().equals(ownerMe)) {
if(position == mChats.size()-1) {
return VIEW_TYPE_MESSAGE_ME_CORNER;
}
if(chat.getUser().equals(mChats.get(position+1).getUser())) {
return VIEW_TYPE_MESSAGE_ME;
} else {
return VIEW_TYPE_MESSAGE_ME_CORNER;
}
} else {
if(position == mChats.size()-1) {
return VIEW_TYPE_MESSAGE_BF_CORNER;
}
if(chat.getUser().equals(mChats.get(position+1).getUser())) {
return VIEW_TYPE_MESSAGE_BF;
} else {
return VIEW_TYPE_MESSAGE_BF_CORNER;
}
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
if(viewType == VIEW_TYPE_MESSAGE_ME || viewType == VIEW_TYPE_MESSAGE_ME_CORNER) {
view = mInflater.inflate(R.layout.recyclerview_item_right, parent, false);
return new MeMessageHolder(view);
} else if (viewType == VIEW_TYPE_MESSAGE_BF || viewType == VIEW_TYPE_MESSAGE_BF_CORNER) {
view = mInflater.inflate(R.layout.recyclerview_item_left, parent, false);
return new BfMessageHolder(view);
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (mChats != null) {
Chat current = mChats.get(position);
long unixTime= current.getUnixTime();
Date time = new java.util.Date(unixTime*1000L);
SimpleDateFormat sdf = new java.text.SimpleDateFormat("h:mm a");
String formattedTime = sdf.format(time);
switch (holder.getItemViewType()) {
case VIEW_TYPE_MESSAGE_ME:
((MeMessageHolder) holder).bind(current, formattedTime, false);
break;
case VIEW_TYPE_MESSAGE_ME_CORNER:
((MeMessageHolder) holder).bind(current, formattedTime, true);
break;
case VIEW_TYPE_MESSAGE_BF:
((BfMessageHolder) holder).bind(current, formattedTime, false);
break;
case VIEW_TYPE_MESSAGE_BF_CORNER:
((BfMessageHolder) holder).bind(current, formattedTime, true);
break;
}
}
}
class MeMessageHolder extends RecyclerView.ViewHolder {
private final TextView chatItemView;
private final ImageView cornerRightIImageView;
private final ConstraintLayout constraintLayout;
private final TextView timeItemView;
private MeMessageHolder(View itemView) {
super(itemView);
chatItemView = itemView.findViewById(R.id.textView);
cornerRightIImageView = itemView.findViewById(R.id.corner_view_right);
constraintLayout = itemView.findViewById(R.id.chat_bubble_id);
timeItemView = itemView.findViewById(R.id.text_message_time);
}
void bind(Chat chat, String formattedTime, boolean isCorner) {
chatItemView.setText(chat.getMessage());
timeItemView.setText(formattedTime);
if(isCorner) {
constraintLayout.setBackgroundResource(R.drawable.chat_bubble_v2);
} else {
cornerRightIImageView.setVisibility(View.INVISIBLE);
}
}
}
class BfMessageHolder extends RecyclerView.ViewHolder {
private final TextView chatItemView;
private final ImageView cornerLeftImageView;
private final ConstraintLayout constraintLayout;
private final TextView timeItemView;
private BfMessageHolder(View itemView) {
super(itemView);
chatItemView = itemView.findViewById(R.id.textView);
cornerLeftImageView = itemView.findViewById(R.id.corner_view_left);
constraintLayout = itemView.findViewById(R.id.chat_bubble_id);
timeItemView = itemView.findViewById(R.id.text_message_time);
}
void bind(Chat chat, String formattedTime, boolean isCorner) {
chatItemView.setText(chat.getMessage());
timeItemView.setText(formattedTime);
if(isCorner) {
constraintLayout.setBackgroundResource(R.drawable.chat_bubble_v3);
} else {
cornerLeftImageView.setVisibility(View.INVISIBLE);
}
}
}
void setChats(List<Chat> chats) {
mChats = chats;
notifyDataSetChanged();
}
#Override
public int getItemCount() {
if(mChats!=null)
return mChats.size();
else return 0;
}
}
This is method correct? I formatted the date in the onBindViewHoldermethod
It depends whether you want to display different dates on different items of the recyclerview, or the same date on all items of the recyclerview.
If you want to show same date to all items, better to do it outside of the adapter and then pass the parsed date to the recyclerview adapter.
Or, if you want to show different dates on each item, you should do it inside onBindViewHolder as it has access to the item position.
Remember, getItemViewType is used for getting a view type out of the available ones. This is used in case you are inflating multiple views. Think of a chatapp where view1 will display message on the left, and view2 will display message on the right; all within the same recyclerview.
The onBindViewHolder method simply performs a generic binding task. Binds what : the item of the inflated view and the data.
It seems like business logic. So, i recommend to move you UNIX time stamp convertation in Model for example.
class Chat {
private Long unixTime;
// another code
public Long getUnixTime() {
return unixTime;
}
public String convertedUnixTimeToString(String format) {
// Also need to add some format validation
if(format == null) {
// do some action, like trowing exception, or setting default value in format
}
Date time = new java.util.Date(unixTime*1000L);
SimpleDateFormat sdf = new java.text.SimpleDateFormat(format);
return sdf.format(time);
}
}
I recommend you to use JodaTime for date&time formatting. Very useful thing.
And then, just modify your code
public class ChatListAdapter extends RecyclerView.Adapter {
private final LayoutInflater mInflater;
private List<Chat> mChats;
private final String ownerMe = "OWNER_ME";
private static final int VIEW_TYPE_MESSAGE_ME = 1;
private static final int VIEW_TYPE_MESSAGE_ME_CORNER = 2;
private static final int VIEW_TYPE_MESSAGE_BF = 3;
private static final int VIEW_TYPE_MESSAGE_BF_CORNER = 4;
ChatListAdapter(Context context) {mInflater = LayoutInflater.from(context);}
#Override
public int getItemViewType(int position) {
Chat chat = mChats.get(position);
if(chat.getUser().equals(ownerMe)) {
if(position == mChats.size()-1) {
return VIEW_TYPE_MESSAGE_ME_CORNER;
}
if(chat.getUser().equals(mChats.get(position+1).getUser())) {
return VIEW_TYPE_MESSAGE_ME;
} else {
return VIEW_TYPE_MESSAGE_ME_CORNER;
}
} else {
if(position == mChats.size()-1) {
return VIEW_TYPE_MESSAGE_BF_CORNER;
}
if(chat.getUser().equals(mChats.get(position+1).getUser())) {
return VIEW_TYPE_MESSAGE_BF;
} else {
return VIEW_TYPE_MESSAGE_BF_CORNER;
}
}
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
if(viewType == VIEW_TYPE_MESSAGE_ME || viewType == VIEW_TYPE_MESSAGE_ME_CORNER) {
view = mInflater.inflate(R.layout.recyclerview_item_right, parent, false);
return new MeMessageHolder(view);
} else if (viewType == VIEW_TYPE_MESSAGE_BF || viewType == VIEW_TYPE_MESSAGE_BF_CORNER) {
view = mInflater.inflate(R.layout.recyclerview_item_left, parent, false);
return new BfMessageHolder(view);
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (mChats != null) {
Chat current = mChats.get(position);
switch (holder.getItemViewType()) {
case VIEW_TYPE_MESSAGE_ME:
((MeMessageHolder) holder).bind(current, false);
break;
case VIEW_TYPE_MESSAGE_ME_CORNER:
((MeMessageHolder) holder).bind(current, true);
break;
case VIEW_TYPE_MESSAGE_BF:
((BfMessageHolder) holder).bind(current, false);
break;
case VIEW_TYPE_MESSAGE_BF_CORNER:
((BfMessageHolder) holder).bind(current, true);
break;
}
}
}
class MeMessageHolder extends RecyclerView.ViewHolder {
private final TextView chatItemView;
private final ImageView cornerRightIImageView;
private final ConstraintLayout constraintLayout;
private final TextView timeItemView;
private MeMessageHolder(View itemView) {
super(itemView);
chatItemView = itemView.findViewById(R.id.textView);
cornerRightIImageView = itemView.findViewById(R.id.corner_view_right);
constraintLayout = itemView.findViewById(R.id.chat_bubble_id);
timeItemView = itemView.findViewById(R.id.text_message_time);
}
void bind(Chat chat, boolean isCorner) {
chatItemView.setText(chat.getMessage());
timeItemView.setText(chat.convertedUnixTimeToString("h:mm a"));
if(isCorner) {
constraintLayout.setBackgroundResource(R.drawable.chat_bubble_v2);
} else {
cornerRightIImageView.setVisibility(View.INVISIBLE);
}
}
}
class BfMessageHolder extends RecyclerView.ViewHolder {
private final TextView chatItemView;
private final ImageView cornerLeftImageView;
private final ConstraintLayout constraintLayout;
private final TextView timeItemView;
private BfMessageHolder(View itemView) {
super(itemView);
chatItemView = itemView.findViewById(R.id.textView);
cornerLeftImageView = itemView.findViewById(R.id.corner_view_left);
constraintLayout = itemView.findViewById(R.id.chat_bubble_id);
timeItemView = itemView.findViewById(R.id.text_message_time);
}
void bind(Chat chat, boolean isCorner) {
chatItemView.setText(chat.getMessage());
timeItemView.setText(chat.convertedUnixTimeToString("h:mm a"));
if(isCorner) {
constraintLayout.setBackgroundResource(R.drawable.chat_bubble_v3);
} else {
cornerLeftImageView.setVisibility(View.INVISIBLE);
}
}
}
void setChats(List<Chat> chats) {
mChats = chats;
notifyDataSetChanged();
}
#Override
public int getItemCount() {
if(mChats!=null)
return mChats.size();
else return 0;
}
}
You should be updating the UI changes in onBindViewHolder method. You can call bind method of ViewHolder in onBindViewHolder.
Example:
public class SampleAdapter extends RecyclerView.Adapter<SampleAdapter.ViewHolder> {
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.sample_view, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder viewHolder, int i) {
viewHolder.bind(i);
}
public class ViewHolder extends RecyclerView.ViewHolder {
public ViewHolder(#NonNull View itemView) {
super(itemView);
}
void bind(int position) {
// Do your data updates here.
}
}
}
Just Use SimpleDateFormat with yyyy-MM-dd pattern .
Apply SimpleDateFormat.format(millis) in onBindViewHolder method of RecyclerView.
You need to convert it to milliseconds by multiplying the timestamp by 1000:
java.util.Date dateTime=new java.util.Date((long)timeStamp*1000);
then first you need to convert UNIX timestamp to datetime format
final long unixTime = 1372339860;
final String formattedDtm = Instant.ofEpochSecond(unixTime)
.atZone(ZoneId.of("GMT-4"))
.format(formatter);
System.out.println(formattedDtm); // => '2013-06-27 09:31:00'
then you want to store this data to field value of RecyclerView
then you can format it from this time format like h:mm

attempting to use incompatible return type

Can someone help me with this error that I keep getting? The program that I'm trying to implement admob banner ad between items in recyclerview. every thing is ok but still this one error that blocked me from go on.
public class RecipeAdapter extends RecyclerView.Adapter<RecipeAdapter.ViewHolder> {
public static final String TAG = RecipeAdapter.class.getSimpleName();
public static final HashMap<String, Integer> LABEL_COLORS = new HashMap<String, Integer>() {{
put("Low-Carb", R.color.colorLowCarb);
put("Low-Fat", R.color.colorLowFat);
put("Low-Sodium", R.color.colorLowSodium);
put("Medium-Carb", R.color.colorMediumCarb);
put("Vegetarian", R.color.colorVegetarian);
put("Balanced", R.color.colorBalanced);
}};
private Context mContext;
private LayoutInflater mInflater;
private ArrayList<Recipe> mDataSource;
private static final int DEFAULT_VIEW_TYPE = 1;
private static final int NATIVE_AD_VIEW_TYPE = 2;
public RecipeAdapter(Context context, ArrayList<Recipe> items) {
mContext = context;
mDataSource = items;
mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); }
#Override public int getItemViewType(int position) {
// Change the position of the ad displayed here. Current is after 5
if ((position + 1) % 6 == 0) {
return NATIVE_AD_VIEW_TYPE;
}
return DEFAULT_VIEW_TYPE; }
#NonNull
#Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
LayoutInflater layoutInflater = LayoutInflater.from(mContext);
switch (viewType) {
default:
view = layoutInflater
.inflate(R.layout.list_item_native_ad, parent, false);
return new ViewHolder(view);
case NATIVE_AD_VIEW_TYPE:
view = layoutInflater.inflate(R.layout.list_item_native_ad, parent, false);
return new ViewHolderAdMob(view);
}
}
#Override public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
// Get relevant subviews of row view
TextView titleTextView = holder.titleTextView;
TextView subtitleTextView = holder.subtitleTextView;
TextView detailTextView = holder.detailTextView;
ImageView thumbnailImageView = holder.thumbnailImageView;
//Get corresponding recipe for row final Recipe recipe = (Recipe) getItem(position);
// Update row view's textviews to display recipe information
titleTextView.setText(recipe.title);
subtitleTextView.setText(recipe.description);
detailTextView.setText(recipe.label);
// Use Picasso to load the image. Temporarily have a placeholder in case it's slow to load
Picasso.with(mContext).load(recipe.imageUrl).placeholder(R.mipmap
.ic_launcher).into(thumbnailImageView);
holder.parentView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent detailIntent = new Intent(mContext, RecipeDetailActivity.class);
detailIntent.putExtra("title", recipe.title);
detailIntent.putExtra("url", recipe.instructionUrl);
mContext.startActivity(detailIntent);
}
});
// Style text views
Typeface titleTypeFace = Typeface.createFromAsset(mContext.getAssets(),
"fonts/JosefinSans-Bold.ttf");
titleTextView.setTypeface(titleTypeFace);
Typeface subtitleTypeFace = Typeface.createFromAsset(mContext.getAssets(),
"fonts/JosefinSans-SemiBoldItalic.ttf");
subtitleTextView.setTypeface(subtitleTypeFace);
Typeface detailTypeFace = Typeface.createFromAsset(mContext.getAssets(),
"fonts/Quicksand-Bold.otf");
detailTextView.setTypeface(detailTypeFace);
detailTextView.setTextColor(android.support.v4.content.ContextCompat.getColor(mContext, LABEL_COLORS
.get(recipe.label)));
}
#Override public int getItemCount() {
return mDataSource.size(); }
#Override public long getItemId(int position) {
return position; }
public Object getItem(int position) {
return mDataSource.get(position); }
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView titleTextView;
private TextView subtitleTextView;
private TextView detailTextView;
private ImageView thumbnailImageView; private View parentView;
public ViewHolder(#NonNull View view){
super(view);
// create a new "Holder" with subviews
this.parentView = view;
this.thumbnailImageView = (ImageView) view.findViewById(R.id.recipe_list_thumbnail);
this.titleTextView = (TextView) view.findViewById(R.id.recipe_list_title);
this.subtitleTextView = (TextView) view.findViewById(R.id.recipe_list_subtitle);
this.detailTextView = (TextView) view.findViewById(R.id.recipe_list_detail);
// hang onto this holder for future recyclage
view.setTag(this);
}
}
public class ViewHolderAdMob extends RecyclerView.ViewHolder {
private final AdView mNativeAd;
public ViewHolderAdMob(View itemView) {
super(itemView);
mNativeAd = itemView.findViewById(R.id.nativeAd);
mNativeAd.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
super.onAdLoaded();
// if (mItemClickListener != null) {
Log.i("AndroidBash", "onAdLoaded");
// }
}
#Override
public void onAdClosed() {
super.onAdClosed();
// if (mItemClickListener != null) {
Log.i("AndroidBash", "onAdClosed");
// }
}
#Override
public void onAdFailedToLoad(int errorCode) {
super.onAdFailedToLoad(errorCode);
// if (mItemClickListener != null) {
Log.i("AndroidBash", "onAdFailedToLoad");
// }
}
#Override
public void onAdLeftApplication() {
super.onAdLeftApplication();
// if (mItemClickListener != null) {
Log.i("AndroidBash", "onAdLeftApplication");
// }
}
#Override
public void onAdOpened() {
super.onAdOpened();
// if (mItemClickListener != null) {
Log.i("AndroidBash", "onAdOpened");
// }
}
});
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice("") // Remove this before publishing app
.build();
mNativeAd.loadAd(adRequest);
}
}
}
The return type needs to be whatever ViewHolder type you declared for your adapter class.
For example, from the Android RecyclerView example page:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
// ^^^^^^^^^^^^^^^^^^^^^^
// It should return this type ^
public static class MyViewHolder extends RecyclerView.ViewHolder {
// your adapter
}
#Override
public MyAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent,int viewType) {
// Note: returns MyAdapter.MyViewHolder, not RecyclerView.ViewHolder
}
}
In your case, you have
public class RecipeAdapter extends RecyclerView.Adapter<RecipeAdapter.ViewHolder>
which means your onCreateViewHolder has to return RecipeAdapter.ViewHolder not RecyclerView.ViewHolder.
There is a separate issue too, which is that you have two ViewHolder types in the same adapter. To do this, you would need to change the ViewHolder type that your RecyclerView is based on to the generic type (RecyclerView.ViewHolder).
Please review this question, it has good answers for how to do this.

Items repeated in Listview with customadapter

I have a ToDo project with listview that shows the data from SQLite with custom adapter. Also, I have a button to add the new task but, the items in list view will be repeated.
my custom adapter is
public class CustomAdapter extends BaseAdapter {
private final Activity activity;
private final ArrayList < LT_Model > data;
private static LayoutInflater inflater = null;
public CustomAdapter(Activity a, ArrayList < LT_Model > d) {
this.activity = a;
this.data = d;
inflater = (LayoutInflater) this.activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public static class ViewHolder {
public TextView task;
public ImageView imgD;
public ImageView imgE;
public ImageView imgS;
}#
Override
public int getCount() {
if (data.size() <= 0)
return 1;
return data.size();
}
#
Override
public Object getItem(int position) {
return position;
}
#
Override
public long getItemId(int position) {
return position;
}
#
Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.item_todo, null);
holder = new ViewHolder();
holder.task = (TextView) convertView.findViewById(R.id.task_title);
holder.imgD = (ImageView) convertView.findViewById(R.id.imgDelete);
holder.imgE = (ImageView) convertView.findViewById(R.id.imgEdit);
holder.imgS = (ImageView) convertView.findViewById(R.id.imgCheck);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
if (data.size() <= 0) {
holder.task.setText("No Data");
} else {
holder.task.setText(data.get(position).getTaskName());
holder.imgD.setImageResource(android.R.drawable.ic_delete);
holder.imgE.setImageResource(data.get(position).getImgComment());
holder.imgS.setImageResource(data.get(position).getImgStatus());
}
return convertView;
}
}
My LT_Model with getter and setter
public class LT_Model {
private String TaskName = "";
private int ImgComment;
private int ImgStatus;
public String getTaskName() {
return TaskName;
}
public void setTaskName(String taskName) {
TaskName = taskName;
}
public int getImgComment() {
return ImgComment;
}
public void setImgComment(int imgComment) {
ImgComment = imgComment;
}
public int getImgStatus() {
return ImgStatus;
}
public void setImgStatus(int imgStatus) {
ImgStatus = imgStatus;
}
}
My UpdateUI which return the data to Arraylist from SQLite in the activity.
My table has 3 columns and I passed them to ArrayList.
private void updateUI() {
ArrayList<LT_Model> taskList = new ArrayList<>();
LT_Model lt_model = new LT_Model();
SQLiteDatabase db = mdb.getReadableDatabase();
Cursor cursor = db.query(DB_Value.Constant.List_Table,
new String[]{DB_Value.Constant._ID, DB_Value.Constant.COL_Task, DB_Value.Constant.COL_Comment,
DB_Value.Constant.COL_Status}, null, null, null, null, null);
while (cursor.moveToNext()) {
//int idx = cursor.getColumnIndex(DB_Value.Constant.COL_Task);
lt_model.setTaskName(cursor.getString(1));
Toast.makeText(getApplicationContext(), lt_model.getTaskName(), Toast.LENGTH_SHORT).show();
if (cursor.getString(2) == null || cursor.getString(2).equals("")) {
lt_model.setImgComment(android.R.drawable.ic_menu_edit);
}else{
lt_model.setImgComment(android.R.drawable.ic_menu_agenda);
}
if (cursor.getInt(3)==1){
lt_model.setImgStatus(android.R.drawable.checkbox_on_background);
}else{
lt_model.setImgStatus(android.R.drawable.checkbox_off_background);
}
taskList.add(lt_model);
}
mTaskListView.setAdapter(new CustomAdapter(dailyNew, taskList));
cursor.close();
db.close();
}
and this is my problem.
When I add the second task the title of first task would change with that, and this is repeated for the others rows.
When you iterate through your cursor, you need to make a new Model for each row, so you're adding a distinct object each time.
while (cursor.moveToNext()) {
LT_Model lt_model = new LT_Model();

Custom Adapter not working for the listview from Parse.com

I am trying to create an android application using a database from Parse.com. I am using a custom adapter to create a listview. I don't find any errors with the code and yet the listeview is not showing up. Nothing there in the logcat as well. Just the listview does not show up.
lv = (ListView)findViewById(R.id.listView);
mProgress = (ProgressBar)findViewById(R.id.check_progress);
mProgress.setVisibility(View.VISIBLE);
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Sellers");
query.orderByAscending("Name");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> parseObjects, ParseException e) {
if (e == null) {
studentsList = new ArrayList<Sellers>();
for (ParseObject ob : parseObjects) {
s = new Sellers();
s.setName(ob.getString("Name").toString());
s.setAddress1(ob.getString("Address1").toString());
s.setAddress2(ob.getString("Address2").toString());
s.setShopName(ob.getString("ShopName").toString());
s.setEmail(ob.getString("Email").toString());
s.setPhone(ob.getString("Phone").toString());
s.setZipcode(ob.getString("Zipcode").toString());
studentsList.add(s);
}
adapter = new ListviewAdapter(CheckStatus.this, studentsList);
lv.setAdapter(adapter);
mProgress.setVisibility(View.GONE);
} else {
mProgress.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
This is the activity where I am invoking the listview.
public class ListviewAdapter extends BaseAdapter{
private final static String TAG = ListviewAdapter.class.getSimpleName();
private Context activity;
private LayoutInflater inflater = null;
private List<Sellers> sellers;
int layout;
public ListviewAdapter(Context activity, List<Sellers> sellers) {
this.activity = activity;
this.sellers = sellers;
inflater = LayoutInflater.from(activity);
}
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public class ViewHolder {
TextView name ;
TextView shop ;
TextView address1 ;
TextView address2;
TextView phone;
TextView email;
RelativeLayout rl;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
View v =view;
ViewHolder holder = new ViewHolder();
if (view == null) {
LayoutInflater li = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = li.inflate(R.layout.list_item_layout,null);
holder.name = (TextView)v.findViewById(R.id.seller_name);
holder.shop = (TextView)v.findViewById(R.id.shop_name);
holder.address1 = (TextView)v.findViewById(R.id.address1);
holder.address2 = (TextView)v.findViewById(R.id.address2);
holder.phone = (TextView)v.findViewById(R.id.phone);
holder.email = (TextView)v.findViewById(R.id.emailID);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
Sellers s = sellers.get(position);
// String a = s.Name;
// Log.d(TAG, a);
holder.name.setText(s.getName());
holder.shop.setText(s.getShopName());
holder.address1.setText(s.getAddress1());
holder.address2.setText(s.getAddress2());
holder.phone.setText(s.getPhone());
holder.email.setText(s.getEmail());
Log.d("CustomAdapter.class", "CustomAdapter");
// imageView.setImageDrawable(s.getPic());
return v;
}
}
And this is the custom adapter. There are no null pointer exceptions showing up in the logcat. I can't determine why the listview is not getting populated.
Try this;
#Override
public int getCount() {
return sellers.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position:
}
You have to implement your code on getCount() by return number of item listview will be created.

Categories

Resources