Custom ListView + getView method - java

I need help with custom adapter with getView() method. When adapter create a list in getView() method called every time rendering like holder.textEpisode.setTextColor() etc. This gives heavy load and the list begins to slow down.
Please help me solve this problem. Thanks!
public class myAdapterDouble extends ArrayAdapter<Order> {
private int[] colorWhite = new int[] { -0x1 };
private int[] colors = new int[] { -0x1, -0x242425 };
private int[] colorBlack = new int[] { -0x1000000 };
private int[] colorTransparent = new int[] { android.R.color.transparent };
private LayoutInflater lInflater;
private ArrayList<Order> data;
private Order o;
private DisplayImageOptions options;
private ImageLoader imageLoader;
private ImageLoaderConfiguration config;
private Context ctx;
private Typeface tf;
public myAdapterDouble(Context c, int listItem, ArrayList<Order> data) {
super(c, listItem, data);
lInflater = LayoutInflater.from(c);
this.data = data;
ctx = c;
tf = Typeface.createFromAsset(ctx.getAssets(), "meiryo.ttc");
imageLoader = ImageLoader.getInstance();
options = new DisplayImageOptions.Builder()
.showStubImage(R.drawable.no_image)
.showImageForEmptyUri(R.drawable.no_image).cacheOnDisc()
.cacheInMemory().build();
config = new ImageLoaderConfiguration.Builder(c.getApplicationContext())
.threadPriority(Thread.NORM_PRIORITY - 2)
.memoryCacheSize(2 * 1024 * 1024) // 2 Mb
.memoryCacheExtraOptions(100, 100)
.denyCacheImageMultipleSizesInMemory()
.discCacheFileNameGenerator(new Md5FileNameGenerator())
.tasksProcessingOrder(QueueProcessingType.LIFO).enableLogging()
.build();
ImageLoader.getInstance().init(config);
}
SharedPreferences sharedPref;
boolean posters, fixFont;
float headerSize, timeSize, dateSize;
int imageWSize;
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
o = data.get(position);
sharedPref = PreferenceManager.getDefaultSharedPreferences(ctx);
posters = sharedPref.getBoolean("poster", true);
fixFont = sharedPref.getBoolean("fix_font", false);
if (convertView == null) {
convertView = lInflater.inflate(R.layout.double_list_item, null);
holder = new ViewHolder();
holder.textName = (TextView) convertView.findViewById(R.id.text);
if (fixFont) {
try {
holder.textName.setTypeface(tf);
} catch (Exception e) {
Toast.makeText(ctx, e.toString(), Toast.LENGTH_SHORT).show();
}
} else {
try {
holder.textName.setTypeface(Typeface.DEFAULT);
} catch (Exception e) {
Toast.makeText(ctx, e.toString(), Toast.LENGTH_SHORT).show();
}
}
holder.textEpisode = (TextView) convertView.findViewById(R.id.text2);
holder.img = (ImageView) convertView.findViewById(R.id.image);
String width = sharedPref.getString("image_width", "70");
imageWSize = Integer.parseInt(width); // ширина
final float scale = getContext().getResources().getDisplayMetrics().density;
int px = (int) (imageWSize*scale + 0.5f);
holder.img.getLayoutParams().height = LayoutParams.WRAP_CONTENT;
holder.img.getLayoutParams().width = px;
if(imageWSize == 0) {
holder.img.getLayoutParams().width = LayoutParams.WRAP_CONTENT;
}
holder.img.setPadding(5, 5, 5, 5);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
headerSize = Float.parseFloat(sharedPref.getString("headsize", "20"));
holder.textName.setTextSize(headerSize); // размер названия
timeSize = Float.parseFloat(sharedPref.getString("timesize", "15"));
holder.textEpisode.setTextSize(timeSize); // размер времени
if (posters) {
holder.img.setVisibility(View.VISIBLE);
try {
imageLoader.displayImage(o.getLink(), holder.img, options);
} catch (NullPointerException e) {
e.printStackTrace();
}
} else {
holder.img.setVisibility(View.GONE);
}
holder.img.setTag(o);
holder.textName.setText(o.getTextName());
holder.textEpisode.setText(o.getTextEpisode());
holder.textEpisode.setTextColor(Color.BLACK);
if (o.getTextEpisode().toString().contains(ctx.getString(R.string.final_ep))) {
String finaleColor = sharedPref.getString("finale_color", "1");
if (finaleColor.contains("default")) {
holder.textEpisode.setTextColor(Color.parseColor("#2E64FE"));
}
if (finaleColor.contains("yelow")) {
holder.textEpisode.setTextColor(Color.YELLOW);
}
if (finaleColor.contains("red")) {
holder.textEpisode.setTextColor(Color.RED);
}
if (finaleColor.contains("green")) {
holder.textEpisode.setTextColor(Color.GREEN);
}
if (finaleColor.contains("white")) {
holder.textEpisode.setTextColor(Color.WHITE);
}
if (finaleColor.contains("gray")) {
holder.textEpisode.setTextColor(Color.GRAY);
}
} else {
holder.textEpisode.setTextColor(Color.parseColor("#2E64FE"));
}
String chooseColor = sharedPref.getString("colorList", "");
if (chooseColor.contains("white")) {
int colorPos = position % colorWhite.length;
convertView.setBackgroundColor(colorWhite[colorPos]);
}
if (chooseColor.contains("black")) {
int colorPos = position % colorBlack.length;
convertView.setBackgroundColor(colorBlack[colorPos]);
holder.textName.setTextColor(Color.parseColor("#FFFFFF"));
}
if (chooseColor.contains("whitegray")) {
int colorPos = position % colors.length;
convertView.setBackgroundColor(colors[colorPos]);
}
if (chooseColor.contains("transparent")) {
int colorPos = position % colorTransparent.length;
convertView.setBackgroundColor(colorTransparent[colorPos]);
}
return convertView;
}

getView() method will be called every time when u do a scroll for loading next items.
sharedPref = PreferenceManager.getDefaultSharedPreferences(ctx);
posters = sharedPref.getBoolean("poster", true);
fixFont = sharedPref.getBoolean("fix_font", false);
This should slow the scroll since every time it need to read and parse the preference.
Have all those preferences been loaded once as some variables.
If that still does not solved the problem that try Method Profiling and check whats Incl% for the getView Method and see which methods is taking more cpu usage in getView.
EDITED
public class myAdapterDouble extends ArrayAdapter<Order> {
private int[] colorWhite = new int[] { -0x1 };
private int[] colors = new int[] { -0x1, -0x242425 };
private int[] colorBlack = new int[] { -0x1000000 };
private int[] colorTransparent = new int[] { android.R.color.transparent };
private LayoutInflater lInflater;
private ArrayList<Order> data;
private Order o;
private DisplayImageOptions options;
private ImageLoader imageLoader;
private ImageLoaderConfiguration config;
private Context ctx;
private Typeface tf;
boolean posters, fixFont;
float headerSize, timeSize, dateSize;
int imageWSize;
private String finaleColor;
private String chooseColor;
private String final_ep;
public myAdapterDouble(Context c, int listItem, ArrayList<Order> data) {
super(c, listItem, data);
lInflater = LayoutInflater.from(c);
this.data = data;
ctx = c;
tf = Typeface.createFromAsset(ctx.getAssets(), "meiryo.ttc");
imageLoader = ImageLoader.getInstance();
options = new DisplayImageOptions.Builder().showStubImage(R.drawable.no_image).showImageForEmptyUri(R.drawable.no_image).cacheOnDisc().cacheInMemory().build();
config = new ImageLoaderConfiguration.Builder(c.getApplicationContext()).threadPriority(Thread.NORM_PRIORITY - 2).memoryCacheSize(2 * 1024 * 1024)
// 2 Mb
.memoryCacheExtraOptions(100, 100).denyCacheImageMultipleSizesInMemory().discCacheFileNameGenerator(new Md5FileNameGenerator()).tasksProcessingOrder(QueueProcessingType.LIFO)
.enableLogging().build();
ImageLoader.getInstance().init(config);
SharedPreferences sharedPref;
sharedPref = PreferenceManager.getDefaultSharedPreferences(ctx);
posters = sharedPref.getBoolean("poster", true);
fixFont = sharedPref.getBoolean("fix_font", false);
String width = sharedPref.getString("image_width", "70");
imageWSize = Integer.parseInt(width); // ширина
headerSize = Float.parseFloat(sharedPref.getString("headsize", "20"));
timeSize = Float.parseFloat(sharedPref.getString("timesize", "15"));
finaleColor = sharedPref.getString("finale_color", "1");
chooseColor = sharedPref.getString("colorList", "");
final_ep = ctx.getString(R.string.final_ep);
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
o = data.get(position);
if (convertView == null) {
convertView = lInflater.inflate(R.layout.double_list_item, null);
holder = new ViewHolder();
holder.textName = (TextView) convertView.findViewById(R.id.text);
if (fixFont) {
try {
holder.textName.setTypeface(tf);
}
catch (Exception e) {
Toast.makeText(ctx, e.toString(), Toast.LENGTH_SHORT).show();
}
}
else {
try {
holder.textName.setTypeface(Typeface.DEFAULT);
}
catch (Exception e) {
Toast.makeText(ctx, e.toString(), Toast.LENGTH_SHORT).show();
}
}
holder.textEpisode = (TextView) convertView.findViewById(R.id.text2);
holder.img = (ImageView) convertView.findViewById(R.id.image);
final float scale = getContext().getResources().getDisplayMetrics().density;
int px = (int) (imageWSize * scale + 0.5f);
holder.img.getLayoutParams().height = LayoutParams.WRAP_CONTENT;
holder.img.getLayoutParams().width = px;
if (imageWSize == 0) {
holder.img.getLayoutParams().width = LayoutParams.WRAP_CONTENT;
}
holder.img.setPadding(5, 5, 5, 5);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
holder.textName.setTextSize(headerSize); // размер названия
holder.textEpisode.setTextSize(timeSize); // размер времени
if (posters) {
holder.img.setVisibility(View.VISIBLE);
try {
imageLoader.displayImage(o.getLink(), holder.img, options);
}
catch (NullPointerException e) {
e.printStackTrace();
}
}
else {
holder.img.setVisibility(View.GONE);
}
holder.img.setTag(o);
holder.textName.setText(o.getTextName());
holder.textEpisode.setText(o.getTextEpisode());
holder.textEpisode.setTextColor(Color.BLACK);
if (o.getTextEpisode().toString().contains()) {
if (finaleColor.contains("default")) {
holder.textEpisode.setTextColor(Color.parseColor("#2E64FE"));
}
if (finaleColor.contains("yelow")) {
holder.textEpisode.setTextColor(Color.YELLOW);
}
if (finaleColor.contains("red")) {
holder.textEpisode.setTextColor(Color.RED);
}
if (finaleColor.contains("green")) {
holder.textEpisode.setTextColor(Color.GREEN);
}
if (finaleColor.contains("white")) {
holder.textEpisode.setTextColor(Color.WHITE);
}
if (finaleColor.contains("gray")) {
holder.textEpisode.setTextColor(Color.GRAY);
}
}
else {
holder.textEpisode.setTextColor(Color.parseColor("#2E64FE"));
}
if (chooseColor.contains("white")) {
int colorPos = position % colorWhite.length;
convertView.setBackgroundColor(colorWhite[colorPos]);
}
if (chooseColor.contains("black")) {
int colorPos = position % colorBlack.length;
convertView.setBackgroundColor(colorBlack[colorPos]);
holder.textName.setTextColor(Color.parseColor("#FFFFFF"));
}
if (chooseColor.contains("whitegray")) {
int colorPos = position % colors.length;
convertView.setBackgroundColor(colors[colorPos]);
}
if (chooseColor.contains("transparent")) {
int colorPos = position % colorTransparent.length;
convertView.setBackgroundColor(colorTransparent[colorPos]);
}
return convertView;
}
}

try like this instead of viewholder this works perfectly for me.
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
sharedPref = PreferenceManager.getDefaultSharedPreferences(ctx);
posters = sharedPref.getBoolean("poster", true);
fixFont = sharedPref.getBoolean("fix_font", false);
if (v == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.double_list_item, null);
}
TextView textName = (TextView) v.findViewById(R.id.text);
if (fixFont){
try {
textName.setTypeface(tf);
} catch (Exception e) {
Toast.makeText(ctx, e.toString(), Toast.LENGTH_SHORT).show();
}
}else {
try {
textName.setTypeface(Typeface.DEFAULT);
} catch (Exception e) {
Toast.makeText(ctx, e.toString(), Toast.LENGTH_SHORT).show();
}
}
return super.getView(position, v, parent);
}
};
I hope this will help you.

Related

Why List for Recyclerview returning same items in all positions? [duplicate]

This question already has answers here:
Why does my ArrayList contain N copies of the last item added to the list?
(5 answers)
Closed 5 years ago.
In my android app, I am using recycler view to show items.
(Note: This is not a duplicate question because I tried many answers from stackoverflow but no solution.)
My Problem
The recycler view showing repeated items. A single item is repeating many times even though it occurs only single time in the source DB.
I checked for the reason and note that the List object in Adapter class returning same values in all iterations. But the Fragment that sends List object to adapter class having unique values.
But only the adapter class after receiving the List object contains duplicate items
Solutions I tried
I checked Stackoverflow and added getItemId(int position) and getItemViewType(int position) in adaptor class but no solution
I checked the DB and also List view sending class both dont have duplicate items.
My Code:
InboxHostFragment.java = This class sends List object to adaptor class of recycler view:
public class HostInboxFragment extends Fragment {
View hostinbox;
Toolbar toolbar;
ImageView archive, alert, search;
TextView blank;
Bundle args = new Bundle();
private static final String TAG = "Listinbox_host";
private InboxHostAdapter adapter;
String Liveurl = "";
RelativeLayout layout, host_inbox;
String country_symbol;
String userid;
String login_status, login_status1;
ImageButton back;
String roomid;
RecyclerView listView;
String name = "ramesh";
private int start = 1;
private List < ListFeed > movieList = new ArrayList < > ();
String currency1;
// RecyclerView recyclerView;
public HostInboxFragment() {
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#RequiresApi(api = Build.VERSION_CODES.M)
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
hostinbox = inflater.inflate(R.layout.fragment_host_inbox, container, false);
FontChangeCrawler fontChanger = new FontChangeCrawler(getContext().getAssets(), getString(R.string.app_font));
fontChanger.replaceFonts((ViewGroup) hostinbox);
SharedPreferences prefs = getActivity().getSharedPreferences(Constants.MY_PREFS_NAME, MODE_PRIVATE);
userid = prefs.getString("userid", null);
currency1 = prefs.getString("currenycode", null);
toolbar = (Toolbar) hostinbox.findViewById(R.id.toolbar);
archive = (ImageView) hostinbox.findViewById(R.id.archive);
alert = (ImageView) hostinbox.findViewById(R.id.alert);
search = (ImageView) hostinbox.findViewById(R.id.search);
blank = (TextView) hostinbox.findViewById(R.id.blank);
host_inbox = (RelativeLayout) hostinbox.findViewById(R.id.host_inbox);
layout.setVisibility(View.INVISIBLE);
start = 1;
final String url = Constants.DETAIL_PAGE_URL + "payment/host_reservation_inbox?userto=" + userid + "&start=" + start + "&common_currency=" + currency1;
//*******************************************ListView code start*****************************************************
System.out.println("url in Inbox page===" + url);
movieList.clear();
JsonObjectRequest movieReq = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener < JSONObject > () {
#SuppressWarnings("deprecation")
#Override
public void onResponse(JSONObject response) {
// progressBar.setVisibility(View.GONE);
// Parsing json
// for (int i = 0; i < response.length(); i++) {
try {
JSONArray contact = response.getJSONArray("contact");
obj_contact = contact.optJSONObject(0);
login_status1 = obj_contact.getString("Status");
// progressBar.setVisibility(View.VISIBLE);
layout.setVisibility(View.INVISIBLE);
listView.setVisibility(View.VISIBLE);
host_inbox.setBackgroundColor(Color.parseColor("#FFFFFF"));
ListFeed movie = new ListFeed();
for (int i = 0; i < contact.length(); i++) {
JSONObject obj1 = contact.optJSONObject(i);
movie.getuserby(obj1.getString("userby"));
movie.resid(obj1.getString("reservation_id"));
movie.setresidinbox(obj1.getString("reservation_id"));
System.out.println("reservation iddgdsds" + obj1.getString("reservation_id"));
movie.setuserbys(obj1.getString("userby"));
movie.setuserto(obj1.getString("userto"));
movie.setid(obj1.getString("room_id"));
movie.getid1(obj1.getString("id"));
movie.userto(obj1.getString("userto"));
movie.isread(obj1.getString("isread"));
movie.userbyname(obj1.getString("userbyname"));
country_symbol = obj1.getString("currency_code");
Currency c = Currency.getInstance(country_symbol);
country_symbol = c.getSymbol();
movie.setsymbol(country_symbol);
movie.setTitle(obj1.getString("title"));
movie.setThumbnailUrl(obj1.getString("profile_pic"));
movie.setstatus(obj1.getString("status"));
movie.setcheckin(obj1.getString("checkin"));
movie.setcheckout(obj1.getString("checkout"));
movie.setcreated(obj1.getString("created"));
movie.guest(obj1.getString("guest"));
movie.userbyname(obj1.getString("username"));
movie.getprice(obj1.getString("price"));
String msg = obj1.getString("message");
msg = msg.replaceAll("<b>You have a new contact request from ", "");
msg = msg.replaceAll("</b><br><br", "");
msg = msg.replaceAll("\\w*\\>", "");
movie.message(msg);
movieList.add(movie);
System.out.println(movieList.get(i).message()); // returning unique values
adapter.notifyDataSetChanged();
}
}
} catch (JSONException e) {
e.printStackTrace();
// progressBar.setVisibility(View.GONE);
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
stopAnim();
//progressBar.setVisibility(View.GONE);
if (error instanceof NoConnectionError) {
Toast.makeText(getActivity(),
"Check your Internet Connection",
Toast.LENGTH_LONG).show();
}
//progressBar.setVisibility(View.GONE);
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
movieReq.setRetryPolicy(new DefaultRetryPolicy(5000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
return hostinbox;
}
#Override
public void onStop() {
Log.w(TAG, "App stopped");
super.onStop();
}
#Override
public void onDestroy() {
super.onDestroy();
}
public boolean isOnline(Context c) {
ConnectivityManager cm = (ConnectivityManager) c
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
return ni != null && ni.isConnected();
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
In the above code , System.out.println(movieList.get(i).message()); returning unique values without any problem.
Inboxhostadapter.java = This is the adapter for recycleview
public class InboxHostAdapter extends RecyclerView.Adapter < InboxHostAdapter.CustomViewHolder > {
private List < ListFeed > feedItemList;
private ListFeed listFeed = new ListFeed();
String userid = "",
tag,
str_currency;
String reservation_id,
Liveurl,
india2 = "0";
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
String currency1;
String status1;
//private Activity activity;
public Context activity;
public InboxHostAdapter(Context activity, List < ListFeed > feedItemList, String tag) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(activity);
Liveurl = sharedPreferences.getString("liveurl", null);
userid = sharedPreferences.getString("userid", null);
currency1 = sharedPreferences.getString("currenycode", null);
this.feedItemList = feedItemList; // returning duplicate items
this.activity = activity;
listFeed = new ListFeed();
this.tag = tag;
SharedPreferences prefs1 = activity.getSharedPreferences(Constants.MY_PREFS_LANGUAGE, MODE_PRIVATE);
str_currency = prefs1.getString("currencysymbol", null);
if (str_currency == null) {
str_currency = "$";
}
}
#Override
public InboxHostAdapter.CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.hostinbox, parent, false);
FontChangeCrawler fontChanger = new FontChangeCrawler(activity.getAssets(), activity.getString(R.string.app_font_light));
fontChanger.replaceFonts((ViewGroup) view);
return new CustomViewHolder(view);
}
#Override
public void onBindViewHolder(InboxHostAdapter.CustomViewHolder holder, int position) {
// This block returning duplicate items
listFeed = feedItemList.get(position); // This list feedItemList returning duplicate items
reservation_id = listFeed.getid();
System.out.println("reservation id after getting in inbox adapter" + reservation_id);
System.out.println("check out after getting" + listFeed.getcheckout());
System.out.println("message after getting in inbox adapter" + listFeed.getTitle());
System.out.println("symbol after getting" + listFeed.getsymbol());
System.out.println("username after getting" + listFeed.getaddress());
System.out.println("price after getting" + listFeed.getprice());
System.out.println("status after getting" + listFeed.getstatus());
System.out.println("check in after getting" + listFeed.getcheckin());
System.out.println("check out after getting" + listFeed.getcheckout());
System.out.println("userby after getting====" + listFeed.getuserby());
System.out.println("message after getting====" + listFeed.message());
String msg;
msg = listFeed.message();
holder.name.setText(listFeed.userbyname());
holder.time.setText(listFeed.getcreated());
holder.date1.setText(listFeed.getcheckin());
holder.date2.setText(listFeed.getcheckout());
if (listFeed.guest().equals("1")) {
holder.guest.setText(listFeed.guest() + activity.getResources().getString(R.string.guests));
} else {
holder.guest.setText(listFeed.guest() + activity.getResources().getString(R.string.guests));
}
if (tag.equals("Listinbox_service_host")) {
holder.guest.setText("");
holder.ttt.setVisibility(View.INVISIBLE);
} else {
holder.guest.setText(listFeed.guest() + activity.getResources().getString(R.string.guests));
}
// holder.status.setText(listFeed.getstatus());
holder.title.setText(listFeed.getTitle());
status1 = listFeed.getstatus();
if (status1.equals("Accepted")) {
holder.status.setText(activity.getResources().getString(R.string.accepted_details));
}
} else if (status1.equals("Contact Host")) {
holder.status.setText(activity.getResources().getString(R.string.Contact_Host));
holder.guestmsg.setText(listFeed.message());
} else {
holder.status.setText(status1);
}
if (currency1 == null) {
currency1 = "$";
}
if (listFeed.getprice() != null && !listFeed.getprice().equals("null")) {
DecimalFormat money = new DecimalFormat("00.00");
money.setRoundingMode(RoundingMode.UP);
india2 = money.format(new Double(listFeed.getprice()));
holder.currency.setText(listFeed.getsymbol() + " " + india2);
holder.currency.addTextChangedListener(new NumberTextWatcher(holder.currency));
}
//view.imgViewFlag.setImageResource(listFlag.get(position));
System.out.println("listview price" + listFeed.getprice());
System.out.println("listview useds" + listFeed.getresidinbox());
System.out.println("listview dffdd" + listFeed.getuserbys());
System.out.println("listview dfffdgjf" + listFeed.getuserto());
//holder.bucket.setTag(position);
System.out.println("Activity name" + tag);
holder.inbox.setTag(position);
holder.inbox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = (int) v.getTag();
Intent search = new Intent(activity, Inbox_detailshost.class);
search.putExtra("userid", userid);
search.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(search);
System.out.println("listview useds" + listFeed.getresidinbox());
System.out.println("listview dffdd" + listFeed.getuserbys());
System.out.println("listview dfffdgjf" + listFeed.getuserto());
}
});
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public int getItemCount() {
System.out.println("list item size" + feedItemList.size());
return (null != feedItemList ? feedItemList.size() : 0);
}
#Override
public int getItemViewType(int position) {
return position;
}
class CustomViewHolder extends RecyclerView.ViewHolder {
ImageView thumbNail;
TextView name, time, date1, date2, currency, guest, status, title, ttt, guestmsg;
RelativeLayout inbox;
CustomViewHolder(View view) {
super(view);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
this.thumbNail = (ImageView) view.findViewById(R.id.list_image);
this.name = (TextView) view.findViewById(R.id.title2);
this.time = (TextView) view.findViewById(R.id.TextView4);
this.date1 = (TextView) view.findViewById(R.id.TextView2);
this.date2 = (TextView) view.findViewById(R.id.TextView22);
this.currency = (TextView) view.findViewById(R.id.TextView23);
this.guest = (TextView) view.findViewById(R.id.TextView25);
this.ttt = (TextView) view.findViewById(R.id.TextView24);
this.status = (TextView) view.findViewById(R.id.TextView26);
this.title = (TextView) view.findViewById(R.id.TextView28);
this.inbox = (RelativeLayout) view.findViewById(R.id.inbox);
this.guestmsg = (TextView) view.findViewById(R.id.guestmessage);
}
}
public class NumberTextWatcher implements TextWatcher {
private DecimalFormat df;
private DecimalFormat dfnd;
private boolean hasFractionalPart;
private TextView et;
public NumberTextWatcher(TextView et) {
df = new DecimalFormat("#,###");
df.setDecimalSeparatorAlwaysShown(true);
dfnd = new DecimalFormat("#,###.##");
this.et = et;
hasFractionalPart = false;
}
#SuppressWarnings("unused")
private static final String TAG = "NumberTextWatcher";
#Override
public void afterTextChanged(Editable s) {
et.removeTextChangedListener(this);
try {
int inilen, endlen;
inilen = et.getText().length();
String v = s.toString().replace(String.valueOf(df.getDecimalFormatSymbols().getGroupingSeparator()), "");
Number n = df.parse(v);
int cp = et.getSelectionStart();
if (hasFractionalPart) {
et.setText(df.format(n));
} else {
et.setText(dfnd.format(n));
}
endlen = et.getText().length();
int sel = (cp + (endlen - inilen));
if (sel > 0 && sel <= et.getText().length()) {
et.setSelected(true);
}
} catch (NumberFormatException nfe) {
// do nothing?
} catch (ParseException e) {
// do nothing?
}
et.addTextChangedListener(this);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.toString().contains(String.valueOf(df.getDecimalFormatSymbols().getDecimalSeparator()))) {
hasFractionalPart = true;
} else {
hasFractionalPart = false;
}
}
}
}
In the above code , feedItemList returning duplicate values eventhogh the movieList list from source clas Inboxfragment.java contains unique values.
Kindly please help me with this issue. I tried many answers in Stackoverflow but I can't get solutions. I can't figure out the problem.
Use this code
for (int i = 0; i < contact.length(); i++) {
JSONObject obj1 = contact.optJSONObject(i);
ListFeed movie = new ListFeed();
movie.getuserby(obj1.getString("userby"));
movie.resid(obj1.getString("reservation_id"));
movie.setresidinbox(obj1.getString("reservation_id"));
System.out.println("reservation iddgdsds" + obj1.getString("reservation_id"));
movie.setuserbys(obj1.getString("userby"));
movie.setuserto(obj1.getString("userto"));
movie.setid(obj1.getString("room_id"));
movie.getid1(obj1.getString("id"));
movie.userto(obj1.getString("userto"));
movie.isread(obj1.getString("isread"));
movie.userbyname(obj1.getString("userbyname"));
country_symbol = obj1.getString("currency_code");
Currency c = Currency.getInstance(country_symbol);
country_symbol = c.getSymbol();
movie.setsymbol(country_symbol);
movie.setTitle(obj1.getString("title"));
movie.setThumbnailUrl(obj1.getString("profile_pic"));
movie.setstatus(obj1.getString("status"));
movie.setcheckin(obj1.getString("checkin"));
movie.setcheckout(obj1.getString("checkout"));
movie.setcreated(obj1.getString("created"));
movie.guest(obj1.getString("guest"));
movie.userbyname(obj1.getString("username"));
movie.getprice(obj1.getString("price"));
String msg = obj1.getString("message");
msg = msg.replaceAll("<b>You have a new contact request from ", "");
msg = msg.replaceAll("</b><br><br", "");
msg = msg.replaceAll("\\w*\\>", "");
movie.message(msg);
movieList.add(movie);
System.out.println(movieList.get(i).message()); // returning unique value
}
Declare ListFeed movie = new ListFeed(); into the for Loop
And remove the adapter.notifyDataSetChanged(); from for Loop.
I think this help you.

java for loop is done more than needed

So I have a for loop to make my listview big enough to not scroll, I used this loop from #HussoM. The Cursor returns 3 rows but the for loop run sometimes 7 times and sometimes 10 times.
class dayAdapter extends CursorAdapter {
public dayAdapter(Context context, Cursor c) {
super(context, c);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View view = LayoutInflater.from(context).inflate(R.layout.day_item, parent, false);
dayAdapterViewHolder viewHolder = new dayAdapterViewHolder();
viewHolder.dayTitle = (TextView) view.findViewById(R.id.dayTitle);
viewHolder.transactionList = (ListView) view.findViewById(R.id.day_list);
view.setTag(viewHolder);
return view;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
dayAdapterViewHolder dayAdapterViewHolder = (dayAdapter.dayAdapterViewHolder) view.getTag();
Calendar calendar = Calendar.getInstance();
DatabaseHelper dbHelper = new DatabaseHelper(context);
int day = cursor.getInt(cursor.getColumnIndexOrThrow(dbHelper.COLUMN_DATE_DAY));
calendar.set(year - 1900, month, day);
Date date = new Date(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
DateFormat dateFormat = DateFormat.getDateInstance();
dayAdapterViewHolder.dayTitle.setText(dateFormat.format(date));
DayItemAdapter dayItemAdapter = new DayItemAdapter(context, dbHelper.GetTransactionsInDay(day, month, year));
dayAdapterViewHolder.transactionList.setAdapter(dayItemAdapter);
setListViewHeightBasedOnItemsForDays(dayAdapterViewHolder.transactionList);
}
private class dayAdapterViewHolder {
TextView dayTitle;
ListView transactionList;
}
private class DayItemAdapter extends CursorAdapter {
public DayItemAdapter(Context context, Cursor c) {
super(context, c);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View view = LayoutInflater.from(context).inflate(R.layout.transaction_item, parent, false);
DayAdapterViewHolder viewHolder = new DayAdapterViewHolder();
viewHolder.icon = (ImageView) view.findViewById(R.id.transactionIcon);
viewHolder.amount = (TextView) view.findViewById(R.id.amountText);
viewHolder.category = (TextView) view.findViewById(R.id.categoryText);
view.setTag(viewHolder);
return view;
}
#Override
public void bindView(View view, final Context context, Cursor cursor) {
DatabaseHelper dbHelper = new DatabaseHelper(context);
final Utils utils = new Utils();
DayAdapterViewHolder viewHolder = (DayAdapterViewHolder) view.getTag();
TextView category = viewHolder.category;
final ImageView icon = viewHolder.icon;
final int type = cursor.getInt(cursor.getColumnIndexOrThrow(dbHelper.COLUMN_ENTRY_TYPE));
final int entryCategory = cursor.getInt(cursor.getColumnIndexOrThrow(dbHelper.COLUMN_ENTRY_CATEGORY));
final int entrySubCategory = cursor.getInt(cursor.getColumnIndexOrThrow(dbHelper.COLUMN_ENTRY_SUBCATEGORY));
if (entrySubCategory == -1) {
category.setText(utils.expense_and_incomeCategories(context).get(type).get(entryCategory).getCategoryName());
icon.post(new Runnable() {
#Override
public void run() {
icon.setImageResource(utils.expense_and_incomeCategories(context).get(type).get(entryCategory).getCategoryIcon());
}
});
} else {
category.setText(utils.expense_and_incomeCategories(context).get(type).get(entryCategory).getSubCategories().get(entrySubCategory).getSubCategoryName());
icon.post(new Runnable() {
#Override
public void run() {
icon.setImageResource(utils.expense_and_incomeCategories(context).get(type).get(entryCategory).getSubCategories().get(entrySubCategory).getSubCategoryIcon());
}
});
}
String amountString;
TextView amountText = viewHolder.amount;
double amount = cursor.getDouble(cursor.getColumnIndexOrThrow(dbHelper.COLUMN_AMOUNT));
if (amount > 1000 * 1000) {
String editedAmount;
DecimalFormat df = new DecimalFormat("#.#");
df.setRoundingMode(RoundingMode.HALF_UP);
editedAmount = df.format(amount / (1000 * 1000));
amountString = editedAmount + "Mn";
} else if (amount > 1000) {
String editedAmount;
DecimalFormat df = new DecimalFormat("#.#");
df.setRoundingMode(RoundingMode.HALF_UP);
editedAmount = df.format(amount / (1000));
amountString = editedAmount + "K";
} else {
DecimalFormat df = new DecimalFormat("#.#");
df.setRoundingMode(RoundingMode.HALF_UP);
amountString = df.format(amount);
}
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
amountText.setText(dbHelper.getCountryABV(preferences.getLong("country", 1)) + " " + amountString);
}
private class DayAdapterViewHolder {
ImageView icon;
TextView category;
TextView amount;
}
}
and here's the setListViewHeightBasedOnItems() method
public boolean setListViewHeightBasedOnItems(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter != null) {
int numberOfItems = listAdapter.getCount();
// Get total height of all items.
int totalItemsHeight = 0;
for (int itemPos = 0; itemPos < numberOfItems; itemPos++) {
View item = listAdapter.getView(itemPos, null, listView);
item.measure(0, 0);
totalItemsHeight += item.getMeasuredHeight();
}
// Get total height of all item dividers.
int totalDividersHeight = listView.getDividerHeight() *
(numberOfItems - 1);
// Set list height.
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalItemsHeight + totalDividersHeight;
listView.setLayoutParams(params);
listView.requestLayout();
return true;
} else {
return false;
}
}

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

Mutiple Contact Picker not working in Android api level less than 17

I have a code to read the contacts from the inbuilt phone contacts and it displays all the contacts in a list view in my app.The user can select multiple contacts and display them in another activity.
This code works fine in Android API level 18 and above,but gives an error in the versions below API 18.
I'm attaching the code of the contact picker activity and its adapter.
Error Logcat
private void getSelectedContacts() {
// TODO Auto-generated method stub
StringBuffer sb = new StringBuffer();
dataBase=mHelper.getWritableDatabase();
ContentValues values=new ContentValues();
for (ContactObject bean : ContactsListClass.phoneList) {
if (bean.isSelected()) {
sb.append(bean.getName());
sb.append(bean.getNumber());
sb.append("1");
values.put(DbHelper.KEY_FNAME,bean.getName());
values.put(DbHelper.KEY_LNAME,bean.getNumber() );
values.put(DbHelper.KEY_INVITE,"1" );
dataBase.insert(DbHelper.TABLE_NAME, null, values);
}
}
dataBase.close();
String s = sb.toString().trim();
if (TextUtils.isEmpty(s)) {
Toast.makeText(context, "Select atleast one Contact",
Toast.LENGTH_SHORT).show();
} else {
s = s.substring(0, s.length() - 1);
/**
Toast.makeText(context, "Selected Contacts : " + s,
Toast.LENGTH_SHORT).show();
**/
Intent i = new Intent(Contacts_main.this, MainActivity.class);
i.putExtra("NAME", name);
i.putExtra("EVT_Name", event_name);
i.putExtra("EVT_Date", event_date);
startActivity(i);
}
}
private void addContactsInList() {
// TODO Auto-generated method stub
Thread thread = new Thread() {
#Override
public void run() {
showPB();
try {
Cursor phones = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null, null, null, null);
try {
ContactsListClass.phoneList.clear();
} catch (Exception e) {
}
while (phones.moveToNext()) {
String phoneName = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String phoneImage = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
//String pImage =
ContactObject cp = new ContactObject();
cp.setName(phoneName);
cp.setNumber(phoneNumber);
cp.setImage(phoneImage);
//cp.setImage(getResources(R.drawable.prof_active));
ContactsListClass.phoneList.add(cp);
}
phones.close();
lv = new ListView(context);
lv.setDividerHeight(0);
lv.setDivider(null);
lv.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
llContainer.addView(lv);
}
});
Collections.sort(ContactsListClass.phoneList,
new Comparator<ContactObject>() {
#Override
public int compare(ContactObject lhs,
ContactObject rhs) {
return lhs.getName().compareTo(
rhs.getName());
}
});
objAdapter = new ContactsAdapter(Contacts_main.this,
ContactsListClass.phoneList);
lv.setAdapter(objAdapter); //ERROR SHOWING HERE
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
CheckBox chk = (CheckBox) view
.findViewById(R.id.contactcheck);
ContactObject bean = ContactsListClass.phoneList
.get(position);
if (bean.isSelected()) {
bean.setSelected(false);
chk.setChecked(false);
} else {
bean.setSelected(true);
chk.setChecked(true);
}
}
});
} catch (Exception e) {
// e.printStackTrace();
//Toast.makeText(context, "Crash",Toast.LENGTH_SHORT).show();
}
hidePB();
}
};
thread.start();
}
Adapter Class:
Context mContext;
LayoutInflater inflater;
private List<ContactObject> mainDataList = null;
private List<ContactObject> mainInviteesList = null;
private ArrayList<ContactObject> arraylist;
private DbHelper mHelper;
private SQLiteDatabase dataBase;
public ContactsAdapter(Context context, List<ContactObject> mainDataList) {
mContext = context;
this.mainDataList = mainDataList;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<ContactObject>();
this.arraylist.addAll(mainDataList);
mHelper=new DbHelper(context);
}
static class ViewHolder {
protected TextView name;
protected TextView number;
protected CheckBox check;
protected ImageView image;
protected EditText invitees;
}
#Override
public int getCount() {
return mainDataList.size();
}
#Override
public ContactObject getItem(int position) {
return mainDataList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.list_row, null);
holder.name = (TextView) view.findViewById(R.id.contactname);
holder.number = (TextView) view.findViewById(R.id.contactno);
holder.check = (CheckBox) view.findViewById(R.id.contactcheck);
holder.image = (ImageView) view.findViewById(R.id.contactimage);
holder.invitees = (EditText) view.findViewById(R.id.editInvites);
view.setTag(holder);
view.setTag(R.id.contactname, holder.name);
view.setTag(R.id.contactno, holder.number);
view.setTag(R.id.contactcheck, holder.check);
view.setTag(R.id.editInvites, holder.invitees);
holder.check
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton vw,
boolean isChecked) {
int getPosition = (Integer) vw.getTag();
mainDataList.get(getPosition).setSelected(
vw.isChecked());
/**
dataBase=mHelper.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(DbHelper.KEY_FNAME,mainDataList.get(getPosition).getName());
values.put(DbHelper.KEY_LNAME,mainDataList.get(getPosition).getNumber());
values.put(DbHelper.KEY_INVITE,"1" );
dataBase.insert(DbHelper.TABLE_NAME, null, values);
dataBase.close();
**/
}
});
// holder.invitees.addTextChangedListener(watcher);
} else {
holder = (ViewHolder) view.getTag();
}
holder.check.setTag(position);
//holder.invitees.setTag(position);
holder.name.setText(mainDataList.get(position).getName());
holder.number.setText(mainDataList.get(position).getNumber());
if(getByteContactPhoto(mainDataList.get(position).getImage())==null){
holder.image.setImageResource(R.drawable.prof_active);
}else{
holder.image.setImageBitmap(getByteContactPhoto(mainDataList.get(position).getImage()));
}
holder.check.setChecked(mainDataList.get(position).isSelected());
return view;
}
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
mainDataList.clear();
if (charText.length() == 0) {
mainDataList.addAll(arraylist);
} else {
for (ContactObject wp : arraylist) {
if (wp.getName().toLowerCase(Locale.getDefault())
.contains(charText)) {
mainDataList.add(wp);
}
}
}
notifyDataSetChanged();
}
public Bitmap getByteContactPhoto(String contactId) {
Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, Long.parseLong(contactId));
Uri photoUri = Uri.withAppendedPath(contactUri, Contacts.Photo.CONTENT_DIRECTORY);
Cursor cursor = mContext.getContentResolver().query(photoUri,
new String[] {Contacts.Photo.DATA15}, null, null, null);
if (cursor == null) {
return null;
}
try {
if (cursor.moveToFirst()) {
byte[] data = cursor.getBlob(0);
if (data != null) {
return BitmapFactory.decodeStream( new ByteArrayInputStream(data));
}
}
} finally {
cursor.close();
}
return null;
}
}

Custom BaseAdapter with different row layouts, convertView is null

I can't figure out why I am getting a NullPointerException with my custom BaseAdapter with different row types. I am using the ViewHolder pattern and when I get this NPE, the ViewHolder is null. But looking at my code below, wouldn't there always be a reference to a ViewHolder?
Using getItemViewType should always return a valid row layout, and I cover all of these types in the first switch statement which handles the inflating of the rows.
This line is the issues that is giving me the problem:
case TYPE_TEXT_YOU:
if (message != null) holder.message.setText(message);
It is weird because it was working fine before. I didn't change much but now it is giving me this issue. Please help!!!
public class ChatAdapter extends BaseAdapter {
private static final int TYPE_TEXT_YOU = 0;
private static final int TYPE_AUDIO_YOU = 1;
private static final int TYPE_TEXT_THEM = 2;
private static final int TYPE_AUDIO_THEM = 3;
private static final int TYPE_MATCH_NOTICE = 4;
private static final int TYPE_EMPTY_ROW = 5;
private Context mContext;
private List<ChatMessage> mMessages;
private String mPartnerUserId;
private SharedPrefs mPrefs;
private DatabaseHelper mDb;
private User mUser;
private User mPartnerUser;
private AudioHelper mAudioHelper;
public ChatAdapter(Context context, List<ChatMessage> messages, String partnerUserId) {
mContext = context;
mMessages = messages;
mPartnerUserId = partnerUserId;
mPrefs = new SharedPrefs(context);
mAudioHelper = AudioHelper.getInstance(context, partnerUserId);
mDb = DatabaseHelper.getInstance(context);
mUser = mDb.getUser(mPrefs.getUserId());
mPartnerUser = mDb.getUser(partnerUserId);
}
#Override
public int getCount() {
return mMessages.size();
}
#Override
public Object getItem(int position) {
return mMessages.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
ChatMessage message = mMessages.get(position);
switch (message.getMessageType()) {
case ChatMessage.TYPE_GAME_DATE:
return TYPE_MATCH_NOTICE;
case ChatMessage.TYPE_TEXT:
if (message.getSenderUserId().equals(mPrefs.getUserId())) {
return TYPE_TEXT_YOU;
}
else {
return TYPE_TEXT_THEM;
}
case ChatMessage.TYPE_AUDIO:
if (message.getSenderUserId().equals(mPrefs.getUserId())) {
return TYPE_AUDIO_YOU;
}
else {
return TYPE_AUDIO_THEM;
}
default:
return TYPE_EMPTY_ROW;
}
}
#Override
public int getViewTypeCount() {
return 6;
}
public class ViewHolder {
private ImageView avatar;
private CustomTextView timestamp;
private CustomTextView message;
private CustomTextView date;
private CustomTextView time;
private LinearLayout btnPlayAudio;
private ImageView ivPlayAudio;
private ProgressBar spinPlayingAudio;
private CustomTextView tvPlayAudio;
private ImageView gameCover;
private ProgressBar spinGameCover;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
int type = getItemViewType(position);
if (convertView == null) {
holder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context
.LAYOUT_INFLATER_SERVICE);
switch (type) {
case TYPE_TEXT_YOU:
convertView = inflater.inflate(R.layout.row_chat_you, parent, false);
holder.avatar = (ImageView) convertView.findViewById(R.id.avatar_you);
holder.message = (CustomTextView) convertView.findViewById(R.id.message_you);
holder.timestamp = (CustomTextView) convertView.findViewById(R.id.timestamp_you);
break;
case TYPE_AUDIO_YOU:
convertView = inflater.inflate(R.layout.row_chat_audio_you, parent, false);
holder.avatar = (ImageView) convertView.findViewById(R.id.avatar_you);
holder.timestamp = (CustomTextView) convertView.findViewById(R.id.timestamp_you);
holder.btnPlayAudio = (LinearLayout) convertView.findViewById(R.id.btn_play_audio_you);
holder.ivPlayAudio = (ImageView) convertView.findViewById(R.id.iv_play_audio);
holder.spinPlayingAudio = (ProgressBar) convertView.findViewById(R.id.spin_playing_audio);
holder.tvPlayAudio = (CustomTextView) convertView.findViewById(R.id.tv_play_audio);
break;
case TYPE_TEXT_THEM:
convertView = inflater.inflate(R.layout.row_chat_them, parent, false);
holder.avatar = (ImageView) convertView.findViewById(R.id.avatar_them);
holder.message = (CustomTextView) convertView.findViewById(R.id.message_them);
holder.timestamp = (CustomTextView) convertView.findViewById(R.id.timestamp_them);
break;
case TYPE_AUDIO_THEM:
convertView = inflater.inflate(R.layout.row_chat_audio_them, parent, false);
holder.avatar = (ImageView) convertView.findViewById(R.id.avatar_them);
holder.timestamp = (CustomTextView) convertView.findViewById(R.id.timestamp_them);
holder.btnPlayAudio = (LinearLayout) convertView.findViewById(R.id.btn_play_audio_them);
holder.ivPlayAudio = (ImageView) convertView.findViewById(R.id.iv_play_audio);
holder.spinPlayingAudio = (ProgressBar) convertView.findViewById(R.id.spin_playing_audio);
holder.tvPlayAudio = (CustomTextView) convertView.findViewById(R.id.tv_play_audio);
break;
case TYPE_MATCH_NOTICE:
convertView = inflater.inflate(R.layout.row_chat_match_notice, parent, false);
holder.gameCover = (ImageView) convertView.findViewById(R.id.game_cover);
holder.spinGameCover = (ProgressBar) convertView.findViewById(R.id.spin_game_cover);
holder.date = (CustomTextView) convertView.findViewById(R.id.date);
holder.time = (CustomTextView) convertView.findViewById(R.id.time);
break;
case TYPE_EMPTY_ROW:
convertView = inflater.inflate(R.layout.row_padding_10dp, parent, false);
break;
}
convertView.setTag(holder);
}
else holder = (ViewHolder) convertView.getTag();
String message = mMessages.get(position).getMessage();
String timestamp = mMessages.get(position).getTimeStamp();
final String audioFilepath = mMessages.get(position).getFilepath();
DateTime dateTime;
DateTimeFormatter formatter = DateTimeFormat.forPattern(GlobalVars.FORMAT_MESSAGE_TIMESTAMP);
final ViewHolder finalHolder = holder;
switch (type) {
case TYPE_TEXT_YOU:
if (message != null) holder.message.setText(message);
if (timestamp != null && !timestamp.isEmpty()) {
try {
dateTime = ISODateTimeFormat.dateTime().parseDateTime(timestamp);
if (dateTime != null) holder.timestamp.setText(formatter.print(dateTime));
}
catch (IllegalArgumentException e) { e.printStackTrace(); }
}
if (mUser != null && mUser.getAvatarType() != null && !mUser.getAvatarType().isEmpty()) {
try {
holder.avatar.setImageDrawable(mContext.getResources().getDrawable(ViewHelper
.getAvatarHeadDrawableId(mContext, mUser.getAvatarType())));
}
catch (Resources.NotFoundException e) { e.printStackTrace(); }
}
break;
case TYPE_AUDIO_YOU:
if (timestamp != null && !timestamp.isEmpty()) {
try {
dateTime = ISODateTimeFormat.dateTime().parseDateTime(timestamp);
if (dateTime != null) holder.timestamp.setText(formatter.print(dateTime));
}
catch (IllegalArgumentException e) { e.printStackTrace(); }
}
if (mUser != null && mUser.getAvatarType() != null && !mUser.getAvatarType().isEmpty()) {
try {
holder.avatar.setImageDrawable(mContext.getResources().getDrawable(ViewHelper
.getAvatarHeadDrawableId(mContext, mUser.getAvatarType())));
}
catch (Resources.NotFoundException e) { e.printStackTrace(); }
}
holder.btnPlayAudio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (audioFilepath != null && !audioFilepath.isEmpty()) {
mAudioHelper.changeViewsOfStoppedAudioMessage();
mAudioHelper.setPlayingAudioViews(finalHolder.ivPlayAudio,
finalHolder.spinPlayingAudio, finalHolder.tvPlayAudio);
mAudioHelper.playAudio(audioFilepath);
}
}
});
break;
case TYPE_TEXT_THEM:
if (message != null) holder.message.setText(message);
if (timestamp != null && !timestamp.isEmpty()) {
try {
dateTime = ISODateTimeFormat.dateTime().parseDateTime(timestamp);
if (dateTime != null) holder.timestamp.setText(formatter.print(dateTime));
}
catch (IllegalArgumentException e) { e.printStackTrace(); }
}
if (mPartnerUser != null && mPartnerUser.getAvatarType() != null) {
try {
holder.avatar.setImageDrawable(mContext.getResources().getDrawable(ViewHelper
.getAvatarHeadDrawableId(mContext, mPartnerUser.getAvatarType())));
}
catch (Resources.NotFoundException e) { e.printStackTrace(); }
}
break;
case TYPE_AUDIO_THEM:
if (timestamp != null && !timestamp.isEmpty()) {
try {
dateTime = ISODateTimeFormat.dateTime().parseDateTime(timestamp);
if (dateTime != null) holder.timestamp.setText(formatter.print(dateTime));
}
catch (IllegalArgumentException e) { e.printStackTrace(); }
}
if (mPartnerUser != null && mPartnerUser.getAvatarType() != null) {
try {
holder.avatar.setImageDrawable(mContext.getResources().getDrawable(ViewHelper
.getAvatarHeadDrawableId(mContext, mPartnerUser.getAvatarType())));
}
catch (Resources.NotFoundException e) { e.printStackTrace(); }
}
holder.btnPlayAudio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (audioFilepath != null && !audioFilepath.isEmpty()) {
mAudioHelper.changeViewsOfStoppedAudioMessage();
mAudioHelper.setPlayingAudioViews(finalHolder.ivPlayAudio,
finalHolder.spinPlayingAudio, finalHolder.tvPlayAudio);
mAudioHelper.playAudio(audioFilepath);
}
}
});
break;
case TYPE_MATCH_NOTICE:
if (message != null) {
if (message.contains("{")) {
Bundle info = null;
message = message.substring(message.indexOf("{"));
try {
JSONObject obj = new JSONObject(message);
info = JsonHelper.parseMatchNoticeMessageJson(obj);
}
catch (JSONException e) { e.printStackTrace(); }
if (info != null) {
if (info.containsKey(GlobalVars.KEY_GAME) && info.containsKey(GlobalVars
.KEY_PLATFORM)) {
Game game = mDb.getGame(info.getString(GlobalVars.KEY_GAME),
info.getString(GlobalVars.KEY_PLATFORM));
if (game != null && game.getCoverPhoto() != null) {
ViewHelper.loadOrDownloadGameCover(mContext, game.getCoverPhoto(),
holder.gameCover, holder.spinGameCover);
}
}
if (info.containsKey(GlobalVars.KEY_GAME_TIME)) {
String matchTime = info.getString(GlobalVars.KEY_GAME_TIME);
if (matchTime != null && !matchTime.isEmpty()) {
try {
dateTime = ISODateTimeFormat.dateTime().parseDateTime(matchTime);
if (dateTime != null) {
holder.date.setText(DateTimeFormat.forPattern(GlobalVars
.FORMAT_DATE_WITH_DAY_OF_WEEK).print(dateTime));
holder.time.setText(DateTimeFormat.forPattern(GlobalVars
.FORMAT_TIME).print(dateTime));
}
}
catch (IllegalArgumentException e) { e.printStackTrace(); }
}
}
}
}
}
break;
}
return convertView;
}
public void refreshList(List<ChatMessage> updatedMessages) {
mMessages.clear();
mMessages.addAll(updatedMessages);
this.notifyDataSetChanged();
}
}
My Stacktrace
java.lang.NullPointerException
at com.walintukai.lovelup.adapters.ChatAdapter$ViewHolder.access$100(ChatAdapter.java:118)
at com.walintukai.lovelup.adapters.ChatAdapter.getView(ChatAdapter.java:201)
at android.widget.HeaderViewListAdapter.getView(HeaderViewListAdapter.java:230)
at android.widget.AbsListView.obtainView(AbsListView.java:2739)
at android.widget.ListView.makeAndAddView(ListView.java:1801)
at android.widget.ListView.fillUp(ListView.java:733)
at android.widget.ListView.fillGap(ListView.java:670)
at android.widget.AbsListView.trackMotionScroll(AbsListView.java:6747)
at android.widget.AbsListView.scrollIfNeeded(AbsListView.java:3988)
at android.widget.AbsListView.onTouchMove(AbsListView.java:4840)
at android.widget.AbsListView.onTouchEvent(AbsListView.java:4668)
at android.view.View.dispatchTouchEvent(View.java:8135)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2417)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2141)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2423)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2156)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2423)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2156)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2423)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2156)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2423)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2156)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2423)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2156)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2423)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2156)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2423)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2156)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2423)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2156)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2423)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2156)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2423)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2156)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2423)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2156)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2423)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2156)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2423)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2156)
at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2295)
at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1622)
at android.app.Activity.dispatchTouchEvent(Activity.java:2565)
at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:2243)
at android.view.View.dispatchPointerEvent(View.java:8343)
at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:4743)
at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:4609)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4167)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4221)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4190)
at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:4301)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4198)
at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:4358)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4167)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4221)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4190)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4198)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4167)
at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:6517)
at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:6434)
at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:6405)
at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:6370)
at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:6597)
at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:185)
at android.os.MessageQueue.nativePollOnce(MessageQueue.java)
at android.os.MessageQueue.next(MessageQueue.java:138)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:5579)
at java.lang.reflect.Method.invokeNative(Method.java)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
at dalvik.system.NativeStart.main(NativeStart.java)
Played around and found my answer. So I guess some of the tags of the rows were null so it would call the else statement with the convertView.getTag() which was coming up null.
The solution is to check also if convertView.getTag() == null like so:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
int type = getItemViewType(position);
if (convertView == null || convertView.getTag() == null) {
...
}
else {
holder = (ViewHolder) convertView.getTag();
}

Categories