Retrieving Shared Preferences from a check-able list - android

I am currently creating a new project that involves a checkbox for a list of items contained in an array.xml. I am using shared preferences and want to be able to pull up the checked items in another activity. I have a button that saves the selections and opens a new activity. Now I am just having trouble having it appear in second activity. I will show my code for my main activity as I am not sure how to begin on the second activity.
#Override
public void onClick(View v) {
String selected = "";
int cntChoice = myList.getCount();
SparseBooleanArray sparseBooleanArray = myList.getCheckedItemPositions();
for(int i = 0; i < cntChoice; i++){
if(sparseBooleanArray.get(i)) {
selected += myList.getItemAtPosition(i).toString() + "\n";
System.out.println("Checking list while adding:" + myList.getItemAtPosition(i).toString());
SaveSelections();
Intent learnintent = new
Intent(MainActivity.this,UserList.class);
learnintent.putExtra("",selected);
Toast.makeText(MainActivity.this, selected,
Toast.LENGTH_LONG).show();
startActivity(learnintent);
}
}
Toast.makeText(MainActivity.this, selected,
Toast.LENGTH_LONG).show();
}});
clearAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
ClearSelections();
}
});
}
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);
Toast.makeText(getApplicationContext(), "Curren Item: " + currentItem,Toast.LENGTH_LONG).show();
} 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();
}

#KeithB
I written Singleton Shared Preferences class. it may be useful for you
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
public class SharedPref
{
private static SharedPreferences mSharedPref;
public static final String NAME = "NAME";
public static final String AGE = "AGE";
public static final String IS_SELECT = "IS_SELECT";
public static void init(Context context)
{
if(mSharedPref == null)
mSharedPref = context.getSharedPreferences(context.getPackageName(), Activity.MODE_PRIVATE);
}
public static String read(String key, String defValue) {
return mSharedPref.getString(key, defValue);
}
public static void write(String key, String value) {
SharedPreferences.Editor prefsEditor = mSharedPref.edit();
prefsEditor.putString(key, value);
prefsEditor.commit();
}
public static boolean read(String key, boolean defValue) {
return mSharedPref.getBoolean(key, defValue);
}
public static void write(String key, boolean value) {
SharedPreferences.Editor prefsEditor = mSharedPref.edit();
prefsEditor.putBoolean(key, value);
prefsEditor.commit();
}
public static Integer read(String key, int defValue) {
return mSharedPref.getInt(key, defValue);
}
public static void write(String key, Integer value) {
SharedPreferences.Editor prefsEditor = mSharedPref.edit();
prefsEditor.putInt(key, value).commit();
}
}
for more info see the link SharedPref Sample

Related

Android Bookmak Page by Clicking Image not working

I wrote the core to add PDF pages to shared-preference for bookmarks, but when I click the image neither the image get changed nor the page number added to the book mark list.
Below is my code. It show me no error and image get clicked but the page number not added to spinner for book mark list.
Before I used a textview for the task and that was working fine but now I want a tag image to get changed when I tag or un-tag a page.
#EActivity(R.layout.activity_main)
#OptionsMenu(R.menu.actionbar)
public class PDFViewActivity extends SherlockActivity implements OnPageChangeListener, View.OnClickListener {
public static final String SAMPLE_FILE = "myfile.pdf";
public static final String KEY_BOOKMARKS = "bookmarks_pages";
#ViewById
PDFView pdfView;
#NonConfigurationInstance
String pdfName = SAMPLE_FILE;
#NonConfigurationInstance
Integer pageNumber = 1;
SharedPreferences sharedpreferences;
public static final String mypreference = "mypref";
public static final String Name = "nameKey";
public static final String Email = "emailKey";
Spinner bookmarkSp;
ArrayAdapter<String> dataAdapter;
private final int TotalPages = 57;
#AfterViews
void afterViews() {
sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
display(pdfName, false);
}
int check = 0;
private void display(String assetFileName, boolean jumpToFirstPage) {
if (jumpToFirstPage) pageNumber = 1;
int x = TotalPages;
int[] page_seq = new int[TotalPages];
for (int i = 0; i < TotalPages; i++) {
page_seq[i] = --x;
Log.d("testdesp", "" + page_seq[i]);
}
// .pages(2,1,0)
pdfView.fromAsset(assetFileName)
.defaultPage(TotalPages)
.pages(page_seq)
.onLoad(new OnLoadCompleteListener() {
#Override
public void loadComplete(int nbPages) {
((TextView) findViewById(R.id.tv_total_page)).setText("/ " + pdfView.getPageCount());
}
})
.onPageChange(this)
.load();
findViewById(R.id.btn_go).setOnClickListener(this);
findViewById(R.id.tag_btn).setOnClickListener(this);
bookmarkSp = (Spinner) findViewById(R.id.sp_bookmark_list);
List<String> list = new ArrayList<String>();
String pages = sharedpreferences.getString(KEY_BOOKMARKS, "");
String[] split = pages.split(",");
list.add("");
for (String val : split)
if (val.length() > 0) {
int value = Integer.parseInt(val);
// value = pdfView.getPageCount() - (value - 1);
value = TotalPages - (value - 1);
list.add("" + value);
}
dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
bookmarkSp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (++check > 1) {
String val = (String) parent.getItemAtPosition(position);
if (val.length() > 0) {
int value = Integer.parseInt(val);
value = pdfView.getPageCount() - (value - 1);
pdfView.jumpTo(value);
}
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
bookmarkSp.setAdapter(dataAdapter);
}
#Override
public void onPageChanged(int page, int pageCount) {
pageNumber = page;
((EditText) findViewById(R.id.et_page_number)).setText(pageCount - (pageNumber - 1) + "");
if (check(page))
((ImageView) findViewById(R.id.tag_btn)).setImageResource(R.drawable.tagged);
else
((ImageView) findViewById(R.id.tag_btn)).setImageResource(R.drawable.untaged);
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
private boolean displaying(String fileName) {
return fileName.equals(pdfName);
}
#Override
public void onClick(View view) {
view.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.fade_out));
switch (view.getId()) {
case R.id.btn_go:
int page = Integer.parseInt(((EditText) findViewById(R.id.et_page_number)).getText().toString());
page = TotalPages - (page - 1);
pdfView.jumpTo(page);
break;
case R.id.tag_btn:
if (((ImageView) findViewById(R.id.tag_btn)).getDrawable().getConstantState() == getResources().getDrawable(R.drawable.untaged).getConstantState() ) {
sharedpreferences.edit().putString(KEY_BOOKMARKS, sharedpreferences.getString(KEY_BOOKMARKS, "") + pageNumber + ",").commit();
((ImageView) findViewById(R.id.tag_btn)).setImageResource(R.drawable.tagged);
dataAdapter.add(pdfView.getPageCount() - (pageNumber - 1) + "");
dataAdapter.notifyDataSetChanged();
} else if (((ImageView) findViewById(R.id.tag_btn)).getDrawable().getConstantState() == getResources().getDrawable(R.drawable.tagged).getConstantState() ) {
sharedpreferences.edit().putString(KEY_BOOKMARKS, sharedpreferences.getString(KEY_BOOKMARKS, "").replace(pageNumber + ",", "")).commit();
((ImageView) findViewById(R.id.tag_btn)).setImageResource(R.drawable.untaged);
dataAdapter.remove(TotalPages - (pageNumber - 1) + "");
dataAdapter.notifyDataSetChanged();
}
break;
}
}
boolean check(int page) {
String number = sharedpreferences.getString(KEY_BOOKMARKS, "");
Log.d("testdisp", pdfView.getPageCount() + " ** " + number + " ****" + number.contains(page + ","));
return number.contains(page + ",");
}
}
I resolved my issue by adding a drawable resource
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:drawable="#drawable/tagged" />
<item android:state_checked="false" android:drawable="#drawable/untaged" />
</selector>
and made below changes in my java activity code.
if (((CheckBox) findViewById(R.id.chk_tag)).isChecked()) {
sharedpreferences.edit().putString(KEY_BOOKMARKS, sharedpreferences.getString(KEY_BOOKMARKS, "") + pageNumber + ",").commit();
((CheckBox) findViewById(R.id.chk_tag)).setChecked(true);
dataAdapter.add(pdfView.getPageCount() - (pageNumber - 1) + "");
dataAdapter.notifyDataSetChanged();
} else {
sharedpreferences.edit().putString(KEY_BOOKMARKS, sharedpreferences.getString(KEY_BOOKMARKS, "").replace(pageNumber + ",", "")).commit();
((CheckBox) findViewById(R.id.chk_tag)).setChecked(false);
}

MultiSelectListPreference onPreferenceChange() method getting wrong parameters

I have an Android app with a MultiSelectListPreference, and I'm using the onPreferenceChange() method to update the Preference's summary. I've managed to write the code that updates the summary based on the newValues parameter, but the contents of the Object do not match the actual options selected by the user.
Here is my code:
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (preference instanceof MultiSelectListPreference) {
List<String> newValues = new ArrayList<>((HashSet<String>) newValue);
MultiSelectListPreference pref = (MultiSelectListPreference) preference;
ArrayList<String> newSummary = new ArrayList<>();
ArrayList<CharSequence> values = new ArrayList<>(Arrays.asList(pref.getEntryValues()));
for (int i = 0; i < newValues.size(); i++) {
int currentIndex = findIndexOfString(values, newValues.get(i).replaceAll(" ", ""));
String title = (currentIndex >= 0) ? pref.getEntries()[currentIndex].toString().replaceAll(" ", "") : "";
newSummary.add(title);
}
pref.setSummary(TextUtils.join(", ", newSummary));
}
return true;
}
private static int findIndexOfString(List<CharSequence> list, String s) {
for (int i = 0; i < list.size(); i++) {
if (s.equals(list.get(i).toString().replaceAll(" ", ""))) {
return i;
}
}
return -1;
}
This is the code I'm using to set summary based on the newValue Object received from onPreferenceChange(), which contains the values stored as a preference. (Not good for the summary)
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (preference instanceof MultiSelectListPreference) {
List<String> newValues = new ArrayList<>((HashSet<String>) newValue);
pref.setSummary(TextUtils.join(", ", getSummaryListFromValueList(newValues)));
}
return true;
}
private List<String> getSummaryListFromValueList(List<String> valueList) {
String[] allSummaries = getResources().getStringArray(R.array.pref_notif);
String[] allValues = getResources().getStringArray(R.array.pref_notif_values);
List<String> summaryList = new ArrayList<>();
for (int i = 0; i < allValues.length; i++) {
for (String value : valueList) {
if (allValues[i].equals(value)) {
summaryList.add(allSummaries[i]);
}
}
}
return summaryList;
}

Getting Same Values For Two Different Keys in Shared Preferences

i am creating an app in which different payments modes are there so for card payments and cheque payments i have created two different activities in which i am getting details from user and save the data into shared Preferences and then app returns back to the activities where other details are also there and then user can save the data on a button click.This data gets saved into Sqlite Database.
My problem is when i am selecting card payment its getting stored properly but the same value also getting stored at cheque No aswell into the sqlite database.Inshort the value of card payment is getting copied into cheque no column by default.
below is my code for Card payment Activity :
public class CardNo extends Activity {
String bankname;
String cardno;
int chq;
TextView textView1, textView2;
EditText editText1, editText2;
Button btn;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.creditdebit);
textView1 = (TextView) findViewById(R.id.tv1);
textView2 = (TextView) findViewById(R.id.tv2);
editText1 = (EditText) findViewById(R.id.bankname);
editText2 = (EditText) findViewById(R.id.cardno);
btn = (Button) findViewById(R.id.btn1);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveData();
Intent card = new Intent(CardNo.this, EnterAmount.class);
startActivity(card);
finish();
}
});
}
private void saveData() {
bankname = editText1.getText().toString();
cardno = editText2.getText().toString();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("Bank Name", bankname);
editor.putString("Card No", cardno);
editor.apply();
}
}
Now code for cheque payment Activity :
public class Cheque extends Activity {
String bankname1;
String chequeno;
int chq;
TextView textView1,textView2;
EditText editText1,editText2;
Button btn;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cheque);
textView1=(TextView)findViewById(R.id.tv11);
textView2=(TextView)findViewById(R.id.tv12);
editText1=(EditText)findViewById(R.id.bankname1);
editText2=(EditText)findViewById(R.id.chequeno);
btn=(Button)findViewById(R.id.btn11);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveData();
Intent cheque = new Intent(Cheque.this, EnterAmount.class);
startActivity(cheque);
finish();
}
});
}
private void saveData() {
bankname1 = editText1.getText().toString();
chequeno = editText2.getText().toString();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("Bank Name", bankname1);
editor.putString("Cheque No", chequeno);
editor.apply();
}
}
Now the code of the activity where i am retrieving the data from shared preferences and storing the data into sqlite.
public class EnterAmount extends Activity implements OnClickListener {
Intent intent;
Button save;
Spinner spinnerPayment, spinnerCategory;
EditText etamt, etbdgt, et_get_other;
String date, sBdgt, budget, bankname, cardno, chequeno;
String sAmt;
String spinnerItemSelectedPayment;
String spinnerItemSelectedCategory;
// String category;
int amt;
int date2;
TextView caategories, tv_cat;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.enteramount);
save = (Button) findViewById(R.id.bsaveDb);
caategories = (TextView) findViewById(R.id.tvCaategories);
etamt = (EditText) findViewById(R.id.etAmount);
etbdgt = (EditText) findViewById(R.id.etbudget);
spinnerCategory = (Spinner) findViewById(R.id.spinnerCategory);
spinnerPayment = (Spinner) findViewById(R.id.payment_spinner);
List<String> sCategory = new ArrayList<String>();
String[] categories = {"Food", "Bills",
"Travel", "Entertainment", "Office Stationary",
"Medical Expenses", "Fuel"
};
sCategory.add("Food");
sCategory.add("Office Stationary");
sCategory.add("Bills");
sCategory.add("Travel");
sCategory.add("Entertainment");
sCategory.add("Medical Expenses");
sCategory.add("Fuel");
ArrayAdapter<String> sc = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, sCategory);
spinnerCategory.setAdapter(sc);
List<String> l = new ArrayList<String>();
String[] paymentMode = {"Cash", "Credit/Debit Card", "Cheque", "NetBanking"};
l.add("Cash");
l.add("Credit/Debit Card");
l.add("Cheque");
l.add("NetBanking");
ArrayAdapter<String> sp = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, l);
spinnerPayment.setAdapter(sp);
save.setOnClickListener(this);
spinnerCategory.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent,
View selectedItemView, int pos, long id) {
spinnerItemSelectedCategory = parent.getItemAtPosition(pos)
.toString();
}
public void onNothingSelected(AdapterView<?> parentView) {
spinnerItemSelectedCategory = "Food";
}
});
spinnerPayment.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent,
View selectedItemView, int pos, long id) {
spinnerItemSelectedPayment = parent.getItemAtPosition(pos).toString();
if (spinnerItemSelectedPayment.equals("Cheque")) {
Intent cheque = new Intent(EnterAmount.this, Cheque.class);
cheque.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(cheque);
} else if (spinnerItemSelectedPayment.equals("Credit/Debit Card")) {
Intent card = new Intent(EnterAmount.this, CardNo.class);
card.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(card);
}
}
public void onNothingSelected(AdapterView<?> parentView) {
spinnerItemSelectedPayment = "Cash";
}
});
final Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy-HH:mm:ss ");
date = sdf.format(c.getTime());
int yy = c.get(Calendar.YEAR);
int mm = c.get(Calendar.MONTH) + 1;
int dd = c.get(Calendar.DAY_OF_MONTH);
String s = yy + "" + (mm < 10 ? ("0" + mm) : (mm)) + ""
+ (dd < 10 ? ("0" + dd) : (dd));
Log.e("datechange", s);
date2 = Integer.parseInt(s);
Log.e("integer2", "hello" + date2);
}
#Override
public void onBackPressed () {
super.onBackPressed();
finish();
}
private void vibrate(int ms) {
((Vibrator) getSystemService(Context.VIBRATOR_SERVICE)).vibrate(ms);
}
private void loadSavedPreferences() {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
budget = sharedPreferences.getString("Budget", " ");
getSharedPreferences(mypreference,Context.MODE_PRIVATE);
bankname = sharedPreferences.getString("Bank Name", "Not Applicable");
cardno = sharedPreferences.getString("Card No", "Not Applicable");
chequeno = sharedPreferences.getString("Cheque No", "Not Applicable");
}
private void removeSavedPreferences() {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.remove("Bank Name");
editor.remove("Cheque No");
editor.remove("Card No");
editor.apply();
}
private void savePreferences(String key, String value) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bsaveDb: {
savePreferences("Budget", etbdgt.getText().toString());
loadSavedPreferences();
sAmt = etamt.getText().toString();
Log.e("category", "Hello" + sAmt);
try {
amt = Integer.parseInt(sAmt);
Log.e("amt is", "" + amt);
} catch (Exception e) {
}
DbClass dc = new DbClass(this);
dc.open();
if (amt == 0) {
Toast.makeText(getApplicationContext(),
"Please insert the amount", Toast.LENGTH_SHORT).show();
} else {
dc.categoryDetailsInsert(amt, spinnerItemSelectedCategory, date, spinnerItemSelectedPayment, date2, bankname, cardno, chequeno);
dc.close();
Toast.makeText(getApplicationContext(), "Saved successfully",
Toast.LENGTH_LONG).show();
amt = 0;
etamt.setText("");
etbdgt.setText(budget);
removeSavedPreferences();
}
break;
}
}
}
}
i am attching a screenshot of sqlite database and you can see bank name is getting stored properly but cardno and cheque no is always same with respect to payment.Screenshot Of Database
Attach your keys to the context tag to prevent override of values.
like:
String TAG = "ContextName or ActivityName";
then on saving do:
pref.put(TAG+key, "value");
Actually above code is Fine the Problem was in the code where i was retrieving code from the database i inserted the same index number for the two different columns. so i was getting same values for cheque no and debit card number.

Items not displaying orderwise in Recycler View

In my Recycler View not displaying the item orderwise routinely changing the items for each and every time while running the program.
How to display Order wise the items in Recycler View.
Code:
final CustomLinearLayoutManagercartpage layoutManager = new CustomLinearLayoutManagercartpage(CartItems.this, LinearLayoutManager.VERTICAL, false);
recyleitems.setHasFixedSize(false);
recyleitems.setLayoutManager(layoutManager);
cartadapter = new CartlistAdapter(cart, CartItems.this);
Log.i(String.valueOf(cartadapter), "cartadapter");
recyleitems.setAdapter(cartadapter);
recyleitems.setNestedScrollingEnabled(false);
myView.setVisibility(View.GONE);
cartadapter.notifyDataSetChanged();
Adapter:
public class CartlistAdapter extends RecyclerView.Adapter < CartlistAdapter.ViewHolder > {
private ArrayList < CartItemoriginal > cartlistadp;
private ArrayList < Cartitemoringinaltwo > cartlistadp2;
DisplayImageOptions options;
private Context context;
public static final String MyPREFERENCES = "MyPrefs";
public static final String MYCARTPREFERENCE = "CartPrefs";
public static final String MyCartQtyPreference = "Cartatyid";
SharedPreferences.Editor editor;
SharedPreferences shared,
wishshared;
SharedPreferences.Editor editors;
String pos,
qtyDelete;
String date;
String currentDateandTime;
private static final int VIEW_TYPE_ONE = 1;
private static final int VIEW_TYPE_TWO = 2;
private static final int TYPE_HEADER = 0;
private Double orderTotal = 0.00;
DecimalFormat df = new DecimalFormat("0");
Double extPrice;
View layout,
layouts;
SharedPreferences sharedPreferences;
SharedPreferences.Editor QutId;
boolean flag = false;
public CartlistAdapter() {
}
public CartlistAdapter(ArrayList < CartItemoriginal > cartlistadp, Context context) {
this.cartlistadp = cartlistadp;
this.cartlistadp2 = cartlistadp2;
this.context = context;
options = new DisplayImageOptions.Builder().cacheOnDisk(true).cacheInMemory(true).showImageOnLoading(R.drawable.b2)
.showImageForEmptyUri(R.drawable.b2).build();
if (YelloPage.imageLoader.isInited()) {
YelloPage.imageLoader.destroy();
}
YelloPage.imageLoader.init(ImageLoaderConfiguration.createDefault(context));
}
public int getItemViewType(int position) {
if (cartlistadp.size() == 0) {
Toast.makeText(context, String.valueOf(cartlistadp), Toast.LENGTH_LONG).show();
return VIEW_TYPE_TWO;
}
return VIEW_TYPE_ONE;
}
#Override
public CartlistAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int position) {
ViewHolder viewHolder = null;
switch (position) {
case VIEW_TYPE_TWO:
View view2 = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.activity_cart, viewGroup, false);
viewHolder = new ViewHolder(view2, new MyTextWatcher(viewGroup, position));
// return view holder for your placeholder
break;
case VIEW_TYPE_ONE:
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.cartitemrow, viewGroup, false);
viewHolder = new ViewHolder(view, new MyTextWatcher(view, position));
// return view holder for your normal list item
break;
}
return viewHolder;
}
#Override
public void onBindViewHolder(CartlistAdapter.ViewHolder viewHolder, int position) {
viewHolder.productnames.setText(cartlistadp.get(position).getProductname());
viewHolder.cartalisname.setText(cartlistadp.get(position).getAliasname());
viewHolder.cartprice.setText("Rs" + " " + cartlistadp.get(position).getPrice());
viewHolder.cartdelivery.setText(cartlistadp.get(position).getDelivery());
viewHolder.cartshippin.setText(cartlistadp.get(position).getShippincharge());
viewHolder.cartsellername.setText(cartlistadp.get(position).getSellername());
viewHolder.Error.setText(cartlistadp.get(position).getError());
viewHolder.qty.setTag(cartlistadp.get(position));
viewHolder.myTextWatcher.updatePosition(position);
if (cartlistadp.get(position).getQty() != 0) {
viewHolder.qty.setText(String.valueOf(cartlistadp.get(position).getQty()));
viewHolder.itemView.setTag(viewHolder);
} else {
viewHolder.qty.setText("0");
}
YelloPage.imageLoader.displayImage(cartlistadp.get(position).getProductimg(), viewHolder.cartitemimg, options);
}
#Override
public int getItemCount() {
return cartlistadp.size();
}
public long getItemId(int position) {
return position;
}
public Object getItem(int position) {
return cartlistadp.get(position);
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView productnames, cartalisname, cartprice, cartdelivery, cartshippin, cartsellername, Error, total;
private ImageView cartitemimg;
private ImageButton wishbtn, removebtn;
private LinearLayout removecart, movewishlist;
private CardView cd;
private EditText qty;
private ImageView WishImg;
public MyTextWatcher myTextWatcher;
public ViewHolder(final View view, MyTextWatcher myTextWatcher) {
super(view);
productnames = (TextView) view.findViewById(R.id.cartitemname);
cartalisname = (TextView) view.findViewById(R.id.cartalias);
cartprice = (TextView) view.findViewById(R.id.CartAmt);
cartdelivery = (TextView) view.findViewById(R.id.cartdel);
cartshippin = (TextView) view.findViewById(R.id.shippingcrg);
cartsellername = (TextView) view.findViewById(R.id.cartSellerName);
cartitemimg = (ImageView) view.findViewById(R.id.cartimg);
Error = (TextView) view.findViewById(R.id.error);
this.myTextWatcher = myTextWatcher;
removecart = (LinearLayout) view.findViewById(R.id.removecart);
movewishlist = (LinearLayout) view.findViewById(R.id.movewishlist);
WishImg = (ImageView) view.findViewById(R.id.wishimg);
qty = (EditText) view.findViewById(R.id.quantity);
qty.addTextChangedListener(myTextWatcher);
String pid, qid;
sharedPreferences = view.getContext().getSharedPreferences(MYCARTPREFERENCE, Context.MODE_PRIVATE);
QutId = sharedPreferences.edit();
Log.d("Position checking1 ---", String.valueOf(getAdapterPosition()));
//MyTextWatcher textWatcher = new MyTextWatcher(view,qty);
// qty.addTextChangedListener(new MyTextWatcher(view,getAdapterPosition()));
//qty.addTextChangedListener(textWatcher);
qty.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
qty.setSelection(qty.getText().length());
return false;
}
});
wishshared = view.getContext().getSharedPreferences(MyPREFERENCES, context.MODE_PRIVATE);
editors = view.getContext().getSharedPreferences(MyPREFERENCES, context.MODE_PRIVATE).edit();
shared = view.getContext().getSharedPreferences(MYCARTPREFERENCE, context.MODE_PRIVATE);
editor = view.getContext().getSharedPreferences(MYCARTPREFERENCE, context.MODE_PRIVATE).edit();
cd = (CardView) view.findViewById(R.id.cv);
productnames.setSingleLine(false);
productnames.setEllipsize(TextUtils.TruncateAt.END);
productnames.setMaxLines(2);
//totalPrice();
view.setClickable(true);
// view.setFocusableInTouchMode(true);
removecart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (cartlistadp.size() == 1) {
Intent list = new Intent(v.getContext(), Cart.class);
context.startActivity(list);
((Activity) context).finish();
removeAt(getAdapterPosition());
Log.i(String.valueOf(getPosition()), "item");
Toast.makeText(context, "All items deleted from your WishList", Toast.LENGTH_LONG).show();
} else {
removeAt(getAdapterPosition());
}
}
});
MovewishList();
totalPrice();
}
private void totalPrice() {
int price = 0;
for (int j = 0; j < cartlistadp.size(); j++) {
price += Integer.parseInt(cartlistadp.get(j).getPrice()) * (cartlistadp.get(j).getQty());
String totalprice = String.valueOf(price);
String count = String.valueOf(cartlistadp.size());
CartItems.Totalamt.setText(totalprice);
CartItems.cartcount.setText("(" + count + ")");
CartItems.carttotalcount.setText("(" + count + ")");
}
}
public void removeAt(int positions) {
JSONArray test = new JSONArray();
JSONArray test1 = new JSONArray();
JSONArray test2 = new JSONArray();
JSONArray item = null;
JSONArray itemsQty = null;
test1.put("0");
test2.put("0");
test.put(test1);
test.put(test2);
String channel = shared.getString(Constants.cartid, String.valueOf(test));
pos = cartlistadp.get(getAdapterPosition()).getProductid();
qtyDelete = String.valueOf(cartlistadp.get(getAdapterPosition()).getQty());
try {
JSONArray delteitems = new JSONArray(channel);
itemsQty = delteitems.getJSONArray(0);
item = delteitems.getJSONArray(1);
for (int x = 0; x < itemsQty.length(); x++) {
if (pos.equalsIgnoreCase(itemsQty.getString(x))) {
itemsQty.remove(x);
cartlistadp.remove(positions);
notifyItemRemoved(positions);
notifyItemRangeChanged(positions, cartlistadp.size());
notifyDataSetChanged();
}
}
for (int y = 0; y < item.length(); y++) {
if (qtyDelete.equalsIgnoreCase(item.getString(y)))
item.remove(y);
}
String s = String.valueOf(delteitems);
editor.putString(Constants.cartid, String.valueOf(delteitems));
editor.apply();
} catch (JSONException e) {
e.printStackTrace();
}
}
public void MovewishList() {
movewishlist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (cartlistadp.size() == 1) {
pos = cartlistadp.get(getAdapterPosition()).getProductid();
JSONArray items3;
if (!flag) {
// wishlist.setBackgroundResource(R.drawable.wishnew);
flag = true;
String channel = wishshared.getString(Constants.productid, "['']");
JSONArray items;
String wishitem;
if (TextUtils.isEmpty(channel)) {
items = new JSONArray();
items.put(String.valueOf(pos));
wishitem = String.valueOf(items);
editors.putString(Constants.productid, wishitem);
editors.apply();
removeAt(getAdapterPosition());
Toast.makeText(context, "cartItems", Toast.LENGTH_LONG).show();
flag = false;
} else {
try {
Boolean found = false;
items = new JSONArray(channel);
for (int x = 0; x < items.length(); x++) {
if (pos.equalsIgnoreCase(items.getString(x))) {
found = true;
removeAt(getAdapterPosition());
Toast.makeText(context, "cartItems1", Toast.LENGTH_LONG).show();
}
}
if (!found) {
items.put(String.valueOf(pos));
wishitem = String.valueOf(items);
editors.putString(Constants.productid, wishitem);
removeAt(getAdapterPosition());
Toast.makeText(context, Constants.productid, Toast.LENGTH_LONG).show();
Log.i(Constants.productid, "wishitems");
}
editors.apply();
flag = false;
} catch (JSONException e) {
e.printStackTrace();
}
}
Intent list = new Intent(view.getContext(), Cart.class);
context.startActivity(list);
((Activity) context).finish();
} else {
removeAt(getAdapterPosition());
Intent list = new Intent(view.getContext(), Cart.class);
context.startActivity(list);
((Activity) context).finish();
}
} else {
pos = cartlistadp.get(getAdapterPosition()).getProductid();
if (!flag) {
// wishlist.setBackgroundResource(R.drawable.wishnew);
flag = true;
String channel = wishshared.getString(Constants.productid, "['']");
JSONArray items;
String wishitem;
if (TextUtils.isEmpty(channel)) {
items = new JSONArray();
items.put(String.valueOf(pos));
wishitem = String.valueOf(items);
editors.putString(Constants.productid, wishitem);
editors.apply();
removeAt(getAdapterPosition());
Toast.makeText(context, "cartItems", Toast.LENGTH_LONG).show();
flag = false;
} else {
try {
Boolean found = false;
items = new JSONArray(channel);
for (int x = 0; x < items.length(); x++) {
if (pos.equalsIgnoreCase(items.getString(x))) {
found = true;
removeAt(getAdapterPosition());
}
}
if (!found) {
items.put(String.valueOf(pos));
wishitem = String.valueOf(items);
editors.putString(Constants.productid, wishitem);
removeAt(getAdapterPosition());
Log.i(Constants.productid, "wishitems");
}
editors.apply();
flag = false;
} catch (JSONException e) {
e.printStackTrace();
}
}
} else {
removeAt(getAdapterPosition());
}
}
}
});
}
}
public class InputFilterMinMax implements InputFilter {
private int min, max;
public InputFilterMinMax(int min, int max) {
this.min = min;
this.max = max;
}
public InputFilterMinMax(String min, String max) {
this.min = Integer.parseInt(min);
this.max = Integer.parseInt(max);
}
#Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
try {
int input = Integer.parseInt(dest.toString() + source.toString());
if (isInRange(min, max, input))
return null;
} catch (NumberFormatException nfe) {}
return "";
}
private boolean isInRange(int a, int b, int c) {
return b > a ? c >= a && c <= b : c >= b && c <= a;
}
}
private class MyTextWatcher implements TextWatcher {
private View view;
private EditText editText;
private int position;
//private int position;
private MyTextWatcher(View view, int position) {
this.view = view;
this.position = position;
// this.position = adapterPosition;
// cartlistadp.get(position).getQty() = Integer.parseInt((Caption.getText().toString()));
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//do nothing
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
// EditText qtyView = (EditText) view.findViewById(R.id.quantity);
Log.i("editextpostion", String.valueOf(position));
}
public void afterTextChanged(Editable s) {
DecimalFormat df = new DecimalFormat("0");
String qtyString = s.toString();
int quantity = qtyString.equals("") ? 0 : Integer.valueOf(qtyString);
String quty = String.valueOf(quantity);
EditText qtyView = (EditText) view.findViewById(R.id.quantity);
CartItemoriginal product = (CartItemoriginal) qtyView.getTag();
// int position = (int) view.qtyView.getTag();
Log.d("postion is qtytag", "Position is: " + product);
qtyView.setFilters(new InputFilter[] {
new InputFilterMinMax(product.getMinquantity(), product.getMaxquantity())
});
if (product.getQty() != quantity) {
Double currPrice = product.getExt();
Double price = Double.parseDouble(product.getPrice());
int maxaty = Integer.parseInt(product.getMaxquantity());
int minqty = Integer.parseInt(product.getMinquantity());
if (quantity < maxaty) {
extPrice = quantity * price;
} else {
Toast.makeText(context, "Sorry" + " " + " " + "we are shipping only" + " " + " " + maxaty + " " + " " + "unit of quantity", Toast.LENGTH_LONG).show();
}
Double priceDiff = Double.valueOf(df.format(extPrice - currPrice));
product.setQty(quantity);
product.setExt(extPrice);
TextView ext = (TextView) view.findViewById(R.id.CartAmt);
if (product.getQty() != 0) {
ext.setText("Rs." + " " + df.format(product.getExt()));
} else {
ext.setText("0");
}
if (product.getQty() != 0) {
qtyView.setText(String.valueOf(product.getQty()));
} else {
qtyView.setText("");
}
JSONArray test = new JSONArray();
JSONArray test1 = new JSONArray();
JSONArray test2 = new JSONArray();
JSONArray items = null;
JSONArray itemsQty = null;
test1.put("0");
test2.put("0");
test.put(test1);
test.put(test2);
JSONArray listitems = null;
//String Sharedqty= String.valueOf(cartlistadp.get(getAdapterPosition()).getQty());
String channel = (shared.getString(Constants.cartid, String.valueOf(test)));
try {
listitems = new JSONArray(channel);
itemsQty = listitems.getJSONArray(1);
} catch (JSONException e) {
e.printStackTrace();
}
try {
if (itemsQty != null) {
itemsQty.put(position + 1, qtyString);
}
} catch (JSONException e) {
e.printStackTrace();
}
try {
if (listitems != null) {
listitems.put(1, itemsQty);
}
} catch (JSONException e) {
e.printStackTrace();
}
QutId.putString(Constants.cartid, String.valueOf(listitems));
QutId.apply();
Toast.makeText(context, String.valueOf(listitems), Toast.LENGTH_SHORT).show();
totalPrice();
}
return;
}
private void totalPrice() {
int price = 0;
for (int j = 0; j < cartlistadp.size(); j++) {
price += Integer.parseInt(cartlistadp.get(j).getPrice()) * (cartlistadp.get(j).getQty());
String totalprice = String.valueOf(price);
String count = String.valueOf(cartlistadp.size());
CartItems.Totalamt.setText(totalprice);
CartItems.cartcount.setText("(" + count + ")");
CartItems.carttotalcount.setText("(" + count + ")");
}
}
public void updatePosition(int position) {
this.position = position;
}
}
}
Thanks in Advance.
For sorting you need to Collection.sort method of Java and also you need to implement comparable interface for define your comparison.
CartItemoriginal implements Comparable {
public int compareTo(Object obj) { } }
Updated
public class CartItemoriginal implements Comparable<CartItemoriginal > {
private Float val;
private String id;
public CartItemoriginal (Float val, String id){
this.val = val;
this.id = id;
}
#Override
public int compareTo(ToSort f) {
if (val.floatValue() > f.val.floatValue()) {
return 1;
}
else if (val.floatValue() < f.val.floatValue()) {
return -1;
}
else {
return 0;
}
}
#Override
public String toString(){
return this.id;
}
}
and use
Collections.sort(sortList);

Shared Preference: Retrieve and Display the data stored

I have make used of shared preference to store my data into MyUserChoice.xml:
<string name="MyUserChoice">ApplicationInfo{1ebad2cb com.example.user.example},
ApplicationInfo{15c7caa8 com.android.gallery},
ApplicationInfo{bc0a9c1 com.android.quicksearchbox}</string>
I have tried to retrieve the 3 string above.
for (int i = 0; i < count; i++) {
String currentItem = (String) myList.getAdapter()
.getItem(i);
if (selectedItems.contains(currentItem)) {
myList.setItemChecked(i, true);
Toast.makeText(getApplicationContext(),
"Current Item: " + currentItem,
Toast.LENGTH_LONG).show();
} else {
myList.setItemChecked(i, false);
}
}
What I want to achieve is that upon I relaunch my app, it should display each of this string one after another.
Current Item: ApplicationInfo{1ebad2cb com.example.user.example},
Current Item: ApplicationInfo{15c7caa8 com.android.gallery},
Current Item: ApplicationInfo{bc0a9c1 com.android.quicksearchbox}
Instead, it returns nothing and I saw this in my logcat:
10-09 01:19:18.756 1311-1311/com.android.systemui W/ResourceType﹕ No package identifier when getting value for resource number 0x00000000
10-09 01:19:18.756 1311-1311/com.android.systemui W/PackageManager﹕ Failure retrieving resources for com.example.checkboxsharedpreferences: Resource ID #0x0
10-09 01:19:18.781 1311-1327/com.android.systemui I/art﹕ Background sticky concurrent mark sweep GC freed 10643(410KB) AllocSpace objects, 0(0B) LOS objects, 0% free, 22MB/22MB, paused 5.699ms total 16.577ms
10-09 01:19:19.371 931-931/? W/SurfaceFlinger﹕ couldn't log to binary event log: overflow.
Anyone knows what's wrong with my coding? Hereby attached is my MainActivity.java:
ListView myList;
Button getChoice, clearAll, selectAll;
SharedPreferences sharedpreferences;
public static final String MyPREFERENCES = "MyUserChoice" ;
ArrayList<String> selectedItems = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myList = (ListView)findViewById(android.R.id.list);
getChoice = (Button)findViewById(R.id.getchoice);
clearAll = (Button)findViewById(R.id.clearall);
selectAll = (Button)findViewById(R.id.selectall);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice);
myList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
myList.setAdapter(adapter);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
if(sharedpreferences.contains(MyPREFERENCES)){
LoadSelections();
}
getChoice.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
String selected = "";
int cntChoice = myList.getCount();
SparseBooleanArray sparseBooleanArray = myList.getCheckedItemPositions();
for (int i = 0; i < cntChoice; i++) {
if (sparseBooleanArray.get(i)) {
selected += myList.getItemAtPosition(i).toString() + "\n";
System.out.println("Checking list while adding:" + myList.getItemAtPosition(i).toString());
SaveSelections();
}
}
Toast.makeText(MainActivity.this, selected, Toast.LENGTH_LONG).show();
}
});
clearAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ClearSelections();
}
});
selectAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SelectAllSelections();
}
});
packageManager = getPackageManager();
new LoadApplications().execute();
}
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);
Toast.makeText(getApplicationContext(),
"Current Item: " + currentItem,
Toast.LENGTH_LONG).show();
} 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();
}
private void SelectAllSelections() {
// 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, true);
}
// also clear the saved selections then uncomment the below line.
// SaveSelections();
}
protected void onListItemClick(ListView l, View v, int position, long id){
super.onListItemClick(l, v, position, id);
ApplicationInfo app = applist.get(position);
try{
Intent intent = packageManager.getLaunchIntentForPackage(app.packageName);
/*if(intent != null){
startActivity(intent);
}*/
}catch(ActivityNotFoundException e){
Toast.makeText(MainActivity.this,e.getMessage(), Toast.LENGTH_LONG).show();
}catch(Exception e){
Toast.makeText(MainActivity.this,e.getMessage(), Toast.LENGTH_LONG).show();
}
}
private List<ApplicationInfo> checkForLaunchIntent(List<ApplicationInfo> list){
ArrayList<ApplicationInfo> appList = new ArrayList<ApplicationInfo>();
for(ApplicationInfo info : list){
try{
if(packageManager.getLaunchIntentForPackage(info.packageName)!=null){
appList.add(info);
}
}catch(Exception e){
e.printStackTrace();
}
}
return appList;
}
private class LoadApplications extends AsyncTask<Void, Void, Void>{
private ProgressDialog progress = null;
protected Void doInBackground(Void... params){
applist = checkForLaunchIntent(packageManager.getInstalledApplications(PackageManager.GET_META_DATA));
listadapter = new AppAdapter(MainActivity.this, R.layout.activity_list_app, applist);
return null;
}
protected void onPostExecute(Void result){
setListAdapter(listadapter);
progress.dismiss();
super.onPostExecute(result);
}
protected void onPreExecute(){
progress = ProgressDialog.show(MainActivity.this, null, "Loading apps info...");
super.onPreExecute();
}
}
}
Change MyPREFERENCES.toString() to MyPREFERENCES.It is already String.No need to use .toString();
SharedPreferences.Editor prefEditor = sharedpreferences.edit();
String savedItems = getSavedItems();
prefEditor.putString(MyPREFERENCES, savedItems);
prefEditor.commit();
Retrieving data from SharedPreferences:
SharedPreferences sharedpreferences= getSharedPreferences(PREF_NAME, MODE_PRIVATE);
String channel = sharedpreferences.getString(MyPREFERENCES, "null");
this
sharedpreferences.contains(MyPREFERENCES.toString())
isn't returning something usefull.
replace it with that
!sharedpreferences.getString(MyPREFERENCES, "").equals("")

Categories

Resources