I have problem with removing items from ArrayList. I tried it maybe 100 times but I can't fix it. Saving to list isn't problem but it's very hard to remove for me.
When I remove SharedPrefs key (position) It's good first time but if I first time remove first position it's deleted from list but its still in preferences so when I try to remove first position second time I cant remove it because there is still saved preference with value "" but I need to remove this preference totally that first position have to contain preferences with value on second position not "".
I tried to make some images for better understanding.
Thats before remove 1st position:
And this is after remove 1st position
There is my CustomListAdapter class
public class CustomListAdapterInterests extends ArrayAdapter < String > {
private final Activity context;
private final ArrayList < String > mItemInterest;
public CustomListAdapterInterests(Activity context, ArrayList < String > itemInterest) {
super(context, R.layout.list_item_interests, itemInterest);
this.context = context;
this.mItemInterest = itemInterest;
}
#Override
public int getCount() {
return mItemInterest.size();
}
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.list_item_interests, null, true);
TextView itemInterestTV = (TextView) rowView.findViewById(R.id.textInterest);
itemInterestTV.setText(mItemInterest.get(position));
return rowView;
}
}
And here is my fragment
public class InterestsFragment extends BaseFragment {
private ArrayList < String > mInterestList;
private static final int MAX_STORED_LINES_INTERESTS = 50;
private FloatingActionButton plusInterestsBTN;
private CustomListAdapterInterests adapterInterests;
private ListView listInterests;
private EditText interestET;
private Button confirmInterestBTN;
public SharedPreferences sharedPreferences;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_interests, container, false);
plusInterestsBTN = (FloatingActionButton) v.findViewById(R.id.plusInterests);
sharedPreferences = getActivity().getSharedPreferences(Constants.PREFERENCES_INTERESTS, Context.MODE_PRIVATE);
mInterestList = new ArrayList < String > ();
loadInterestFromPreferences(mInterestList);
adapterInterests = new CustomListAdapterInterests(getActivity(), mInterestList);
listInterests = (ListView) v.findViewById(R.id.listViewInterests);
listInterests.setAdapter(adapterInterests);
listInterests.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView <? > arg0, View v, int position, long arg3) {
if (sharedPreferences.contains(Constants.INTEREST + position)) {
SharedPreferences.Editor editor = sharedPreferences.edit();
mInterestList.remove(position);
adapterInterests.notifyDataSetChanged();
editor.remove(Constants.INTEREST + position);
editor.commit();
}
}
});
listInterests.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {#Override
public boolean onItemLongClick(AdapterView <? > arg0, View arg1,
final int position, long id) {
onShowDialogSetItem(position);
return true;
}
});
plusInterestsBTN.setOnClickListener(new View.OnClickListener() {#Override
public void onClick(View v) {
onShowDialogAddItem();
}
});
listInterests.setOnScrollListener(new AbsListView.OnScrollListener() {#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
int btn_initPosY = plusInterestsBTN.getScrollY();
if (scrollState == SCROLL_STATE_TOUCH_SCROLL) {
plusInterestsBTN.animate().cancel();
plusInterestsBTN.animate().translationXBy(350);
} else {
plusInterestsBTN.animate().cancel();
plusInterestsBTN.animate().translationX(btn_initPosY);
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
}
});
return v;
}
private void loadInterestFromPreferences(ArrayList < String > mInterestList) {
for (int x = 0; x < 5; x++) {
String interests = sharedPreferences.getString(Constants.INTEREST + x, Constants.DEFAULT);
Toast.makeText(getActivity(), interests, Toast.LENGTH_SHORT).show();
if (interests != "") {
mInterestList.add(interests);
}
}
}
private void onShowDialogSetItem(final int position) {
final Dialog dialogInterest = new Dialog(getActivity());
dialogInterest.getWindow().getAttributes().windowAnimations = R.anim.abc_slide_in_top;
dialogInterest.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialogInterest.getWindow().getAttributes().windowAnimations = R.style.animationName;
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.fragment_interests_add_event, null, false);
dialogInterest.setCanceledOnTouchOutside(true);
dialogInterest.setContentView(view);
final EditText interestET = (EditText) dialogInterest.findViewById(R.id.editTextInterest);
Button confirmInterestBTN = (Button) dialogInterest.findViewById(R.id.confirmInterest);
TextView title = (TextView) dialogInterest.findViewById(R.id.textView2);
title.setText("Edit Interest");
interestET.setText(mInterestList.get(position));
confirmInterestBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("2", "" + position);
String interest = sharedPreferences.getString(Constants.INTEREST + position, Constants.DEFAULT);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(Constants.INTEREST + position, interestET.getText().toString());
editor.commit();
String interests = sharedPreferences.getString(Constants.INTEREST + position, Constants.DEFAULT);
mInterestList.set(position, interestET.getText().toString());
Toast.makeText(getActivity(), "Upravené: " + interests, Toast.LENGTH_SHORT).show();
adapterInterests.notifyDataSetChanged();
dialogInterest.dismiss();
}
});
dialogInterest.show();
}
private void onShowDialogAddItem() {
if (mInterestList.size() >= MAX_STORED_LINES_INTERESTS) {
return;
}
final Dialog dialogInterest = new Dialog(getActivity());
dialogInterest.getWindow().getAttributes().windowAnimations = R.anim.abc_slide_in_top;
dialogInterest.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialogInterest.getWindow().getAttributes().windowAnimations = R.style.animationName;
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.fragment_interests_add_event, null, false);
dialogInterest.setCanceledOnTouchOutside(true);
dialogInterest.setContentView(view);
interestET = (EditText) dialogInterest.findViewById(R.id.editTextInterest);
confirmInterestBTN = (Button) dialogInterest.findViewById(R.id.confirmInterest);
confirmInterestBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = listInterests.getAdapter().getCount();
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(Constants.INTEREST + position, interestET.getText().toString());
editor.commit();
String interests = sharedPreferences.getString(Constants.INTEREST + position, Constants.DEFAULT);
Toast.makeText(getActivity(), "Přidané: " + interests, Toast.LENGTH_SHORT).show();
mInterestList.add(interestET.getText().toString());
//adapterInterests.notifyDataSetChanged();
dialogInterest.dismiss();
}
});
dialogInterest.show();
adapterInterests.notifyDataSetChanged();
}
}
Thank you for help. Sorry for my English. If do you will help me I can do any material design app icon for you or google play designs. Thank you. If there is few informations please say me.
I think if you save all of your string list to single property of preferences will make it easy to manage.
see this sample:
//for save
StringBuilder sb = new StringBuilder();
for (String interest : mInterestList) {
sb.append(interest).append(",");
}
prefsEditor.putString("MyInterests", sb.toString());
prefsEditor.commit();
//for read
String [] interests= sharedPreferences.getString("MyInterests");
mInterestList = new ArrayList<String>(Arrays.asList(interests));
in every change to your mInterestList just save it again. no need to remove and adding. change your mInterestList and save again in shared preferences.
Looks to me like your adapter runs off of mInterestList .
I don't see you removing the data item from mInterestsList when your remove the Preference?
Rather than checking whether shared preferences contains, see if it is set to null instead or not, that is do,
if (sharedPreferences.getString(Constants.INTEREST + position)!=null) {
SharedPreferences.Editor editor = sharedPreferences.edit();
mInterestList.remove(position);
adapterInterests.notifyDataSetChanged();
editor.remove(Constants.INTEREST + position);
editor.commit();
}
Related
I face a problem in list view. In my list view have edit text and text view. When i scroll the list my data that is entered in text view has lost the value and show the default value. i have two button in list view i increase the quantity and scroll the list for next product when i come back text view lost the value and show default value 1 . And when i open keyboard for enter data then same issue . please help me.
And its my code
Custom Adapter
private List<ShowProducts> listShowProducts;
private Context context;
private int resource;
private String condition;
String uri;
private static final String TAG = "CustomAdapter";
int i = 0;
float total;
ListView listView;
TextView tvTotal;
float sum = 0;
public CustomAdapter(#NonNull Context context, #LayoutRes int resource, List<ShowProducts> objects) {
super(context, resource, objects);
this.context = context;
this.resource = resource;
this.listShowProducts = objects;
}
#Override
public int getCount() {
return super.getCount();
}
#Nullable
#Override
public Object getItem(int position) {
return super.getItem(position);
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View view = LayoutInflater.from(context).inflate(resource, parent, false);
{
final ShowProducts showProducts = listShowProducts.get(position);
ImageView imageView = (ImageView) view.findViewById(R.id.imageViewOfSelecteditem);
ImageView plus = (ImageView) view.findViewById(R.id.imageviewPlus);
ImageView minus = (ImageView) view.findViewById(R.id.imageviewminus);
TextView tvSetNameOfSeletedItem = (TextView) view.findViewById(R.id.tvSetNameOfSeletedItem);
TextView tvSetSizeOfSeletedItem = (TextView) view.findViewById(R.id.tvSetSizeOfSeletedItem);
TextView tvSetPriceOfSeletedItem = (TextView) view.findViewById(R.id.tvSetPriceOfSeletedItem);
final TextView tvQunatitySetOfSelectedItem = (TextView) view.findViewById(R.id.tvQunatitySetOfSelectedItem);
for (int a = 0; a < 10; a++) {
Log.d(TAG, "onnnnView: ");
}
Log.d(TAG, "getView: +++++");
tvSetNameOfSeletedItem.setText(showProducts.getProduct_name().toString());
tvSetSizeOfSeletedItem.setText(showProducts.getSize_name());
tvSetPriceOfSeletedItem.setText(String.valueOf(showProducts.getSize_price()).toString());
uri = showProducts.getProduct_photo().toString();
Picasso.with(context).load(uri).into(imageView);
plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int a = Integer.parseInt(tvQunatitySetOfSelectedItem.getText().toString());
a++;
Log.d(TAG, "getView: ");
if (a <= showProducts.getSize_quantity()) {
tvQunatitySetOfSelectedItem.setText(String.valueOf(a).toString());
tvTotal = (TextView) ((Activity) context).findViewById(R.id.tvTotalShow);
float price = Float.parseFloat(tvTotal.getText().toString());
sum = price + showProducts.getSize_price();
tvTotal.setText(String.valueOf(sum));
}
}
});
minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int a = Integer.parseInt(tvQunatitySetOfSelectedItem.getText().toString());
a--;
if (a > 0)
{
tvQunatitySetOfSelectedItem.setText(String.valueOf(a).toString());
tvTotal = (TextView) ((Activity) context).findViewById(R.id.tvTotalShow);
float price = Float.parseFloat(tvTotal.getText().toString());
sum = price - showProducts.getSize_price();
tvTotal.setText(String.valueOf(sum));
}
}
});
}
return view;
}
And activity code
public class SelectedProductFromShopingCartShow extends AppCompatActivity {
ArrayList<ShowProducts> arrayList = new ArrayList<>();
String condition = "SelectedItemsFromShoppingCart";
CustomAdapter customAdapter;
ListView listView;
TextView tvTotal;
EditText etDiscount;
int total;
float sum = 0;
Button discount;
private static final String TAG = "SelectedProductFromShop";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_selected_product_from_shoping_cart_show);
listView = (ListView) findViewById(R.id.listViewSelectedItemsOfShopingCart);
tvTotal = (TextView) findViewById(R.id.tvTotalShow);
etDiscount = (EditText) findViewById(R.id.etDiscount);
arrayList = (ArrayList<ShowProducts>) getIntent().getSerializableExtra("selectedList");
ShowProducts showProducts = arrayList.get(0);
Log.d(TAG, "onnnnCreate: " + showProducts.getProduct_name());
customAdapter = new CustomAdapter(SelectedProductFromShopingCartShow.this, R.layout.show_selected_item_of_shopingcart, condition, arrayList);
listView.setAdapter(customAdapter);
getTotalListView();
Log.d(TAG, "onnnnCreate: Before inner class");
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
AlertDialog.Builder builder = new AlertDialog.Builder(SelectedProductFromShopingCartShow.this);
builder.setTitle("Delete this product");
builder.setMessage("Are you sure you want to delete it?");
builder.setCancelable(true);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
arrayList.remove(position);
customAdapter.notifyDataSetChanged();
Toast.makeText(SelectedProductFromShopingCartShow.this, "item deleted", Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.setIcon(android.R.drawable.ic_dialog_alert);
builder.show();
return true;
}
});
}
public void getTotalListView() {
sum = 0;
for (int i = 0; i < arrayList.size(); i++) {
ShowProducts showProducts = arrayList.get(i);
sum = sum + showProducts.getSize_price();
tvTotal.setText(String.valueOf(sum));
}
}
And watch this video for understand problems
https://youtu.be/WAjtRkI5dl4
You need to follow viewholder pattern. It will resolve your issue. You can check it here https://developer.android.com/training/improving-layouts/smooth-scrolling.html
The only place you're keeping count is in the view. You should make your count a field in the list item ShowProducts and create a getter & setter. For example, in the plus onClickListener, instead of
int a = Integer.parseInt(tvQunatitySetOfSelectedItem.getText().toString());
a++;
You'll have
// for example, in the `plus` listener
int a = showProducts.getCount();
a++;
showProducts.setCount(a);
And don't forget
notifyDataSetChanged();
I need to put a strikethrough on the text after the item has been checked. I found solutions that use setPaintFlags(descriptionView.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);. I don't use a textview but instead use simple_list_item_multiple_choice for my listview so how do I solve this? Here is my entire code:
public class Surv_list extends Fragment {
final String[] OPSys = new String[]{"item1","item2","item3","item4"
};
ListView myList;
Button getChoice, clearAll;
SharedPreferences sharedpreferences;
public static final String MyPREFERENCES = "MyUserChoice" ;
ArrayList<String> selectedItems = new ArrayList<String>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.listlay, container, false);
myList = (ListView)rootView.findViewById(R.id.list);
ListView list = (ListView) rootView.findViewById(R.id.list);
clearAll = (Button)rootView.findViewById(R.id.clearall);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_multiple_choice, OPSys);
myList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
myList.setAdapter(adapter);
list.setAdapter(adapter);
sharedpreferences = getActivity().getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
if(sharedpreferences.contains(MyPREFERENCES)){
LoadSelections();
}
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
SaveSelections();
}
});
clearAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
ClearSelections();
}
});
return rootView;
}
private void SaveSelections() {
// save the selections in the shared preference in private mode for the user
SharedPreferences.Editor prefEditor = sharedpreferences.edit();
String savedItems = getSavedItems();
prefEditor.putString(MyPREFERENCES.toString(), savedItems);
prefEditor.commit();
}
private String getSavedItems() {
String savedItems = "";
int count = this.myList.getAdapter().getCount();
for (int i = 0; i < count; i++) {
if (this.myList.isItemChecked(i)) {
if (savedItems.length() > 0) {
savedItems += "," + this.myList.getItemAtPosition(i);
} else {
savedItems += this.myList.getItemAtPosition(i);
}
}
}
return savedItems;
}
private void LoadSelections() {
// if the selections were previously saved load them
if (sharedpreferences.contains(MyPREFERENCES.toString())) {
String savedItems = sharedpreferences.getString(MyPREFERENCES.toString(), "");
selectedItems.addAll(Arrays.asList(savedItems.split(",")));
int count = this.myList.getAdapter().getCount();
for (int i = 0; i < count; i++) {
String currentItem = (String) myList.getAdapter()
.getItem(i);
if (selectedItems.contains(currentItem)) {
myList.setItemChecked(i, true);
} else {
myList.setItemChecked(i, false);
}
}
}
}
private void ClearSelections() {
// user has clicked clear button so uncheck all the items
int count = this.myList.getAdapter().getCount();
for (int i = 0; i < count; i++) {
this.myList.setItemChecked(i, false);
}
// also clear the saved selections
SaveSelections();
}
}
any help would be very much appreciated.
You can create a custom adapter for your list view and in the getview method of the adpater take the handle of textview . Based on your condition you can combine the already available code to strikeout the text view.
for making your own view attributes in list view, you have to make a custom Adapter other than using default adapter. there is no way you can do this using default adapter. here you can learn how to make custom adapter. also I would suggest you to use RecyclerView instead of ListView
I have to set the Background color of the visitedItem(imageView of listView row).
It shows a list of item, if you visited (itemclick) on row its item backgroundColor must be changed. I use sharedPreferences for it. And also debug it(in debug it show false). But don't know why first item is set to green after first time itemClick on any listView row.
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View view = convertView;
if(view == null)
{
view = inflater.inflate(R.layout.item_ads, parent, false);
}
final HashMap<String, String> map = list.get(position);
ImageView imageAd = (ImageView)view.findViewById(R.id.ad_image);
if(sessionManager.ItemVisited(position))// && position!=0)// && !sessionManager.getFirstRun())
{
imageAd.setBackgroundColor(Color.GREEN);
}
}
SessionManager
public class SessionManager
{
public static ArrayList<Boolean> listBoolTrain = new ArrayList<Boolean>();
private int giftRemaining;
private SharedPreferences prefs;
// Editor for Shared preferences
Editor editor;
// Context
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Sharedpref file name
private static final String PREF_NAME = "AndroidHivePref";
public SessionManager(Context context)
{
this._context = context;
prefs = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = prefs.edit();
}
public void setNumberOfGits(int numberOfGifts)
{
editor.putInt("numberOfGifts", numberOfGifts);
editor.commit();
}
public int getNumberOfGits()
{
int nog = prefs.getInt("numberOfGifts", -5);
return nog;
}
public void initializerBooleans(int arraySiz)
{
int arraySize = prefs.getInt("arraySize", 10);
for(int x = 0 ; x < arraySize; x++)
{
editor.putBoolean("Bool"+x, false);
editor.commit();
}
}
public void setItemVisited(int x)
{
editor.putBoolean("Bool"+x, true);
editor.commit();
}
public boolean isItemVisited(int x)
{
return prefs.getBoolean("Bool"+x, false);
}
public int getUnVisitedItemCount()
{
int count = 0;
int arraySize = prefs.getInt("arraySize", 10);
for(int x = 0 ; x < arraySize ; x++)// listBoolTrain.size(); x++)
{
boolean bol= prefs.getBoolean("Bool"+x, false);
if(!bol)
{
count++;
}
}
return count;
}
public void remainingGift()
{
}
public void setFirstRun(boolean status)
{
editor.putBoolean("firstrun", status);
editor.commit();
}
public boolean getFirstRun()
{
return prefs.getBoolean("firstrun", true);
}
public void removeAllPreferences()
{
prefs.edit().clear().commit();
}
public void removeKey(String keyName)
{
prefs.edit().remove(keyName).commit();
}
public void showAll()
{
Map<String,?> keys = prefs.getAll();
for(Map.Entry<String,?> entry : keys.entrySet())
{
Log.d("map values",entry.getKey() + ": " + entry.getValue().toString());
}
}
public void setArraySize(int boolSize)
{
editor.putInt("arraySize", boolSize);
editor.commit();
initializerBooleans(boolSize);
}
public int getArraySize()
{
return prefs.getInt("arraySize", -1);
}
public boolean ItemVisited(int position)
{
return prefs.getBoolean("Bool"+position, false);
}
}
And listView itemClicked..
listView.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long arg3)
{
Log.e("TAG_ADS","Item Visited " + position);
sessionManager.setItemVisited(position);
view.findViewById(R.id.ad_image).setBackgroundColor(Color.BLUE);
final String appPackageName = arl.get(position).get("packageName"); //map.get("packageName"); // getPackageName() from Context or Activity object
Intent marketIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id="+ appPackageName));
startActivity(marketIntent);
}
});
I have to create session for visited links. In a listView i have urls, Once a url is visited,its backgroundColor must be replaced.I have tried multiple ways but nothing happens.
Once i clicked on any item, position 0 background color also changed as it is a visited link.
You set the backgroundcolor only to green. The next time getView is called, convertView will be some sort of copy so you don't have to inflate it and do some findViewById, but the background color is also already set to green.
If you add an else statement to set the color to white (for example), it will work.
if(sessionManager.ItemVisited(position))// && position!=0)// && !sessionManager.getFirstRun())
{
imageAd.setBackgroundColor(Color.GREEN);
} else {
imageAd.setBackgroundColor(Color.WHITE);
}
You have to do something like below:-
View rowView = convertView;
if (rowView == null)
{
LayoutInflater inflater = context.getLayoutInflater();
rowView = inflater.inflate(R.layout.partner_list_element, null);
// configure view holder
ViewHolder viewHolder = new ViewHolder();
viewHolder.price = (TextView) rowView.findViewById(R.id.price);
viewHolder.header = (TextView) rowView.findViewById(R.id.header);
viewHolder.location = (TextView) rowView.findViewById(R.id.location);
viewHolder.space = (TextView) rowView.findViewById(R.id.space);
viewHolder.main_image = (ImageView) rowView.findViewById(R.id.main_image);
viewHolder.logo_image = (ImageView) rowView.findViewById(R.id.logo_image);
rowView.setTag(viewHolder);
}
// fill data
ViewHolder holder = (ViewHolder) rowView.getTag();
make below class on adapter
class ViewHolder {
public TextView header,location,space,price;
public ImageView main_image,logo_image;
}
Listview recycle his element that's why you facing problem.
my app contains a list view which is being populated by a spinner value
this list contains toggle button in each row and for customization purpose i have used baseadapter in list view
i am changing image of toggle button on checked and unchecked
the functionality is going well on toggle button and listview but the problem occurrs when i closes the app and then again opens it it gets refreshed and the toggle state become unchecked and the unchecked image is shown every where
so to solve this i have saved the value of toggle button in shared preferences but now i dont know where to check this in base adapter class plz help me
the necessary code for this
public class DDListAdapter extends BaseAdapter {
ArrayList<DataModelDD> listArray;
int curIndex=1000, pIndex;
public DDListAdapter(String[] str, String[] str1) {
listArray = new ArrayList<DataModelDD>();
for (int i=0; i < str.length; i++) {
listArray.add(new DataModelDD(str[i],str1[i], " Day Alert on " + str[i],false));
}
}
public void DDListUpdate(String[] str, String[] str1){
listArray = new ArrayList<DataModelDD>();
for (int i=0; i < str.length; i++) {
listArray.add(new DataModelDD(str[i],str1[i], " Day Alert on " + str[i],false));
}
this.notifyDataSetChanged();
}
#Override
public int getCount() {
return listArray.size(); // total number of elements in the list
}
#Override
public Object getItem(int i) {
return listArray.get(i); // single item in the list
}
#Override
public long getItemId(int i) {
return i; // index number
}
#Override
public View getView(final int index, View view, final ViewGroup parent) {
lIndex = index;
pIndex = index;
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
view = inflater.inflate(R.layout.lstdd, parent, false);
final DataModelDD dmFl = listArray.get(index);
final TextView lbl1 = (TextView) view.findViewById(R.id.txtDDate);
final TextView lbl2 = (TextView) view.findViewById(R.id.txtDres);
lbl1.setText(dmFl.getDDate());
lbl2.setText(dmFl.getDres());
final ToggleButton btnlock = (ToggleButton) view.findViewById(R.id.btnDAlarm);
if (dmFl.getdSel()) {
//selected
btnlock.setButtonDrawable(a_icon);
} else {
//not selected
btnlock.setButtonDrawable(a_dicon);
}
btnlock.setTag(pIndex);
btnlock.setOnCheckedChangeListener(new OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(btnlock.isChecked()){
btnlock.setButtonDrawable(a_icon);
btnlock.setChecked(true);
dmFl.setdSel(true);
Integer position = (Integer) buttonView.getTag();
sp = context.getSharedPreferences("MyPref", 0);
SharedPreferences.Editor editor = sp.edit();
editor.putBoolean("value"+month+"_"+state+"_"+cday, true);
editor.commit();
}
else{
final String alarmTime = dmFl.getDDate();
disableAlarm(buttonView,alarmTime);
btnlock.setButtonDrawable(a_dicon);
btnlock.setChecked(false);
dmFl.setdSel(false);
Integer position = (Integer) buttonView.getTag();
}
}
});
return view;
}
}
and the data model class
package com.example.dd;
public class DataModelDD {
private String DDate;
private String Dres;
private String ShrStr;
private Boolean dSel;
public DataModelDD(String DDate, String Dres, String ShrStr, Boolean dSel){
this.DDate = DDate;
this.Dres = Dres;
this.ShrStr = ShrStr;
this.dSel = dSel;
}
public String getDDate(){
return this.DDate;
}
public void setDDate(String DDate){
this.DDate = DDate;
}
public String getDres(){
return this.Dres;
}
public void setDres(String Dres){
this.Dres = Dres;
}
public String getShrStr(){
return this.ShrStr;
}
public void setShrStr(String ShrStr){
this.ShrStr = ShrStr;
}
public Boolean getdSel(){
return this.dSel;
}
public void setdSel(Boolean dSel){
this.dSel = dSel;
}
}
you need to do
is
SharedPreferences prefs = getSharedPreferences(settingsTAG, 0);
boolean rb0 = prefs.getBoolean("rb0", true);
if (dmFl.getdSel()||rb0) {
//selected
btnlock.setButtonDrawable(a_icon);
} else {
//not selected
btnlock.setButtonDrawable(a_dicon);
}
Hello Everyone!!
I am making a sample shopping cart in which i need to get the position of item clicked and get the image displayed on the page on selecting the image from the shopping cart..But here i am getting image of first item only no matter i have clicked another..it is always showing first image of the list...
Here is my code for ProductAdapter.java
public class ProductAdapter extends BaseAdapter {
private List<Product> mProductList;
private LayoutInflater mInflater;
private boolean mShowQuantity;
public ProductAdapter(List<Product> list, LayoutInflater inflater, boolean showQuantity) {
mProductList = list;
mInflater = inflater;
mShowQuantity = showQuantity;
}
#Override
public int getCount() {
return mProductList.size();
}
#Override
public Object getItem(int position) {
return mProductList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewItem item;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.item, null);
item = new ViewItem();
item.productImageView = (ImageView) convertView
.findViewById(R.id.ImageViewItem);
item.productTitle = (TextView) convertView
.findViewById(R.id.TextViewItem);
item.productQuantity = (TextView) convertView
.findViewById(R.id.textViewQuantity);
convertView.setTag(item);
} else {
item = (ViewItem) convertView.getTag();
}
Product curProduct = mProductList.get(position);
item.productImageView.setImageDrawable(curProduct.productImage);
item.productTitle.setText(curProduct.title);
// Show the quantity in the cart or not
if (mShowQuantity) {
item.productQuantity.setText("Quantity: "
+ ShoppingCartHelper.getProductQuantity(curProduct));
} else {
// Hid the view
item.productQuantity.setVisibility(View.GONE);
}
return convertView;
}
private class ViewItem {
ImageView productImageView;
TextView productTitle;
TextView productQuantity;
}}
And Here is my shoppingcart file
public class ShoppingCartActivity extends Activity {
private List<Product> mCartList;
private ProductAdapter mProductAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.shoppingcart);
mCartList = ShoppingCartHelper.getCartList();
// Make sure to clear the selections
for (int i = 0; i < mCartList.size(); i++) {
mCartList.get(i).selected = false;
}
// Create the list
final ListView listViewCatalog = (ListView) findViewById(R.id.ListViewCatalog);
mProductAdapter = new ProductAdapter(mCartList, getLayoutInflater(),
true);
listViewCatalog.setAdapter(mProductAdapter);
listViewCatalog.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent productDetailsIntent = new Intent(getBaseContext(),
ProductDetailsActivity.class);
productDetailsIntent.putExtra(ShoppingCartHelper.PRODUCT_INDEX,
position);
startActivity(productDetailsIntent);
}
});
}
#Override
protected void onResume() {
super.onResume();
// Refresh the data
if (mProductAdapter != null) {
mProductAdapter.notifyDataSetChanged();
}
double subTotal = 0;
for (Product p : mCartList) {
int quantity = ShoppingCartHelper.getProductQuantity(p);
subTotal += p.price * quantity;
}
TextView productPriceTextView = (TextView) findViewById(R.id.TextViewSubtotal);
productPriceTextView.setText("Subtotal: $" + subTotal);
}
}
ProductActivity.java
public class CatalogActivity extends Activity {
private List<Product> mProductList;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.catalog);
// Obtain a reference to the product catalog
mProductList = ShoppingCartHelper.getCatalog(getResources());
// Create the list
ListView listViewCatalog = (ListView) findViewById(R.id.ListViewCatalog);
listViewCatalog.setAdapter(new ProductAdapter(mProductList, getLayoutInflater(), false));
listViewCatalog.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Intent productDetailsIntent = new Intent(getBaseContext(),ProductDetailsActivity.class);
productDetailsIntent.putExtra(ShoppingCartHelper.PRODUCT_INDEX, position);
startActivity(productDetailsIntent);
}
});
Button viewShoppingCart = (Button) findViewById(R.id.ButtonViewCart);
viewShoppingCart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent viewShoppingCartIntent = new Intent(getBaseContext(), ShoppingCartActivity.class);
startActivity(viewShoppingCartIntent);
}
});
}
}
Code for ProductDetailsActivity.java
public class ProductDetailsActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.productdetails);
List<Product> catalog = ShoppingCartHelper.getCatalog(getResources());
int productIndex = getIntent().getExtras().getInt(
ShoppingCartHelper.PRODUCT_INDEX);
final Product selectedProduct = catalog.get(productIndex);
// Set the proper image and text
ImageView productImageView = (ImageView) findViewById(R.id.ImageViewProduct);
productImageView.setImageDrawable(selectedProduct.productImage);
TextView productTitleTextView = (TextView) findViewById(R.id.TextViewProductTitle);
productTitleTextView.setText(selectedProduct.title);
TextView productDetailsTextView = (TextView) findViewById(R.id.TextViewProductDetails);
productDetailsTextView.setText(selectedProduct.description);
TextView productPriceTextView = (TextView) findViewById(R.id.TextViewProductPrice);
productPriceTextView.setText("$" + selectedProduct.price);
// Update the current quantity in the cart
TextView textViewCurrentQuantity = (TextView) findViewById(R.id.textViewCurrentlyInCart);
textViewCurrentQuantity.setText("Currently in Cart: "
+ ShoppingCartHelper.getProductQuantity(selectedProduct));
// Save a reference to the quantity edit text
final EditText editTextQuantity = (EditText) findViewById(R.id.editTextQuantity);
Button addToCartButton = (Button) findViewById(R.id.ButtonAddToCart);
addToCartButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Check to see that a valid quantity was entered
int quantity = 0;
try {
quantity = Integer.parseInt(editTextQuantity.getText()
.toString());
if (quantity < 0) {
Toast.makeText(getBaseContext(),
"Please enter a quantity of 0 or higher",
Toast.LENGTH_SHORT).show();
return;
}
} catch (Exception e) {
Toast.makeText(getBaseContext(),
"Please enter a numeric quantity",
Toast.LENGTH_SHORT).show();
return;
}
// If we make it here, a valid quantity was entered
ShoppingCartHelper.setQuantity(selectedProduct, quantity);
// Close the activity
finish();
}
});
}
Plz guys Any help will be highly appreciated.
Thanx in advance..
The int position in onItemClick gives the position of the clicked item in the array/list you gave to the adapter.
You can also do getItemAtPosition(); on your listview, if you don't have an easy handle on your original list.
add this code to your Project :
mProductList.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent,
View v, int position, long id)
{
int h = parent.getPositionForView(v);
Toast.makeText(getBaseContext(),
"pic" + (position + 1) + " selected" + h,
Toast.LENGTH_SHORT).show();
}
});
Just geussig that you have a problematic code where you are reading the index value. Following is the sample code for writing and reading int extra:
To put int value:
productDetailsIntent.putExtra(ShoppingCartHelper.PRODUCT_INDEX,
position);
Following code should be used to read this value in another Activity
int index = getIntent().getExtras().getInt(ShoppingCartHelper.PRODUCT_INDEX);
Hope it helps...