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;
}
}
Related
I'm creating an app where I have radio group with three radio buttons. What I want is when I check the radio button I need to get the id value of that radio button and save it in array or database and then count the id value.
For example i have this radiogroup in 19 fragment. which is each radiobutton has id value. if the button selected, it will get the id and store it so i can count the selected id value.
this is the display of my stepperstone
My StepFragment
Bundle bundle = this.getArguments();
Log.d("##", "onCreateView: " + bundle.getInt(MyStepperAdapter.CURRENT_STEP_POSITION_KEY)) ;
View view = inflater.inflate(R.layout.fragment_step_fragment_example, container, false);
mRadioGroup = view.findViewById(R.id.radioGroupWrapper);
mRadioGroup.getCheckedRadioButtonId();
DatabaseHelper mDBHelper = new DatabaseHelper(getContext());
Log.d("#######", String.valueOf(bundle.getInt(MyStepperAdapter.CURRENT_STEP_POSITION_KEY)));
final List<Klasifikasi> lk = mDBHelper.getListKlasifikasiByGroup(String.valueOf(Integer.valueOf(bundle.getInt(MyStepperAdapter.CURRENT_STEP_POSITION_KEY)) + 1));
final RadioButton[] rb = new RadioButton[lk.size()];
Log.d("##sz", "onCreateView: " + lk.size()) ;
int[][] states = new int[][] {
new int[] { android.R.attr.state_enabled}, // enabled
new int[] {-android.R.attr.state_enabled}, // disabled
new int[] {-android.R.attr.state_checked}, // unchecked
new int[] { android.R.attr.state_pressed} // pressed
};
int[] colors = new int[] {
Color.BLACK,
Color.BLACK,
Color.BLACK,
Color.BLACK
};
mRadioButton1 = view.findViewById(R.id.checkbox1);
mRadioButton2 = view.findViewById(R.id.checkbox2);
mRadioButton3 = view.findViewById(R.id.checkbox3);
if(lk.size() > 0) {
Klasifikasi kl0 = lk.get(0);
Klasifikasi kl1 = lk.get(1);
Klasifikasi kl2 = lk.get(2);
mRadioButton1.setText(kl0.getKlasifikasi());
mRadioButton2.setText(kl1.getKlasifikasi());
mRadioButton3.setText(kl2.getKlasifikasi());
}
My StepperAdapter
public static final String CURRENT_STEP_POSITION_KEY = "CURRENT_STEP_POSITION_KEY";
public MyStepperAdapter(FragmentManager fm, Context context) {
super(fm, context);
}
#Override
public Step createStep(int position) {
final StepFragmentExample step = new StepFragmentExample();
Bundle b = new Bundle();
b.putInt(CURRENT_STEP_POSITION_KEY, position);
step.setArguments(b);
return step;
}
#Override
public int getCount() {
return 19;
}
#NonNull
#Override
public StepViewModel getViewModel(#IntRange(from = 0) int position) {
//Override this method to set Step title for the Tabs, not necessary for other stepper types
return new StepViewModel.Builder(context)
.setTitle("Fragment " + getCount()) //can be a CharSequence instead
.create();
}
ListKlasifikasiAdapter
public ListKlasifikasiAdapter.KlasifikasiViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
LayoutInflater layoutInflater = LayoutInflater.from(viewGroup.getContext());
View view = layoutInflater.inflate(R.layout.item_listklasifikasi, viewGroup, false);
KlasifikasiViewHolder klasifikasiViewHolder = new KlasifikasiViewHolder(view);
klasifikasiViewHolder.setIsRecyclable(false);
return klasifikasiViewHolder;
}
#Override
public void onBindViewHolder(#NonNull KlasifikasiViewHolder klasifikasiViewHolder, int i) {
final List<Klasifikasi> lk = mDBHelper.getListKlasifikasiByGroup(String.valueOf(mKlasifikasiList.get(i).getGroup_index()));
final RadioButton[] rb = new RadioButton[lk.size()];
for (int j = 0; j < lk.size(); j++) {
Klasifikasi kl = lk.get(j);
rb[j] = new RadioButton(mContext);
rb[j].setId(j);
rb[j].setText(kl.getKlasifikasi());
klasifikasiViewHolder.radioGroup.addView(rb[j]);
}
}
class KlasifikasiViewHolder extends RecyclerView.ViewHolder {
private RadioGroup radioGroup;
public KlasifikasiViewHolder(#NonNull View itemView) {
super(itemView);
radioGroup = itemView.findViewById(R.id.radioGroupWrapper);
}
}
MyDatabaseHelper
public List<Klasifikasi> getListKlasifikasiByGroup(String index){
Klasifikasi klasifikasi = null;
List<Klasifikasi> klasifikasiList = new ArrayList<>();
openDatabase();
Cursor cursor = mDatabase.rawQuery("SELECT * FROM klasifikasi k WHERE k.group_index = ? ORDER BY k.kategori_id ASC", new String[] {index});
cursor.moveToFirst();
while (!cursor.isAfterLast()){
klasifikasi = new Klasifikasi(cursor.getInt(0),cursor.getString(1),cursor.getString(2),cursor.getString(3), cursor.getInt(4));
klasifikasiList.add(klasifikasi);
cursor.moveToNext();
}
cursor.close();
closeDatabase();
ga ada yg jawab T^T cries in the corner
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.
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;
}
}
I am creating an events. Also I am creating time tables. Events are created based on time table id. Dynamic event view I have created to show events.
I have created two tables for this events and time table. And loaded events from database.
Now I have loaded the events from time table witch is enabled. I have set color to time tables. This color I want to show on events with respected time table id.
I tried to load this color using Time table's object.
But I have used for loop so it's showing color of last time table to all events.
How can I set color to event's with respected time table id?
Monday fragment :
public class Mon extends Fragment {
private EventTableHelper mDb;
private Intent i;
private ViewGroup dayplanView;
private int minutesFrom,minutesTo;
private List<EventData> events;
private List<View> list;
private List<TimeTable> tables;
private LayoutInflater inflater;
public boolean editMode;
private RelativeLayout container;
private View eventView;
private TimeTableHelper tableHelper;
int color;
private boolean mCheckFragment;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_mon, container, false);
list = new ArrayList<View>();
dayplanView = (ViewGroup) view.findViewById(R.id.hoursRelativeLayout);
showEvents();
mCheckFragment = true;
return view;
}
private void createEvent(LayoutInflater inflater, ViewGroup dayplanView, int fromMinutes, int toMinutes, String title,String location,final int id,int color,String notification) {
eventView = inflater.inflate(R.layout.event_view, dayplanView, false);
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) eventView.getLayoutParams();
container = (RelativeLayout) eventView.findViewById(R.id.container);
TextView tvTitle = (TextView) eventView.findViewById(R.id.textViewTitle);
list.add(eventView);
ImageView notify = (ImageView) eventView.findViewById(R.id.notify);
((GradientDrawable) eventView.getBackground()).setColor(color);
tvTitle.setTextColor(Color.parseColor("#FFFFFF"));
if (tvTitle.getParent() != null)
((ViewGroup) tvTitle.getParent()).removeView(tvTitle);
if(notification == null)
{
notify.setVisibility(View.GONE);
}
else {
notify.setVisibility(View.VISIBLE);
}
if(location.equals(""))
{
tvTitle.setText("Event : " + title);
} else {
tvTitle.setText("Event : " + title + " (At : " + location +")");
}
int distance = (toMinutes - fromMinutes);
layoutParams.topMargin = dpToPixels(fromMinutes + 9);
layoutParams.height = dpToPixels(distance);
eventView.setLayoutParams(layoutParams);
dayplanView.addView(eventView);
container.addView(tvTitle);
eventView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
i = new Intent(getActivity(), AddEventActivity.class);
editMode = true;
i.putExtra("EditMode", editMode);
i.putExtra("id", id);
startActivityForResult(i, 1);
}
});
}
public void showEvents()
{
tableHelper = new TimeTableHelper(getActivity());
tables = tableHelper.getAllTables();
for (TimeTable table : tables) {
int tableId = table.getId();
int status = table.getStatus();
if(status == 1) {
color = table.getTableColor();
}
mDb = new EventTableHelper(getActivity());
events = mDb.getTimeTableEvents("Mon", tableId);
}
for (EventData eventData : events) {
int id = eventData.getId();
String datefrom = eventData.getFromDate();
if (datefrom != null) {
String[] times = datefrom.substring(11, 16).split(":");
minutesFrom = Integer.parseInt(times[0]) * 60 + Integer.parseInt(times[1]);
}
String title = eventData.getTitle();
String location = eventData.getLocation();
String dateTo = eventData.getToDate();
String notification = eventData.getNotificationTime();
if (dateTo != null) {
//times = dateTo.substring(11,16).split(":");
String[] times1 = dateTo.substring(11, 16).split(":");
minutesTo = Integer.parseInt(times1[0]) * 60 + Integer.parseInt(times1[1]);
}
createEvent(inflater, dayplanView, minutesFrom, minutesTo, title, location, id, color, notification);
id++;
}
}
public void removeView()
{
for(int i=0; i<list.size(); i++)
{
View view = (View)list.get(i);
dayplanView.removeView(view);
}
}
private int dpToPixels(int dp) {
return (int) (dp * getResources().getDisplayMetrics().density);
}
#Override
public void onResume()
{
super.onResume();
if(mCheckFragment)
{
removeView();
showEvents();
}
}
}
EDIT:
public void showEvents()
{
tableHelper = new TimeTableHelper(getActivity());
tables = tableHelper.getAllTables();
int color = 0;
for (TimeTable table : tables) {
int tableId = table.getId();
int status = table.getStatus();
mDb = new EventTableHelper(getActivity());
events = mDb.getTimeTableEvents("Mon", tableId);
for (EventData eventData : events) {
int id = eventData.getId();
String datefrom = eventData.getFromDate();
if (datefrom != null) {
String[] times = datefrom.substring(11, 16).split(":");
minutesFrom = Integer.parseInt(times[0]) * 60 + Integer.parseInt(times[1]);
}
String title = eventData.getTitle();
String location = eventData.getLocation();
String dateTo = eventData.getToDate();
color = table.getTableColor();
String notification = eventData.getNotificationTime();
if (dateTo != null) {
//times = dateTo.substring(11,16).split(":");
String[] times1 = dateTo.substring(11, 16).split(":");
minutesTo = Integer.parseInt(times1[0]) * 60 + Integer.parseInt(times1[1]);
}
createEvent(inflater, dayplanView, minutesFrom, minutesTo, title, location, id, color, notification);
id++;
}
}
}
Thank you..
Try merging the two for loops together and see if that works..
as well as the color, it also looks like the events are set to the last table when it enters the second for loop.
for(TimeTable table : tables) {
// code from table for loop
// ...
for(EventData eventData : events) {
// code from event for loop.
// ...
}
}
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.