list view change item randomly - java

I have a listview that when I change the value of one item (count) with click on plus button, Everything is fine as long as the user do scroll down and show more items
And we see that on each page of the scroll has changed a value of item!!!
idont kNow why everything seems fine!!
public class MyAdapter extends BaseAdapter {
private String[] from;
ArrayList <HashMap<String, Object>> BuyList ;
private int[] to;
private Context context;
private ArrayList<HashMap<String, Object>> data ;
private ArrayList<HashMap<String, Object>> selecteddata;
private ArrayList<HashMap<String, Object>> fdata ;
private ImageView pay,more;
private EditText search;
private String user_mobile;
private TextView buy_toolbar_count;
private Holder holder;
// private HashMap<String, Object> hm;
public MyAdapter( Context context, ArrayList<HashMap<String, Object>> data,
ArrayList<HashMap<String, Object>> selecteddata , String[] from, int[] to, ArrayList Bylist,
ImageView pay, ImageView more, String user_mobile, TextView buy_count_toolbar, EditText search) {
this.data = data;
this.selecteddata = selecteddata;
this.fdata = new ArrayList<>(selecteddata);
this.context = context;
this.from = from;
this.to = to;
this.BuyList = Bylist;
this.pay = pay;
this.more = more;
this.search = search;
this.user_mobile = user_mobile;
this.buy_toolbar_count = buy_count_toolbar;
}
public void filter(String s, ImageView img) {
HashMap<String, Object> wp = new HashMap<>();
if (!s.equals("")) {
fdata.clear();
for (int i = 0 ;i<data.size();i++) {
wp = data.get(i);
// Log.i("mosi",wp.get("name").toString() + " wp ");
if (wp.get("name").toString().toLowerCase().contains(s)) {
fdata.add(wp);
}
}
}
else {
fdata = new ArrayList<>(selecteddata);
}
notifyDataSetChanged();
}
public class Holder
{
ImageView g_img;
ImageView plus;
ImageView mines;
TextView g_name;
TextView g_price;
TextView g_off;
TextView count;
TextView f_range;
TextView sum;
TextView temp2;
}
#Override
public int getCount() {
return fdata.size();
}
#Override
public HashMap<String, Object> getItem(int i) {
return fdata.get(i);
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
Typeface font_titr = Typeface.createFromAsset(context.getAssets(), "fonts/titr.TTF");
final HashMap<String, Object> hm = fdata.get(position);
if (convertView == null ) {
holder = new Holder();
convertView = LayoutInflater.from(context).
inflate(R.layout.my_row_layout2, parent, false);
holder.g_img = (ImageView) convertView.findViewById(R.id.f_img);
holder.g_name = (TextView) convertView.findViewById(R.id.f_name);
holder.g_price = (TextView) convertView.findViewById(R.id.f_price);
holder.g_off = (TextView) convertView.findViewById(R.id.f_off);
holder.count = (TextView) convertView.findViewById(R.id.f_count);
holder.f_range = (TextView) convertView.findViewById(R.id.f_kilo);
holder.plus = (ImageView) convertView.findViewById(R.id.plus_id_btn);
holder.mines = (ImageView) convertView.findViewById(R.id.mines_id_btn);
holder.sum = (TextView) convertView.findViewById(R.id.count_sum_id);
holder.temp2 = (TextView) convertView.findViewById(R.id.txt2);
//Date currentTime = Calendar.getInstance().getTime();
convertView.setTag(holder);
// Log.i("mosi",convertView.getTag() + " tagfffff " + hm.get("convertview"));
hm.put("convertview", "1");
}
else
{
holder = (Holder) convertView.getTag();
// Log.i("mosi",convertView.getTag() + " tag " + hm.get("convertview"));
}
final View tempview = convertView;
// set font++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
holder.g_price.setTypeface(font_titr, Typeface.NORMAL);
holder.g_name.setTypeface(font_titr, Typeface.BOLD);
holder.g_off.setTypeface(font_titr, Typeface.NORMAL);
holder.count.setTypeface(font_titr, Typeface.NORMAL);
holder.sum.setTypeface(font_titr, Typeface.NORMAL);
holder.temp2.setTypeface(font_titr, Typeface.NORMAL);
//----------------------------------------------------------------------------------------
// Set pre count and sum
holder.sum.setText(" میلغ کل : " + hm.get("sum").toString() + " تومان ");
holder.count.setText(hm.get("count").toString());
final String oldprice = hm.get("price").toString();
holder.g_off.setText(hm.get("off").toString());
holder.g_name.setText(hm.get("disc").toString());
holder.f_range.setText(hm.get("f_range").toString());
final float f=
(Float.valueOf(oldprice)*
Float.valueOf(holder.g_off.getText().toString()))/100;
// holder.g_price.setText(" قیمت : "+ DtoS((Float.valueOf(oldprice.toString()))-f)+" تومان ");
holder.g_price.setText(" قیمت : "+ oldprice +" تومان ");
File imageFile = new File(hm.get("image").toString());
if(imageFile.exists()){
holder.g_img.setImageBitmap(BitmapFactory.decodeFile(imageFile.getAbsolutePath()));
}
else
holder.g_img.setImageResource(R.drawable.coming_soon);
holder.plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
change_count(holder, hm, "p", tempview, ChangeType.DtoS((Float.valueOf(oldprice.toString())) - f), position);
}
});
holder.mines.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
change_count(holder, hm, "m", tempview , ChangeType.DtoS((Float.valueOf(oldprice.toString()))-f), position);
}
});
// Button Pay && More
pay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (BuyList.size() > 0) {
Intent intent = new Intent(context, Payment_act.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("data", BuyList);
intent.putExtra("all_data", data);
intent.putExtra("mobile", user_mobile);
view.getContext().startActivity(intent);
//
} else {
Toast.makeText(context, "سبد خرید شما خالی است", Toast.LENGTH_LONG).show();
}
}
});
more.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, Choose_act.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("blist", BuyList);
intent.putExtra("data", data);
intent.putExtra("mobile", user_mobile);
view.getContext().startActivity(intent);
// ((Activity)context).finish();
}
});
// Search -------------------------------------------------------------------
search.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence s, int i, int i1, int i2) {
// Log.i("mosi", s+" --- s ***");
// filter(s.toString(), holder.g_img);
}
#Override
public void afterTextChanged(Editable editable) {
}
});
return convertView;
}
// template
// Onclick for mines and plus Button
//#Override
public void change_count(final Holder holder1, HashMap<String, Object> hm_addtolist, String tag, View c_view, String oldprice, int position) {
// Log.i("mosi", position+" position on list ");
String is_pack = hm_addtolist.get("is_pack").toString();
ChangeType ch = new ChangeType();
double temp1 = 0;
double p_with_off = 0;
holder = (Holder) c_view.getTag();
String off = hm_addtolist.get("off").toString();
String num_sum = "0";
if (ch.stringToDouble(off)>0)
{
p_with_off = ch.stringToDouble(hm_addtolist.get("price_with_off").toString());
}
else
p_with_off = ch.stringToDouble(oldprice.toString());
holder.count= (TextView) c_view.findViewById(R.id.f_count);
holder.sum = (TextView) c_view.findViewById(R.id.count_sum_id);
if (!holder.count.getText().toString().equals("") && holder.count!= null)
temp1 = ch.stringToDouble(holder.count.getText().toString());
//my_alert("", temp1+"");
if (tag.equals("p")) {
if (is_pack.equals("1"))
temp1 = temp1 + 1;
else
temp1 = temp1 + 0.5;
// Log.i("mosi", " ::: set 2 !!!!");
holder.count.setText(DtoS(temp1));
num_sum = String.format("%d", (long)(temp1 * p_with_off));
holder.sum.setText(" میلغ کل : " + num_sum + " تومان ");
} else if (tag.equals("m")) {
if (is_pack.equals("1")) {
if (temp1 > 1) {
temp1 = (temp1 - 1);
holder.count.setText(DtoS(temp1));
num_sum = String.format("%d", (long) (temp1 * p_with_off));
holder.sum.setText(" میلغ کل : " + num_sum + " تومان ");
} else {
holder.count.setText("0");
holder.sum.setText("مبلغ کل : 0 تومان");
num_sum = "0";
BuyList.remove(hm_addtolist);
notifyDataSetChanged();
buy_toolbar_count.setText(String.valueOf(BuyList.size()));
}
}
else {
if (temp1 > 0.5) {
temp1 = (temp1 - 0.5);
holder.count.setText(DtoS(temp1));
num_sum = String.format("%d", (long) (temp1 * p_with_off));
holder.sum.setText(" میلغ کل : " + num_sum + " تومان ");
} else {
holder.count.setText("0");
holder.sum.setText("مبلغ کل : 0 تومان");
num_sum = "0";
hm_addtolist.put("count","0");
hm_addtolist.put("sum","0");
BuyList.remove(hm_addtolist);
notifyDataSetChanged();
buy_toolbar_count.setText(String.valueOf(BuyList.size()));
}
}
}
//}
if (!num_sum.equals("0")) {
hm_addtolist.put("sum", num_sum);
hm_addtolist.put("count", holder.count.getText().toString());
boolean check = false;
for (int i = 0; i < BuyList.size(); i++) {
if (BuyList.get(i).get("name").toString().equals(hm_addtolist.get("name").toString())) {
check = true;
HashMap<String, Object> temp_updatelist = BuyList.get(i);
temp_updatelist.put("sum", num_sum);
temp_updatelist.put("count", holder.count.getText().toString());
// BuyList.add(temp_updatelist);
// Log.i("mosi", "add count "+i+"");
// Toast.makeText(context, "ok", Toast.LENGTH_SHORT);
notifyDataSetChanged();
}
}
if (!check) {
// Log.i("mosi", "add count to :: "+hm_addtolist.get("name")+"");
BuyList.add(hm_addtolist);
buy_toolbar_count.setText(String.valueOf(BuyList.size()));
notifyDataSetChanged();
}
}
notifyDataSetChanged();
// Log.i("mosi", BuyList.toString());
// clearbug( c_view);
}
}
make list on activity
I have a listview that when I change the value of one item (count) with click on plus button, Everything is fine as long as the user do scroll down and show more items
And we see that on each page of the scroll has changed a value of item!!!
idont kNow why everything seems fine!!
private void setlist() {
ArrayList<HashMap<String, Object>> selected_data = new ArrayList<>();
for (int i = 0; i < all_data.size(); i++) {
if (all_data.get(i).get("type").toString().equals(mtag)) {
HashMap<String, Object> t = all_data.get(i);
selected_data.add(t);
}
}
//Log.i("mosi",selected_data.toString());
EditText search = (EditText) findViewById(R.id.et_search_id);
ImageView pay = (ImageView) findViewById(R.id.btn_pay_firstpage);
ImageView more = (ImageView) findViewById(R.id.btn_more_firstpage);
String[] from = {"image", "name", "price", "off"};
int[] to = {R.id.f_img, R.id.f_name, R.id.f_price, R.id.f_off};
final MyAdapter adb = new MyAdapter(getBaseContext(), all_data, selected_data, from, to, BuyList, pay, more, user_mobile, buyCount_toolbar, search);
lv.setAdapter(adb);
}
I have a listview that when I change the value of one item (count) with click on plus button, Everything is fine as long as the user do scroll down and show more items
And we see that on each page of the scroll has changed a value of item!!!
idont kNow why everything seems fine!!
its my activity layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layoutDirection="rtl"
android:background="#drawable/main_background_theme">
<include
android:id="#+id/mytoolbar"
layout="#layout/toolbar"
android:layout_height="?attr/actionBarSize"
android:layout_width="match_parent"/>
<include
android:id="#+id/app_message"
layout="#layout/message"
android:layout_height="30dp"
android:layout_width="match_parent"
android:layout_below="#+id/mytoolbar"/>
<include
android:id="#+id/searchbox_id"
layout="#layout/searchbox"
android:layout_height="40sp"
android:layout_width="match_parent"
android:layout_below="#+id/app_message"
android:visibility="invisible"/>
<android.support.v4.widget.DrawerLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/searchbox_id"
android:id="#+id/FirstPage_id">
<RelativeLayout
android:id="#+id/rv_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainLayoutActivity">
<ListView
android:id="#+id/my_listview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#color/listDivader"
android:dividerHeight="1dp"
android:paddingBottom="?attr/actionBarSize" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_alignBottom="#id/my_listview"
android:background="#color/toolbar_back"
android:orientation="horizontal">
<ImageView
android:id="#+id/btn_pay_firstpage"
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight="50"
android:paddingLeft="10sp"
android:src="#drawable/btn_pay" />
<ImageView
android:id="#+id/btn_more_firstpage"
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight="50"
android:paddingLeft="10sp"
android:src="#drawable/btn_more" />
</LinearLayout>
</RelativeLayout>
<fragment
android:layout_width="180dp"
android:layout_height="match_parent"
android:id="#+id/drawer_fragment"
android:layout_gravity="start"
android:layout="#layout/drawer_fragment_layout"
tools:layout="#layout/drawer_fragment_layout"
android:name="com.com.seyedi89gmail.sm.zanco.Drawer_fragment">
</fragment>
</android.support.v4.widget.DrawerLayout>
</RelativeLayout>

Remove notifyDataSetChanged from if-else conditions, May this will work
public void filter(String s, ImageView img) {
HashMap<String, Object> wp = new HashMap<>();
if (!s.equals("")) {
fdata.clear();
for (int i = 0 ;i<data.size();i++) {
wp = data.get(i);
if (wp.get("name").toString().toLowerCase().contains(s)) {
fdata.add(wp);
//notifyDataSetChanged();
}
}
}
else {
fdata = new ArrayList<>(selecteddata);
//notifyDataSetChanged();
}
notifyDataSetChanged();
}

you can use NestedScrollview outside the listview and stop the scrolling of listview by using this: smoothScrollBy(0, 0);

Related

Show hide alternate LinearLayouts when selecting RadioButton in 2 RadioGroups

Six RadioButtons aligned as 3 columns and 2 rows in a RadioGroup, so 6 RB-s in RG. If user selects a RB, right under it image1 and text1 are shown and under alternated RB-s image1 and text2 are also shown. User may select any RB. The proper behavior looks like that https://photos.app.goo.gl/NEqTaxsY6daxD3kJA
<android.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/bg">
<include layout="#layout/app_bar" />
<fragment
android:id="#+id/refreshLayoutFragment"
class="kz.fingram.RefreshLayoutFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:layout="#layout/fragment_refresh_layout" />
<LinearLayout
android:id="#+id/root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingEnd="#dimen/activity_margin"
android:paddingLeft="#dimen/activity_margin"
android:paddingRight="#dimen/activity_margin"
android:paddingStart="#dimen/activity_margin"
android:paddingTop="#dimen/activity_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/when_u_want_money"
android:textAppearance="#style/TextAppearance.Medium" />
<RadioGroup
android:id="#+id/months"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:background="#drawable/primary_transparent_round_bg"
android:orientation="horizontal"
app:setOnCheckedChangeListener="#{viewModel.mMonthOnCheckedChangeListener}" />
<LinearLayout
android:id="#+id/thisIs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="3dp"
android:orientation="horizontal" />
<RadioGroup
android:id="#+id/months2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:background="#drawable/primary_transparent_round_bg"
android:orientation="horizontal"
app:setOnCheckedChangeListener="#{viewModel.mMonthOnCheckedChangeListener2}" />
<LinearLayout
android:id="#+id/thatIs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="3dp"
android:orientation="horizontal" />
<Button
style="#style/Button.Primary"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:enabled="#{viewModel.mIsNextEnabled}"
android:onClick="#{viewModel::nextOnClick}"
android:text="#string/next" />
</LinearLayout>
</android.support.design.widget.CoordinatorLayout>
Java code:
RadioGroup rg1 = findViewById(R.id.months);
rg1.setOnCheckedChangeListener(null);
rg1.clearCheck();
rg1.setOnCheckedChangeListener(mMonthOnCheckedChangeListener);
View view = radioGroup.findViewById(i);
if (view != null) {
mMonth = (TeamFreeMonth) view.getTag();
}
selectMonth();
checkButtonsState();
public final class OptionsActivity extends BaseAppCompatActivity {
private ActivityOptionsBinding mBinding;
public static void show(#NonNull final Context ctx) {
StorageHelper.getInstance().setInvited(false);
BaseAppCompatActivity.show(ctx, OptionsActivity.class, true, false);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBinding = DataBindingUtil.setContentView(this, R.layout.activity_options);
setupToolbar();
mBinding.setViewModel(new ViewModel());
}
public final class ViewModel extends BaseObservable {
private static final int TERM_6_MONTH_ID = 1;
private static final int INSTALLMENT_10000_ID = 1;
private final RefreshLayoutFragment mRefreshLayout;
public boolean mIsNextEnabled;
public TeamFreeMonth mMonth;
private TeamFreeMonth[] mMonths;
ViewModel() {
mMonth = null;
mMonths = null;
mRefreshLayout = (RefreshLayoutFragment) getSupportFragmentManager()
.findFragmentById(R.id.refreshLayoutFragment);
mRefreshLayout.setup(mBinding.root, new RefreshLayoutFragment.Callback() {
#Override
public void reload() {
try {
loadData();
} catch (Exception e) {
ExceptionHelper.displayException(OptionsActivity.this, e);
}
}
});
public RadioGroup.OnCheckedChangeListener mMonthOnCheckedChangeListener =
new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, #IdRes int i) {
if (i != -1) {
RadioGroup rg2 = findViewById(R.id.months2);
rg2.setOnCheckedChangeListener(null);
rg2.clearCheck();
rg2.setOnCheckedChangeListener(mMonthOnCheckedChangeListener2);
View view = radioGroup.findViewById(i);
if (view != null) {
mMonth = (TeamFreeMonth) view.getTag();
}
selectMonth();
checkButtonsState();
}
}
};
public RadioGroup.OnCheckedChangeListener mMonthOnCheckedChangeListener2 =
new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, #IdRes int i) {
if (i != -1) {
RadioGroup rg1 = findViewById(R.id.months);
rg1.setOnCheckedChangeListener(null);
rg1.clearCheck();
rg1.setOnCheckedChangeListener(mMonthOnCheckedChangeListener);
View view = radioGroup.findViewById(i);
if (view != null) {
mMonth = (TeamFreeMonth) view.getTag();
}
selectMonth();
checkButtonsState();
}
}
};
private void refreshMonths() {
mBinding.months.removeAllViews();
mBinding.months.clearCheck();
mBinding.months2.removeAllViews();
mBinding.months2.clearCheck();
mBinding.thisIs.removeAllViews();
mBinding.thatIs.removeAllViews();
final TeamFreeMonth oldMonth = mMonth;
mMonth = null;
checkButtonsState();
if (mMonths == null) {
return;
}
final TeamFreeMonth[] months = mMonths;
if (months.length == 0) {
return;
}
int halfMonths = months.length / 2;
for (int i = 0; i < halfMonths; i++) {
final String date = UtilitiesHelper.dateToStr(months[i].getDate(), Constants.DATE_FORMAT_LLLL);// Получили месяц от даты
final String date2 = UtilitiesHelper.dateToStr(months[i + halfMonths].getDate(), Constants.DATE_FORMAT_LLLL);// Получили месяц от даты
if (TextUtils.isEmpty(date) || TextUtils.isEmpty(date2)) {
continue;
}
final RadioButton rb = (RadioButton) LayoutInflater.from(OptionsActivity.this).inflate(R.layout.radio_button_tab, mBinding.months, false);
rb.setId(i);
rb.setTag(months[i]);
final SpannableString btnCaption = new SpannableString(date);
btnCaption.setSpan(new AbsoluteSizeSpan(getResources().getDimensionPixelSize(R.dimen.font_size_18)), 0, date.length(), 0);
rb.setText(btnCaption);
final RadioButton rb2 = (RadioButton) LayoutInflater.from(OptionsActivity.this).inflate(R.layout.radio_button_tab, mBinding.months2, false);
rb2.setId(i + halfMonths);
rb2.setTag(months[i + halfMonths]);
final SpannableString btnCaption2 = new SpannableString(date2);
btnCaption2.setSpan(new AbsoluteSizeSpan(getResources().getDimensionPixelSize(R.dimen.font_size_18)), 0, date2.length(), 0);
rb2.setText(btnCaption2);
if (i == 0) {
rb.setBackgroundResource(R.drawable.ll_radio_button_start);
rb2.setBackgroundResource(R.drawable.ll_radio_button_start);
} else if (i == halfMonths - 1) {
rb.setBackgroundResource(R.drawable.ll_radio_button_end);
rb2.setBackgroundResource(R.drawable.ll_radio_button_end);
}
mBinding.months.addView(rb);
mBinding.months2.addView(rb2);
TextView thisIs = (TextView) LayoutInflater.from(OptionsActivity.this).inflate(R.layout.options_this_is_item, mBinding.thisIs, false);
thisIs.setId(rb.getId());
thisIs.setText(getString(R.string.thisIs));
thisIs.setVisibility(View.INVISIBLE);
mBinding.thisIs.addView(thisIs);
TextView thatIs = (TextView) LayoutInflater.from(OptionsActivity.this).inflate(R.layout.options_that_is_item, mBinding.thatIs, false);
thatIs.setId(rb2.getId());
thatIs.setText(getString(R.string.thatIs));
thatIs.setVisibility(View.INVISIBLE);
mBinding.thatIs.addView(thatIs);
if (oldMonth != null && UtilitiesHelper.isDateEquals(oldMonth.getDate(), months[i].getDate())) {
mBinding.months.check(rb.getId());
mBinding.months2.check(rb2.getId());
}
}
selectMonth();
}
private void selectMonth()
{
int selectedId1 = mBinding.months.getCheckedRadioButtonId();
int selectedId = selectedId1 !=-1 ? selectedId1 : mBinding.months2.getCheckedRadioButtonId();
int n = mBinding.months.getChildCount();
List<TextView> views = new ArrayList<TextView>();
for (int i = 0; i < n; i++) {
views.add(i, (TextView) mBinding.thisIs.getChildAt(i));
views.add(i+3, (TextView) mBinding.thatIs.getChildAt(i));
}
int length = views.size();
for (int i = 0; i < length; i++) {
TextView child = views.get(i);
}
private void checkButtonsState() {
mIsNextEnabled = mMonth != null;
notifyChange();
}
public void nextOnClick(final View view) {
try {
final TeamFreeMonth[] months = mMonths;
if (mMonth == null || months == null || months.length == 0) {
throw new Exception(getString(R.string.enter_month));
}
SettingsHelper.setTermId(OptionsActivity.this, TERM_6_MONTH_ID);//
SettingsHelper.setTermRateId(OptionsActivity.this, mMonth.getTermRateId());//
SettingsHelper.setInstallmentId(OptionsActivity.this, INSTALLMENT_10000_ID);
SettingsHelper.setGoalDateInMillis(OptionsActivity.this, mMonth.getDate().getTime());//дата получения
SettingsHelper.setFirstGoalDateInMillis(OptionsActivity.this, months[0].getDate().getTime());
SettingsHelper.setGoalSum(OptionsActivity.this, mMonth.getSum());
BaseAppCompatActivity.show(OptionsActivity.this, SetGoalActivity.class, true, false);
} catch (Exception e) {
ExceptionHelper.displayException(OptionsActivity.this, e);
}
}
private void loadData() {
try {
final AsyncTask<Void, Void, TeamFreeMonth[]> task = new AsyncTask<Void, Void, TeamFreeMonth[]>() {
private Exception mError = null;
#Override
protected void onPreExecute() {
mRefreshLayout.setRefreshing(true);
}
#Override
protected TeamFreeMonth[] doInBackground(Void... params) {
try {
TeamFreeMonth[] months = ServerHelper.getInstance().syncGetOptionMonths(OptionsActivity.this, TERM_6_MONTH_ID, INSTALLMENT_10000_ID);
if (months != null && months.length > 0)
return months;
} catch (Exception e) {
mError = e;
}
return null;
}
#Override
protected void onPostExecute(TeamFreeMonth[] result) {
try {
if (mError != null) {
throw mError;
}
mMonths = result;
refreshMonths();
checkButtonsState();
mRefreshLayout.setRefreshing(false);
} catch (Exception e) {
mRefreshLayout.setError(e);
}
}
};
task.execute();
} catch (Exception e) {
mRefreshLayout.setError(e);
}
}
}
}
Image1 is always the same, while text1 and text2 differ. Text1 'You' is shown under the selected RB and text2 'Your friend' - under alternating RB-s.
The quetion still is how to show/hide image1 and text 1 or text 2 alternatively?
I can show/hide image1 and text-s under RB-s which is in the same column, but not alternating RB-s.

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.

How get to all value of EditText in Custom ListView

Good day guys,
I successfully populated my custom-listview-layout in my activity,
but the problem is I can't get all the value of populated EditText in my listview, please help me what approach should I do,
thanks
Picture Adapter.java
public View getView(int position, View convertView, ViewGroup parent) {
View row;
row = convertView;
final dataHandler handler;
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate( R.layout.row_layout,parent, false);
handler = new dataHandler();
handler.pictures = (ImageView) row.findViewById(R.id.pictures);
handler.name = (TextView) row.findViewById(R.id.picturename);
handler.price= (EditText) row.findViewById(R.id.price);
handler.add = (Button) row.findViewById(R.id.btnplus);
handler.minus = (Button) row.findViewById(R.id.btnminus);
row.setTag(handler);
}else{
handler = (dataHandler) row.getTag();
}
PSP psp;
psp =(PSP) this.getItem(position);
Picasso.with(getContext()).load(psp.getPicture()).resize(200, 155).into(handler.pictures);
handler.name.setText(psp.getName());
handler.price.setText(psp.getPrice());
return row;
}
MainActivity.java
PictureAdapter adapter;
listView = (ListView) findViewById(R.id.ls);
adapter = new PictureAdapter(this,R.layout.row_layout);
listView.setAdapter(adapter);
try {
JSONArray users = response.getJSONArray("user");
for (int x = 0; x <= users.length()-1; x++) {
JSONObject user = users.getJSONObject(x);
PSP psp = new PSP(imageUri+user.getString("image")+".png",user.getString("username"),"0");
adapter.add(psp);
}
} catch (JSONException e) {
e.printStackTrace();
}
PSP.java
public class PSP
{
private String picture;
private String name;
private String price;
public String getPicture() {
return picture;
}
public PSP(String picture, String name, String price){
this.setPicture(picture);
this.setName(name);
this.setPrice(price);
}
public void setPicture(String picture) {
this.picture = picture;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
row_layout.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="80dp"
android:background="#000000">
<ImageView
android:id="#+id/pictures"
android:layout_width="100dp"
android:layout_height="75dp"
android:layout_alignParentLeft="true"
/>
<TextView
android:id="#+id/picturename"
android:layout_width="115dp"
android:layout_height="75dp"
android:layout_toRightOf="#+id/pictures"
android:text="Kim Domingo"
android:gravity="center"
android:textColor="#FFFFFF"
/>
<Button
android:id="#+id/btnplus"
android:layout_width="50dp"
android:layout_height="50dp"
android:gravity="center"
android:text="+"
android:textSize="50px"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/picturename"
android:layout_toEndOf="#+id/picturename"
/>
<EditText
android:id="#+id/price"
android:layout_width="50dp"
android:layout_height="50dp"
android:focusable="false"
android:textColor="#FFFFFF"
android:inputType="number"
android:gravity="center"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/btnplus"
android:layout_toEndOf="#+id/btnplus" />
<Button
android:id="#+id/btnminus"
android:layout_width="50dp"
android:layout_height="50dp"
android:gravity="center"
android:text="-"
android:textSize="50px"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/price"
android:layout_toEndOf="#+id/price" />
<View
android:layout_width="match_parent"
android:layout_height="2dp"
android:background="#FFFFFF"
android:layout_below="#+id/pictures"
android:id="#+id/editText"></View>
I created same before like this
You can use the HashMap map = new HashMap<>(); for what item user click. I assume that you use two button click are available in adapter class if not then add it.
Step 1 First Declare the HashMap map = new HashMap<>(); in adapter.
Step 2 Then put value in HashMap map.put("key","value"); This code put in both plus and minus button click event.
Step 3 Call ShowHashMapValue(); method below to the map.put("key","value"); for see the HashMap values check logcat for that.
Compare this adapter code for understand easily if any problem just comment below.
ListAdapter.java
public class ListAdapter extends BaseAdapter {
public ArrayList<Integer> quantity = new ArrayList<Integer>();
public ArrayList<Integer> price = new ArrayList<Integer>();
private String[] listViewItems, prices, static_price;
TypedArray images;
View row = null;
static String get_price, get_quntity;
int g_quntity, g_price, g_minus;
private Context context;
CustomButtonListener customButtonListener;
static HashMap<String, String> map = new HashMap<>();
public ListAdapter(Context context, String[] listViewItems, TypedArray images, String[] prices) {
this.context = context;
this.listViewItems = listViewItems;
this.images = images;
this.prices = prices;
for (int i = 0; i < listViewItems.length; i++) {
quantity.add(0);
}
}
public void setCustomButtonListener(CustomButtonListener customButtonListner) {
this.customButtonListener = customButtonListner;
}
#Override
public int getCount() {
return listViewItems.length;
}
#Override
public String getItem(int position) {
return listViewItems[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ListViewHolder listViewHolder;
if (convertView == null) {
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.activity_custom_listview, parent, false);
listViewHolder = new ListViewHolder();
listViewHolder.tvProductName = (TextView) row.findViewById(R.id.tvProductName);
listViewHolder.ivProduct = (ImageView) row.findViewById(R.id.ivproduct);
listViewHolder.tvPrices = (TextView) row.findViewById(R.id.tvProductPrice);
listViewHolder.btnPlus = (ImageButton) row.findViewById(R.id.ib_addnew);
listViewHolder.edTextQuantity = (EditText) row.findViewById(R.id.editTextQuantity);
listViewHolder.btnMinus = (ImageButton) row.findViewById(R.id.ib_remove);
static_price = context.getResources().getStringArray(R.array.Price);
row.setTag(listViewHolder);
} else {
row = convertView;
listViewHolder = (ListViewHolder) convertView.getTag();
}
listViewHolder.ivProduct.setImageResource(images.getResourceId(position, -1));
listViewHolder.edTextQuantity.setText(quantity.get(position) + "");
listViewHolder.tvProductName.setText(listViewItems[position]);
listViewHolder.tvPrices.setText(prices[position]);
listViewHolder.btnPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (customButtonListener != null) {
customButtonListener.onButtonClickListener(position, listViewHolder.edTextQuantity, 1);
quantity.set(position, quantity.get(position) + 1);
//price.set(position, price.get(position) + 1);
row.getTag(position);
get_price = listViewHolder.tvPrices.getText().toString();
g_price = Integer.valueOf(static_price[position]);
get_quntity = listViewHolder.edTextQuantity.getText().toString();
g_quntity = Integer.valueOf(get_quntity);
map.put("" + listViewHolder.tvProductName.getText().toString(), " " + listViewHolder.edTextQuantity.getText().toString());
// Log.d("A ", "" + a);
// Toast.makeText(context, "A" + a, Toast.LENGTH_LONG).show();
// Log.d("Position ", "" + position);
// System.out.println(+position + " Values " + map.values());
listViewHolder.tvPrices.getTag();
listViewHolder.tvPrices.setText("" + g_price * g_quntity);
ShowHashMapValue();
}
}
});
listViewHolder.btnMinus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (customButtonListener != null) {
customButtonListener.onButtonClickListener(position, listViewHolder.edTextQuantity, -1);
if (quantity.get(position) > 0)
quantity.set(position, quantity.get(position) - 1);
get_price = listViewHolder.tvPrices.getText().toString();
g_minus = Integer.valueOf(get_price);
g_price = Integer.valueOf(static_price[position]);
int minus = g_minus - g_price;
if (minus >= g_price) {
listViewHolder.tvPrices.setText("" + minus);
}
map.put("" + listViewHolder.tvProductName.getText().toString(), " " + listViewHolder.edTextQuantity.getText().toString());
ShowHashMapValue();
}
}
});
return row;
}
private void ShowHashMapValue() {
/**
* get the Set Of keys from HashMap
*/
Set setOfKeys = map.keySet();
/**
* get the Iterator instance from Set
*/
Iterator iterator = setOfKeys.iterator();
/**
* Loop the iterator until we reach the last element of the HashMap
*/
while (iterator.hasNext()) {
/**
* next() method returns the next key from Iterator instance.
* return type of next() method is Object so we need to do DownCasting to String
*/
String key = (String) iterator.next();
/**
* once we know the 'key', we can get the value from the HashMap
* by calling get() method
*/
String value = map.get(key);
System.out.println("Key: " + key + ", Value: " + value);
}
}
}
So so here is logic. You need to declare a boolean in PSP. by default set it to false.
Now when + button will be triggered you need to set that boolean check to true
then in your set price create this logic.
public String getPrice() {
if(check==true){
price++;
}
else{
price--;
}
return price;
}
If i correctly understand you then this surely will help you. Good Luck!

Can somebody help me solve the database?

Hello everybody i m building an android application which has timepicker. what i want is that i want to update the database when user clicks the save button twice. Please guide me how to do that. Now my application crashes because no updation of database takes place.
TimeTable.java
public class Monday extends FragmentActivity implements TimePickerFragment.TimePickerDialogListener {
EditText et1, et2, et3;
TextView tvm;
LinearLayout llm;
int fhour, fmin, thour, tmin, j;
private int cnt = 0;
View vi[] = new View[100];
TimeTableDbHelper db;
String txt,fmeridien,tmeridien,ftime,ttime;
private static final int START_TIME_PICKER_ID = 1;
private static final int END_TIME_PICKER_ID = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
setContentView(R.layout.activity_monday);
tvm = (TextView) findViewById(R.id.tvm);
llm = (LinearLayout) findViewById(R.id.llm);
db = new TimeTableDbHelper(this);
cnt = db.check("timetableM");
if (cnt > 0) {
int i;
for (i = 0; i < cnt; i++) {
LinearLayout mn = (LinearLayout) findViewById(R.id.llm);
View view = getLayoutInflater().inflate(R.layout.activity_timepicker, mn, false);
vi[i] = view;
mn.addView(view);
et1 = (EditText) vi[i].findViewById(R.id.txtTime);
et1.setText(db.rd1(i,1));
//Log.i("Monday", "Database read" + db.read(2) + db.read(3));
et2 = (EditText) vi[i].findViewById(R.id.txtTime2);
et2.setText(db.rd1(i,2));
//Log.i("Monday", "Database read" + db.read(4) + db.read(5));
et3 = (EditText) vi[i].findViewById(R.id.txtSet);
et3.setText(db.rd1(i,3));
}
j = i;
} else {
j = 0;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_monday, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
return super.onOptionsItemSelected(item);
}
public void setTime(View v) {
LinearLayout main = (LinearLayout) findViewById(R.id.llm);
View view = getLayoutInflater().inflate(R.layout.activity_timepicker, main, false);
view.setTag(j);
main.addView(view);
vi[j] = view;
}
public void setTime2(View v) {
DialogFragment newFragment = TimePickerFragment.newInstance(START_TIME_PICKER_ID);
newFragment.show(getFragmentManager(), "timePicker");
}
public void setTime3(View v) {
DialogFragment newFragment = TimePickerFragment.newInstance(END_TIME_PICKER_ID);
newFragment.show(getFragmentManager(), "timePicker");
}
#Override
public void onTimeSet(int id, TimePicker view, int hourOfDay, int minute) {
Log.i("TimePicker", "Time picker set from id " + id + "!");
if (id == START_TIME_PICKER_ID) {
et1 = (EditText) vi[j].findViewById(R.id.txtTime);
fmin = minute;
if(hourOfDay <= 12) {
fhour = hourOfDay;
fmeridien = "AM";
} else {
fhour = hourOfDay-12;
fmeridien = "PM";
}
ftime =fhour + ":" + fmin + fmeridien;
et1.setText(ftime);
} else {
et2 = (EditText) vi[j].findViewById(R.id.txtTime2);
tmin = minute;
if(hourOfDay < 12) {
thour = hourOfDay;
tmeridien = "AM";
} else {
thour = hourOfDay-12;
tmeridien = "PM";
}
ttime = thour + ":" + tmin +tmeridien;
et2.setText(ttime);
}
}
public void Save(View v)
{
int position = (int) v.getTag();
if(position<j);
else {
et3 = (EditText) vi[j].findViewById(R.id.txtSet);
txt = et3.getText().toString();
Log.i("Position", "Value is " + position);
db.write1(j, ftime, ttime, txt);
Toast.makeText(this, "Successfully saved", Toast.LENGTH_LONG).show();
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar c = Calendar.getInstance();
c.setFirstDayOfWeek(Calendar.MONDAY);
int day = c.get(Calendar.DAY_OF_WEEK);
int value;
if(fmeridien=="AM") value=0;
else value=1;
c.set(Calendar.DAY_OF_WEEK,day);
c.set(Calendar.AM_PM, value);
c.set(Calendar.HOUR, fhour);
c.set(Calendar.MINUTE, fmin);
c.set(Calendar.SECOND,0);
Intent i = new Intent("com.example.annu.sheduler.DisplayNotification");
//---assign an ID of 1---
i.putExtra("NotifID", j);
i.putExtra("text",txt);
PendingIntent displayIntent = PendingIntent.getActivity(
getBaseContext(), j, i, 0);
j++;
//---sets the alarm to trigger---
alarmManager.set(AlarmManager.RTC_WAKEUP,
c.getTimeInMillis(), displayIntent);}
}
}
activity_monday.xml
<LinearLayout android:id="#+id/llm"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.annu.sheduler.Monday"
android:background="#ffffa751"
android:label="Monday">
<TextView
android:id="#+id/tvm"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="setTime"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
android:text="Create a schedule"
android:textStyle="bold"
android:textSize="24sp"/>
</LinearLayout>
activity_timepicker.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="1">
<EditText
android:id="#+id/txtTime"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".30"
android:hint="From"
android:onClick="setTime2"/>
<EditText
android:id="#+id/txtTime2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".30"
android:hint="To"
android:onClick="setTime3"/>
<EditText
android:id="#+id/txtSet"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".40"
android:hint="Description!!!"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save"
android:onClick="Save"
android:minHeight="0dp"
android:minWidth="20dp"/>
</LinearLayout>
TimeTableDbHelper.java
public class TimeTableDbHelper extends SQLiteOpenHelper {
public static final String TABLE_NAMEM = "timetableM";
public static final String COLUMN_NO1 = "c_no1";
public static final String COLUMN_FROM_TIME1 = "FTIME1";
public static final String COLUMN_TO_TIME1 = "TTIME1";
public static final String COLUMN_DESC1 = "Description1";
private static final int DATABASE_VERSION = 1;
static final String DATABASE_NAME = "TimeTable.db";
public TimeTableDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
final String SQL_CREATE_TIME_TABLE1 = "CREATE TABLE " + TABLE_NAMEM + " (" +
COLUMN_NO1 + " INTEGER PRIMARY KEY, " +
COLUMN_FROM_TIME1 + " STRING NOT NULL," +
COLUMN_TO_TIME1 + " STRING NOT NULL," +
COLUMN_DESC1 + " TEXT NOT NULL" +
" );";
sqLiteDatabase.execSQL(SQL_CREATE_TIME_TABLE1);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_NAMEM);
onCreate(sqLiteDatabase);
}
public void write1(int column_no, String ftime, String ttime, String desc) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_NO1, column_no);
values.put(COLUMN_FROM_TIME1, ftime);
values.put(COLUMN_TO_TIME1, ttime);
values.put(COLUMN_DESC1, desc);
Boolean res = CheckIsDataAlreadyInDBorNot(TABLE_NAMEM, COLUMN_NO1, column_no);
if (res == false) db.insert(TABLE_NAMEM, null, values);
else db.update(TABLE_NAMEM, values, null, null);
db.close();
}
public int check(String tname) {
SQLiteDatabase db = this.getWritableDatabase();
String count = "SELECT count(*) FROM " + tname;
Cursor mcursor = db.rawQuery(count, null);
mcursor.moveToFirst();
int icount = mcursor.getInt(0);
return icount;
}
public String rd1(int c_no, int col) {
String selectQuery = "SELECT * FROM " + TABLE_NAMEM + " WHERE " + COLUMN_NO1 + " = " + c_no;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
String data = "";
if (cursor.moveToFirst()) {
// get the data into array,or class variable
do {
data = cursor.getString(col);
//Log.i("TimeTableDbHelper", "Value read " + cursor.getString(6));
} while (cursor.moveToNext());
}
db.close();
return data;
}
public boolean CheckIsDataAlreadyInDBorNot(String TableName,
String dbfield, int fieldValue) {
SQLiteDatabase db = this.getReadableDatabase();
String Query = "Select * from " + TableName + " where " + dbfield + " = " + fieldValue;
Cursor cursor = db.rawQuery(Query, null);
if (cursor.getCount() <= 0) {
cursor.close();
return false;
}
cursor.close();
return true;
}
}
As stated here
https://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#update(java.lang.String,%20android.content.ContentValues,%20java.lang.String,%20java.lang.String[]):
Returns:
the number of rows affected
So you can do just:
if (db.update(TABLE_NAMEM, values, null, null) == 0)
db.insert(TABLE_NAMEM, null, values);
db.close();

Universal image loader imageview doesn't update itself with spinner

I'm using UIL to load thrumbs in a listview.
here is the imageview and the spinner in the cell layout :
<ImageView
android:id="#+id/imgAlbum"
android:layout_width="48dip"
android:layout_height="48dip"
android:layout_gravity="center|left"
android:scaleType="centerCrop"
android:visibility="gone" />
<ProgressBar
android:id="#+id/loading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:visibility="gone" />
The list :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/background"
android:orientation="vertical" >
<ListView
android:id="#+id/list_restaurant"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="4dp" >
</ListView>
</LinearLayout>
I config the loader like that :
public void setImageLoader(ImageLoader imageLoader, Context context) {
File cacheDir = StorageUtils.getCacheDirectory(context);
ImageLoaderConfiguration _config;
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD_MR1) {
_config = new ImageLoaderConfiguration.Builder(context).memoryCacheExtraOptions(0, 0).discCacheExtraOptions(480, 800, CompressFormat.JPEG, 75).taskExecutor(null)
.taskExecutorForCachedImages(null).threadPoolSize(3) // default
.threadPriority(Thread.NORM_PRIORITY - 1) // default
.tasksProcessingOrder(QueueProcessingType.FIFO) // default
.denyCacheImageMultipleSizesInMemory().memoryCache(new UsingFreqLimitedMemoryCache(2 * 1024 * 1024)) // default
.memoryCacheSize(2 * 1024 * 1024).discCache(new UnlimitedDiscCache(cacheDir)) // default
.discCacheSize(50 * 1024 * 1024).discCacheFileCount(100).discCacheFileNameGenerator(new HashCodeFileNameGenerator()) // default
.imageDownloader(new BaseImageDownloader(context)) // default
.defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default
.enableLogging().build();
}
else {
_config = new ImageLoaderConfiguration.Builder(context).memoryCacheExtraOptions(0, 0)
// default/screendimensions
.discCacheExtraOptions(480, 800, CompressFormat.JPEG, 75).taskExecutor(AsyncTask.THREAD_POOL_EXECUTOR).taskExecutorForCachedImages(AsyncTask.THREAD_POOL_EXECUTOR)
.threadPoolSize(3) // default
.threadPriority(Thread.NORM_PRIORITY - 1) // default
.tasksProcessingOrder(QueueProcessingType.FIFO) // default
.denyCacheImageMultipleSizesInMemory().memoryCache(new UsingFreqLimitedMemoryCache(2 * 1024 * 1024)) // default
.memoryCacheSize(2 * 1024 * 1024).discCache(new UnlimitedDiscCache(cacheDir)) // default
.discCacheSize(50 * 1024 * 1024).discCacheFileCount(100).discCacheFileNameGenerator(new HashCodeFileNameGenerator()) // default
.imageDownloader(new BaseImageDownloader(context)) // default
.defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default
.enableLogging().build();
}
if (!imageLoader.isInited()) {
imageLoader.init(_config);
}
}
And in the baseadapter i use it like that :
private ImageLoader _imageLoader;
private DisplayImageOptions _options;
in the constructor
this._imageLoader = ImageLoader.getInstance();
this._options = new DisplayImageOptions.Builder().showImageForEmptyUri(R.drawable.error).showImageOnFail(R.drawable.error).cacheInMemory().cacheOnDisc().bitmapConfig(Bitmap.Config.RGB_565)
.build();
Utils utils = new Utils();
utils.setImageLoader(_imageLoader, _activity);
In the GetView() :
final ProgressBar spinner = (ProgressBar) convertView.findViewById(R.id.loading);
_imageLoader.displayImage(etablissement.getImgThumb(), cellHolder.imageIcon, _options, new SimpleImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
view.setVisibility(View.GONE);
spinner.setVisibility(View.VISIBLE);
spinner.invalidate();
view.invalidate();
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
String message = null;
switch (failReason.getType()) {
case IO_ERROR:
message = "Input/Output error";
break;
case DECODING_ERROR:
message = "Image can't be decoded";
break;
case NETWORK_DENIED:
message = "Downloads are denied";
break;
case OUT_OF_MEMORY:
message = "Out Of Memory error";
break;
case UNKNOWN:
message = "Unknown error";
break;
}
view.setVisibility(View.VISIBLE);
spinner.setVisibility(View.GONE);spinner.invalidate();
view.invalidate();
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
view.setVisibility(View.VISIBLE);
spinner.setVisibility(View.GONE);
spinner.invalidate();
view.invalidate();
}
});
Everything works fine BUT the spinner stay instead of the imageview until you scroll the list the redraw the cells.. The imageview should refresh itself when the image is downloaded/got from cache or invalidate()
Here the list loading stay like that : http://imagik.fr/view-rl/45673
Here when i scroll down the imageview refresh : http://imagik.fr/view-rl/45674
Here when i re-scoll up the imageview refresh : http://imagik.fr/view-rl/45675
Any idea ??
EDIT:
The full adapter code (with the UIL part inside) :
public class AdapterDirectories extends BaseAdapter {
/**
* PRIVATE ATTRIBUTES
*/
// LOG
private static final String TAG = AdapterDirectories.class.getSimpleName();
// IHM
private static LayoutInflater _inflater = null;
private Activity _activity;
// DATA
private DataManager _dataManager;
private ImageLoader _imageLoader;
private DisplayImageOptions _options;
private int _section;
private float _latitude;
private float _longitude;
private List<Contact> _listContacts = new ArrayList<Contact>();
private List<Favoris> _listFavoris = new ArrayList<Favoris>();
public AdapterDirectories(Activity activity, boolean favoris, float latitude, float longitude, int section) {
this._activity = activity;
this._latitude = latitude;
this._longitude = longitude;
this._section = section;
//
ContactRepository contactRep = null;
//
if (favoris == false) {
_listContacts = EtablissementApplication._dataManager.get_listOfContacts(_section, _activity);
}
else {
// FAVORITE
this._listFavoris = EtablissementApplication._dataManager.get_listOfFavoris();
// DATA
contactRep = new ContactRepository(_activity);
contactRep.Open();
for (Favoris unFavoris : _listFavoris) {
_listContacts.add(contactRep.GetById(unFavoris.getIdentifiantContact()));
}
contactRep.Close();
}
_inflater = (LayoutInflater) _activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this._imageLoader = ImageLoader.getInstance();
this._options = new DisplayImageOptions.Builder().showImageForEmptyUri(R.drawable.error).showImageOnFail(R.drawable.error).cacheInMemory().cacheOnDisc()
.displayer(new RoundedBitmapDisplayer(Utils.IMAGE_BORDER_RADIUS)).bitmapConfig(Bitmap.Config.RGB_565).build();
Utils utils = new Utils();
utils.setImageLoader(_imageLoader, _activity);
}
#Override
public int getCount() {
return _listContacts.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
CellHolder cellHolder = null;
Contact _contact = _listContacts.get(position);
Etablissement etablissement = new Etablissement();
//
// GET
if (convertView == null) {
view = _inflater.inflate(R.layout.directory_list_item, null);
cellHolder = new CellHolder();
cellHolder.textTitle = (TextView) view.findViewById(R.id.annuaire_titre_etablissement);
cellHolder.textCategory = (TextView) view.findViewById(R.id.annuaire_categorie_etablissement);
cellHolder.textDistance = (TextView) view.findViewById(R.id.annuaire_distance_etablissement);
cellHolder.imageIcon = (ImageView) view.findViewById(R.id.img_icon);
cellHolder.textPromo = (TextView) view.findViewById(R.id.promo);
cellHolder.textTarif = (TextView) view.findViewById(R.id.annuaire_tarif_etablissement);
view.setTag(cellHolder);
}
else {
cellHolder = (CellHolder) convertView.getTag();
}
//
// SET
cellHolder.textTitle.setText(_contact.getName().toUpperCase());
try {
//
EtablissementRepository etablissementRep = new EtablissementRepository(_activity);
etablissementRep.Open();
int idEta = etablissementRep.GetByIdContact(_contact.getIdentifiant());
etablissement = etablissementRep.GetById(idEta);
etablissementRep.Close();
// CATEGORIES
if (_section == 0) {
if (etablissement.getSection() != null && !etablissement.getSection().getLibelle().equals("")) {
cellHolder.textCategory.setText(etablissement.getSection().getLibelle());
}
else {
cellHolder.textCategory.setVisibility(View.GONE);
}
}
else {
String categories = "";
for (Categorie cat : etablissement.getCategories()) {
categories = categories + cat.getLibelle() + "|";
}
if (!categories.equals("")) {
cellHolder.textCategory.setText(categories);
}
else {
cellHolder.textCategory.setText(_activity.getString(R.string.txt_no_categories));
}
}
//
// TARIF
String trancheTarif = "";
if (etablissement.getTarif() != null) {
trancheTarif = etablissement.getTarif().getMinPrice() + "\u20ac à " + etablissement.getTarif().getMaxPrice() + "\u20ac";
}
if (!trancheTarif.equals("") && etablissement.getTarif().getMinPrice() > 0 && etablissement.getTarif().getMaxPrice() > 0) {
cellHolder.textTarif.setText(trancheTarif);
}
else {
cellHolder.textTarif.setText("- \u20ac à - \u20ac");
}
// PROMO
boolean etatPromotion = false;
for (Promotion promo : etablissement.getPromotions()) {
if (promo.isPromoOnGoing()) {
etatPromotion = true;
}
}
if (!etatPromotion) { // PROMO OFF
cellHolder.textPromo.setVisibility(View.VISIBLE);
}
else { // PROMO ON
cellHolder.textPromo.setVisibility(View.VISIBLE);
}
// LOGO
final ProgressBar spinner = (ProgressBar) convertView.findViewById(R.id.loading);
_imageLoader.displayImage(etablissement.getImgThumb(), cellHolder.imageIcon, _options, new SimpleImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
String message = null;
switch (failReason.getType()) {
case IO_ERROR:
message = "Input/Output error";
break;
case DECODING_ERROR:
message = "Image can't be decoded";
break;
case NETWORK_DENIED:
message = "Downloads are denied";
break;
case OUT_OF_MEMORY:
message = "Out Of Memory error";
break;
case UNKNOWN:
message = "Unknown error";
break;
}
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
}
});
}
catch (Exception e) {
}
// DISTANCE
int distanceFormatee = 0;
if (_latitude == 0 || _longitude == 0) {
cellHolder.textDistance.setText("");
}
else {
int distance = (int) distanceBetween(_latitude, _longitude, _contact.getLatitude(), _contact.getLongitude());
distanceFormatee = distance / 1000;
if (distance < 1000) {
cellHolder.textDistance.setText("< 1 km");
}
else {
cellHolder.textDistance.setText(distanceFormatee + " km");
}
}
//
// SAVE DISTANCE
EtablissementApplication._dataManager.get_listOfContacts(_section, _activity).get(position).setDistance(distanceFormatee);
//
// DATA SAVE
List<Integer> _mapData = new ArrayList<Integer>();
_mapData.add(_contact.getIdentifiant());
_mapData.add(etablissement.getIdentifiant());
DataManager._contactForEtaHashMap.put(_contact.getName(), etablissement);
DataManager._mapContact.put(position, _mapData);
return view;
}
public class CellHolder {
public TextView textTitle;
public TextView textAdress;
public TextView textCategory;
public TextView textTarif;
public TextView textPromo;
public ImageView imageIcon;
public TextView textDistance;
}
public void clearData() {
_listContacts.clear();
_listFavoris.clear();
}
private double distanceBetween(float lat_a, float lng_a, float lat_b, float lng_b) {
float pk = (float) (180 / 3.14169);
float a1 = lat_a / pk;
float a2 = lng_a / pk;
float b1 = lat_b / pk;
float b2 = lng_b / pk;
float t1 = FloatMath.cos(a1) * FloatMath.cos(a2) * FloatMath.cos(b1) * FloatMath.cos(b2);
float t2 = FloatMath.cos(a1) * FloatMath.sin(a2) * FloatMath.cos(b1) * FloatMath.sin(b2);
float t3 = FloatMath.sin(a1) * FloatMath.sin(b1);
double tt = Math.acos(t1 + t2 + t3);
return 6366000 * tt;
}
}
You can achieve expected behaviour by this:
Your list item layout:
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ProgressBar
android:id="#+id/loading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" />
<ImageView
android:id="#+id/imgAlbum"
android:layout_width="48dip"
android:layout_height="48dip"
android:layout_gravity="center|left"
android:scaleType="centerCrop" />
</RelativeLayout
If you have ProgressBar and ImageView in this order, then ImageView will overlay the ProgressBar, when Image Loader set image into it so ProgressBar will not be visible anymore.
Then in your getView() method just simply load image with standard way. You dont have to bother with hiding/showing ProgressBar
You will have to put a function to refresh the 'source' that is providing the image resource to the spinner manually once the download is complete i.e i suppose when an onPost is complete in your async task if at all u are using one. This way the source providing the resource to the spinner will be updated all the time.
try this code and use Asynk task will help u:
http://thinkandroid.wordpress.com/2012/06/13/lazy-loading-images-from-urls-to-listviews/

Categories