How to delete saved data from shared preferences in Android - android

Today, I would like to seek your help regarding an issue I have in my acitvity, I am putting three strings in shared preferences using StringTokenizer.Everything is fine, now I would like to remove each textview from parent view and as well as from shared preferences using its long click event .
Here is my code for your reference.
This is the place where I am storing the bitmap and other two string names in shared preferences
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
StringBuilder strCont = new StringBuilder();
screenOnePreferences = PreferenceManager.getDefaultSharedPreferences(AppsActivity.this);
String savedStringCont = screenOnePreferences.getString("appName1", "");
StringTokenizer stCont = new StringTokenizer(savedStringCont, ",");
String[] savedListCont = new String[stCont.countTokens()];
for (int j = 0; j < savedListCont.length; j++) {
savedListCont[j] =stCont.nextToken()+",";
strCont.append(savedListCont[j]);
}
StringBuilder str1 = new StringBuilder();
screenOnePreferences = PreferenceManager.getDefaultSharedPreferences(AppsActivity.this);
String savedString1 = screenOnePreferences.getString("appPackName1", "");
StringTokenizer st1 = new StringTokenizer(savedString1, ",");
String[] savedList1 = new String[st1.countTokens()];
for (int j = 0; j < savedList1.length; j++) {
savedList1[j] =st1.nextToken()+",";
str1.append(savedList1[j]);
}
StringBuilder strImg = new StringBuilder();
screenOnePreferences = PreferenceManager.getDefaultSharedPreferences(AppsActivity.this);
String savedImage = screenOnePreferences.getString("appImage1", "");
StringTokenizer stimg = new StringTokenizer(savedImage, ",");
String[] savedListImg = new String[stimg.countTokens()];
for (int j = 0; j < savedListImg.length; j++) {
savedListImg[j] =stimg.nextToken()+",";
strImg.append(savedListImg[j]);
}
strCont.append(clickedAppName);
str1.append(clickedApp);
strImg.append(Base64.encodeToString(b, Base64.DEFAULT));
PreferenceManager.getDefaultSharedPreferences(AppsActivity.this).edit().putString("appName1",strCont.toString()).commit();
PreferenceManager.getDefaultSharedPreferences(AppsActivity.this).edit().putString("appPackName1",str1.toString()).commit();
PreferenceManager.getDefaultSharedPreferences(AppsActivity.this).edit().putString("appImage1",strImg.toString()).commit();
This is the place where I am retrieving the same and binding to dynamic textviews.
String[] array;
static SharedPreferences prefsCont;
static String[] savedList2;
static List<String> list;
static StringBuilder strCont;
static String savedStringCont;
static String savedString2;
static String savedStringImg;
static StringTokenizer stCont;
static StringTokenizer st2;
static StringTokenizer stImage;
static String[] savedListCont;
static String[] savedListImage;
static List<String> numberList;
static Bitmap yourSelectedImage;
static int numOfContacts;
strCont = new StringBuilder();
prefsCont = PreferenceManager.getDefaultSharedPreferences(context);
savedStringCont = prefsCont.getString("appName1", "");
savedString2 = prefsCont.getString("appPackName1", "") ;
savedStringImg = prefsCont.getString("appImage1", "");
stCont = new StringTokenizer(savedStringCont, ",");
st2 = new StringTokenizer(savedString2, ",");
stImage = new StringTokenizer(savedStringImg, ",");
savedListCont = new String[stCont.countTokens()];
savedListImage = new String[stImage.countTokens()];
savedList2 = new String[st2.countTokens()];
numberList = Arrays.asList(stCont.toString().split(","));
int prevTextViewId = 0;
numOfContacts = stCont.countTokens();
for ( int K = 0; K < numOfContacts; K++) {
final int listenerI = K;
savedListCont[K] = stCont.nextToken();
savedList2[K] = st2.nextToken();
savedListImage[K] = stImage.nextToken();
byte[] b = Base64.decode(savedListImage[K], Base64.DEFAULT);
InputStream is = new ByteArrayInputStream(b);
yourSelectedImage = BitmapFactory.decodeStream(is);
BitmapDrawable bd = new BitmapDrawable(context.getResources(), yourSelectedImage);
for(int i = 0; i < 1; i++)
{
if(savedListCont[K] != null && savedList2[listenerI] != null && yourSelectedImage != null ){
final TextView textView = new TextView(context);
textView.setText(savedListCont[K]);
textView.setCompoundDrawablesRelativeWithIntrinsicBounds(null, bd, null, null);
textView.setPadding(0, 20, 0, 20);
textView.setTextColor(Color.WHITE);
textView.setMaxLines(1);
textView.setEllipsize(TextUtils.TruncateAt.MIDDLE);
int curTextViewId = prevTextViewId + 1;
textView.setId(curTextViewId);
final RelativeLayout.LayoutParams params =
new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.BELOW, prevTextViewId);
textView.setLayoutParams(params);
textView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// Here I would like to delete individual textview from shared preferences.
return false;
}
});
prevTextViewId = curTextViewId;
ll.addView(textView, params);

use this it help you ................
keyname is value which you want to delete........
prefsCont.edit().remove("KeyName").commit();
in your case example :-prefsCont.edit().remove("appName1").commit();
and if you want to delete all then use this prefsCont.edit().clear().commit();
use this to find out value which is you clicked ....
array = ArrayUtils.removeElement(array, "your textview value");
and use this to put array into the SharePrefernce
Set<String> set = new HashSet<String>();
set.addAll(listOfExistingScores);
prefsCont.putStringSet("key", set).commit();
enjoy coding ...............

To remove specific values use below
--> SharedPreferences.Editor.remove() followed by a commit()
To remove all data then use below
--> SharedPreferences.Editor.clear() followed by a commit()

you can use,
SharedPreferences preferences = getSharedPreferences("Mypref", 0);
if you want to remove particular value from shared preferences use below,
preferences.edit().remove("key").commit();
if you want to remove all data,
preferences.edit().clear().commit();

Related

when i try to get the unicode of emoji, why i got some unicode like de01, de02, de03?

img description: first one was textview to get unicode; second one was textview to restore emoji; last one was edittext to input text or emoji
and post my code below
String s = emojiconEditText.getText().toString();
StringBuilder stringBuilder = new StringBuilder();
StringBuilder stringBuilder1 = new StringBuilder();
private void testTwo(String s, StringBuilder stringBuilder, StringBuilder stringBuilder1, TextView emojiconText, TextView emojiconText2) {
int codePointCount = s.codePointCount(0, s.length() - 1);
for (int i = 0; i <codePointCount ; i++) {
int letterCodePoint = s.codePointAt(i);
int type = Character.getType(letterCodePoint);
if (type==Character.SURROGATE||type==Character.OTHER_SYMBOL){
stringBuilder.append("[emoji]U+"+Integer.toHexString(letterCodePoint)+"[emoji]");
}else{
stringBuilder.append(s.charAt(i));
}
}
String text = stringBuilder.toString();
emojiconText.setText(text);
String[] emojis = text.split("\\[emoji\\]");
for (int i = 0; i <emojis.length ; i++) {
if (emojis[i].contains("U+")){
// String[] subSplit = emojis[i].split("[/emoji]");
// int deccode = Integer.parseInt(subSplit[0], 16);
String substring = emojis[i].substring(2, emojis[i].length() );
int deccode = Integer.parseInt(
substring, 16);
/* stringBuilder1.append("\\u");
stringBuilder1.append( deccode);*/
stringBuilder1.append(new String(Character.toChars(deccode))+" ");
}else{
stringBuilder1.append(emojis[i]);
}
}
emojiconText2.setText(stringBuilder1.toString());
}

Save and Load Int Arrays

I want to save two Int Arrays to a File, so i can load the Int Arrays back in my App after it got closed.
My two Arrays are:
LvlDone[currentLevel - 1] = 1;
LvlBest[currentLevel - 1] = turnCounter;
You can try to save the int array in the shared preferences (by converting them into a string):
Put your integers into a string, delimiting every int by a character and then save them as a string:
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
StringBuilder str = new StringBuilder();
for (int i = 0; i < LvlDone.length; i++) {
str.append(LvlDone[i]).append(",");
}
prefs.edit().putString("string", str.toString());
Get the string and parse it using StringTokenizer:
String savedString = prefs.getString("string", "");
StringTokenizer st = new StringTokenizer(savedString, ",");
for (int i = 0; i < 10; i++) {
LvlDone[i] = Integer.parseInt(st.nextToken());
}

converting from a string separated by commas to an array

I have been working on saving 4 String arrays to sharedpreference. Currently I am breaking the array down in to a string separating the pieces by a comma. When I go to the string, it does save the pieces accurately as it should; however, when I "load" the data and convert it back to an array, it's coming up empty (not null). I am unable to determine how I should fix this to pull my array back. Below is my Activity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.debtlist);
String[] debtName = new String[10];
String[] debtAmount = new String[10];
String[] debtRate = new String[10];
String[] debtPayment = new String[10];
int counter = 0;
SharedPreferences sharedPref= getSharedPreferences("chaosdatasnowball", 0);
String tempDebtNames = sharedPref.getString("debtNames", "");
debtName = convertStringToArray(tempDebtNames);
Bundle extras = getIntent().getExtras();
int trigger = 0;
for (int i=0;i<counter || i==counter;i++)
{
if (debtName[i] == null && extras != null && trigger == 0)
{
debtName[i] = extras.getString("debtName");
debtAmount[i] = extras.getString("debtAmount");
debtRate[i] = extras.getString("debtRate");
debtPayment[i] = extras.getString("debtPayment");
trigger = 1;
counter++ ;
}
}
TableLayout tl = (TableLayout) findViewById(R.id.debtListTableView);
for (int i=0;i<counter || i==counter;i++)
{
if (debtName[i] != null)
{
TableRow tr = new TableRow(this);
TextView tv0 = new TextView(this);
TextView tv1 = new TextView(this);
TextView tv2 = new TextView(this);
TextView tv3 = new TextView(this);
TableRow.LayoutParams trlp = new TableRow.LayoutParams();
tv0.setLayoutParams(new LayoutParams(0, LayoutParams.MATCH_PARENT, 0.25f));
tv1.setLayoutParams(new LayoutParams(0, LayoutParams.MATCH_PARENT, 0.25f));
tv2.setLayoutParams(new LayoutParams(0, LayoutParams.MATCH_PARENT, 0.25f));
tv3.setLayoutParams(new LayoutParams(0, LayoutParams.MATCH_PARENT, 0.25f));
trlp.span = 3;
tr.setLayoutParams(trlp);
tv0.setText("" + debtName[i]);
tv1.setText("" + debtAmount[i]);
tv2.setText("" + debtPayment[i]);
tv3.setText("" + i);
tr.addView(tv0);
tr.addView(tv1);
tr.addView(tv2);
tr.addView(tv3);
tl.addView(tr);
}
}
SharedPreferences.Editor editor= sharedPref.edit();
String debtNames = convertArrayToString(debtName, counter);
editor.putString("debtNames", debtNames).commit();
TextView disp = (TextView) findViewById(R.id.dispAdditionalAmount);
disp.setText("" + debtNames); //This is how I confirm that the convertArrayToString is functioning properly
}
public static String convertArrayToString(String[] array, int stop){
String str = "";
for (int i = 0;i<stop; i++) {
str = str+array[i];
// Do not append comma at the end of last element
if(i<stop-1){
str = str+",";
}
}
return str;
}
public static String[] convertStringToArray(String str){
String[] arr = str.split(",");
return arr;
}
You do:
String tempDebtNames = sharedPref.getString("debtNames", "");
debtName = convertStringToArray(tempDebtNames);
It is possible that "debtNames" key does not exist. (It returns "" in this case).
Think about first time the app is run. The key will not exist. Therefore, you should convertStringToArray only if !tempDebtNames.equals(""). If key doesn't exist then proceed with empty values..

how to get value from sharedpreferences and save it arraylist

how to get value from shared preferences and save it array list
I want to get the string from shared preferences so that i want save that string to array list
SharedPreferences keyValues = context.getSharedPreferences("name_icons_list", context.MODE_PRIVATE);
if(keyValues.getString(""+str,"").equals("true"))
{
holder.tb1.setChecked(true);
onApps.add(str);
System.out.println("Block appp+++++"+onApps);
System.out.println("******************************************");
System.out.println("data retrive from database"+ position);
System.out.println("******************************************");
}
You may use this code to save preference in arraylist and vice versa
public String[] getApplicationList() { Log.i("test","prefrence getapplist");
return mApplicationList;
}
public void saveApplicationList(String[] applicationList) { Log.i("test","prefrence saveapplist");
mApplicationList = applicationList;
String combined = "";
for (int i=0; i<mApplicationList.length; i++){
combined = combined + mApplicationList[i] + ";";
}
mPref.edit().putString(PREF_APPLICATION_LIST, combined).commit();
}
I believe this should do the trick:
String savedString = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE)
.getString("name_icons_list", "");
StringTokenizer st = new StringTokenizer(savedString, ",");
int numberOfToken = st.countTokens();
ArrayList<String> arraylist = new ArrayList<String>();
for (int i = 0; i < numberOfToken; i++) {
arraylist.add(st.nextToken());
}

How do you loop through view id's?

For my android app I need to make an array of View ID's.
The array will hold 81 values so it's quite lengthy to add them one by one.
This is how it looks now:
cells[0] = R.id.Square00;
cells[1] = R.id.Square01;
cells[2] = R.id.Square02;
cells[3] = R.id.Square03;
cells[4] = R.id.Square04;
cells[5] = R.id.Square05;
//All the way to 80.
Is there a shorter/more efficient way of doing this?
Thankfully, there is. Use getIdentifier():
Resources r = getResources();
String name = getPackageName();
int[] cells = new int[81];
for(int i = 0; i < 81; i++) {
if(i < 10)
cells[i] = r.getIdentifier("Squares0" + i, "id", name);
else
cells[i] = r.getIdentifier("Squares" + i, "id", name);
}
Sam's answer is better but i think i should share an alternative
int [] ids = new int [] {R.id.btn1, R.id.btn2, ...};
Button [] arrayButton = new Button[ids.length];
for(int i=0 ; i < arrayButton.length ; i++)
{
arrayButton[i] = (Button) findViewById(ids[i]);
}
Modified form of Sam Answer
No need of if else use Integer String Formating
Resources r = getResources();
String name = getPackageName();
int[] resIDs = new int[81];
for(int i = 0; i < 81; i++)
{
resIDs[i] = r.getIdentifier("Squares0" + String.format("%03d", i), "id", name);
}

Categories

Resources