How to save an array of strings with SharedPreferences? - android

I have an array of Strings, I need to save this array with SharedPreferences, and then read and display them on a ListView.
For now, I use this algorithm:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
//To save the strings
public void saveStrings(String[] str){
int a = 0;
int lenght = str.length;
while (a<lenght){
sp.edit().putString(Integer.toString(a), Integer.toString(str[a])).apply();
a=a+1;
}
}
//To read the strings
public String[] getStrings(){
String[] str = new String [8];
int a = 0;
int lenght = 8; //To read 8 strings
while (a<lenght){
str[a] = sp.getString(Integer.toString(a),"Null");
a=a+1;
}
return str;
}
Is there a way to save and read the entire array, rather than a string at a time?
For this project I'm using API level 19 (Android 4.4.2 KitKat)

Well, you could use putStringSet(), but (a) it's only from API level 11 onwards, and (b) as its name says, it's for sets (which means that you will lose the original ordering and any duplicates present in the array).
We solved this problem by "encoding" collections into a string and using putString() and decoding them afterwards on getString(), with this pair of methods (for ArrayList, but should be easily convertible into array versions):
public String encodeStringList(List<String> list, char separator)
{
StringBuilder sb = new StringBuilder(list.size() * 50);
for (String item : list)
{
if (sb.length() != 0)
sb.append(separator);
// Escape the separator character.
sb.append(item.replace(Character.toString(separator), "\\" + separator));
}
return sb.toString();
}
public List<String> decodeStringList(String encoded, char separator)
{
ArrayList<String> items = new ArrayList<String>();
if (encoded != null && encoded.length() != 0)
{
// Use negative look-behind with backslash, because it's used for escaping the separator.
// Expression is "(?<!\)s" with doubling because of escaping in regex, and again because of escaping in Java).
String splitter = "(?<!\\\\)" + separator; //$NON-NLS-1$
String[] parts = encoded.split(splitter);
// While converting to list, take out the escape characters used to escape the now-removed separator.
for (int i = 0; i < parts.length; i++)
items.add(parts[i].replace("\\" + separator, Character.toString(separator)));
}
return items;
}

Set<String> set =list.getStringSet("key", null);
Set<String> set = new HashSet<String>();
set.addAll(list of the string list u have);
editor.putStringSet("key", set);
editor.commit();
Please refer to this thread for further details Save ArrayList to SharedPreferences

//while storing
str is string array
String fin="";
for(i=0;i<n;i++){
fin=fin+str[i]+",";
}
fin=fin.substring(0,fin.length()-1);
//while retrieving
List<String> items = Arrays.asList(fin.split("\\s*,\\s*"));

Related

Reomve special character from Arraylist

I am trying to remove special character from arraylist.
Not getting click how to do this?
I have 3 editfield and filling text after certain conditions
means when 1 is filled then another can be filled. now when i click to save this. this returns an array like [hello,abc,zbz] for fields
private List<String> hashtagData;
hashtagData = new ArrayList<String>();
String status_message = status.getText().toString();
String status_message2 = status2.getText().toString();
String status_message3 = status3.getText().toString();
hashtagData.add(status_message);
hashtagData.add(status_message2);
hashtagData.add(status_message3);
But I am trying to remove "[]".
Thank you if anybody can help.
Here try this:
ArrayList<String> strCol = new ArrayList<String>();
strCol.add("[a,b,c,d,e]");
strCol.add(".a.a.b");
strCol.add("1,2,].3]");
for (String string : strCol) {
System.out.println(removeCharacter(string));
}
private String removeCharacter(String word) {
String[] specialCharacters = { "[", "}" ,"]",",","."};
StringBuilder sb = new StringBuilder(word);
for (int i = 0;i < sb.toString().length() - 1;i++){
for (String specialChar : specialCharacters) {
if (sb.toString().contains(specialChar)) {
int index = sb.indexOf(specialChar);
sb.deleteCharAt(index);
}
}
}
return sb.toString();
}
Create regex which matches with your criteria, then loop through your list.
String myRegex = "[^a-zA-Z0-9]";
int index = 0;
for (String your_string : list)
list.set(index++, s.replaceAll(myRegex, ""));
can use below function to remove special character from string using regular expressions.
using System.Text;
using System.Text.RegularExpressions;
public string RemoveSpecialCharacters(string str)
{
return Regex.Replace(str, "[^a-zA-Z0-9_.]+", "", RegexOptions.Compiled);
}

How to convert a string to character by character in Android?

I have Edittext field that the user can enter their name. I want to check it with alphabets for how many times a letter comes.
Which is the best way to do this?
I tried the below code for getting each character from the string but error occurring? I appreciate it if any one can help.
name=(EditText)findViewById(gami.Numerology.R.id.inputUI);
String a=name.getText().toString();
for ( int i = 0; i < a.length(); i++ )
{
c = a.charAt(i);
if (c=='s')
{
s=1; //like this for all characters
}
}
I just put this in a click event of button.
//declare the original String object
String strOrig = "Hello World";
//declare the char array
char[] stringArray;
//convert string into array using toCharArray() method of string class
stringArray = strOrig.toCharArray();
//display the array
for(int index=0; index < stringArray.length; index++)
//check of character appearance
You can use a hashmap or some sort of dictionary in Java.
Rough example since I don't know how to use Hashmap in Java:
HashMap<Character, Integer> counter = new HashMap<Character, Integer>();
for (Character c: name)
{
counter.put(c, counter.get(c) == null ? 1 : counter.get(c)++);
}

How to convert string into boolean array?

I convert everything in my Android app into string and add it to a Sqlite database. I use the code below to convert boolean arrays into string, but I dont know how to convert it back from string into boolean array. There spaces between each true and false in the string. How can I break string at each space into a boolean array?
String work= "";
for (int i = 0;i<go.length; i++) {
work= work+go[i];
// Do not append comma at the end of last element
if(i<go.length - 1){
work = work+" ";
}
}
Split the string on your separator character (" ")
Create an array of booleans with the same length of the splitted array of strings
Parse one by one them using Boolean.parseBoolean method
Example:
public static void main(String[] args) {
String str = "true false true false false";
String[] parts = str.split(" ");
boolean[] array = new boolean[parts.length];
for (int i = 0; i < parts.length; i++)
array[i] = Boolean.parseBoolean(parts[i]);
System.out.println(Arrays.toString(array));
}
Outputs:
[true, false, true, false, false]
Please use boolean b = Boolean.parseBoolean(string);

JSON Array of strings (no objects), extracting data

I have a long JSON string representing a string[] array being returned from a WCF service. The array elements are simply strings, they are not objects. This is an example of the return data
["1|ArrayElement1","2|ArrayElement2","3|ArrayElement3"..."n|ArrayElementn"]
I don't mind the index being included in the string, but I need to parse the strings into an ArrayList in Android so that I can adapt it to a ListView.
Since these technically aren't JSONObjects, how can I iterate over them and extract the string from each array element?
this is a valid JSON array of strings, you can parse it normally like this
JSONArray jsonStrings = json.getJSONArray("items");
String strings[] = new String[jsonStrings.length()];
for(int i=0;i<strings.length;i++) {
strings[i] = jsonStrings.getString(i);
}
Maybe this post can help you out:
JSON Array iteration in Android/Java
HashMap<String, String> applicationSettings = new HashMap<String,String>();
for(int i = 0; i < settings.length(); i++){
String value = settings.getJSONObject(i).getString("value");
String name = settings.getJSONObject(i).getString("name");
applicationSettings.put(name, value);
}
JSONArray names= json.names();
JSONArray values = json.toJSONArray(names);
for(int i = 0 ; i < values.length(); i++){
if(names.getString(i).equals("description")){
setDescription(values.getString(i));
}
else if(names.getString(i).equals("expiryDate")){
String dateString = values.getString(i);
setExpiryDate(stringToDateHelper(dateString));
}
else if(names.getString(i).equals("id")){
setId(values.getLong(i));
}
else if(names.getString(i).equals("offerCode")){
setOfferCode(values.getString(i));
}
else if(names.getString(i).equals("startDate")){
String dateString = values.getString(i);
setStartDate(stringToDateHelper(dateString));
}
else if(names.getString(i).equals("title")){
setTitle(values.getString(i));
}
}
Just to clarify, as I understand it you are receiving a JSON array of strings which are strings of valid JSON prefixed with the array index and a pipe character?
First, I would suggest contacting the creator of this abomination and lecturing them on violating standards. If they won't listen, talk to their bosses. This kind of thing is unacceptable in my opinion and needs to stop.
Second, I'd suggest doing something like this:
string[] element_strings = JSON.deserialize(WCF_string_result);
object[] elements = new object[element_strings.length];
for(int x = 0; x < elements.length; x++)
{
int pipeIndex = element_strings.indexOf("|");
elements[x] = JSON.deserialize(element_strings[x].substr(pipeIndex + 1));
}
Of course this assumes you have some kind of method for deserializing strings of JSON objects. If you don't I'd recommend using the built in library available in Android:
http://developer.android.com/reference/org/json/package-summary.html
If you want to extract specific value from it using Java8 stream on JSONArray. Then this code will help.
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.json.JSONArray;
public class JsonArrayTest {
public static void main(String[] args) {
System.out.println("Output - "+ getValue("[{\"id\":\"11\",\"username\":\"ABC\"},{\"id\":\"12\",\"username\":\"ABC\"}]\""));
System.out.println("Output - "+ getValue("[{\"id\":\"13\",\"username\":\"XYZ\"}]\""));
}
private static String getValue(String input) {
JSONArray jsonArray = new JSONArray(input);
return IntStream
.range(0, jsonArray.length()).mapToObj(obj -> jsonArray.getJSONObject(obj))
.filter(filterObj -> filterObj.getString("id") != null && "12".equals(filterObj.getString("id")))
.map(finalObj -> finalObj.getString("username")).collect(Collectors.joining(""));
}
}
Note: This is just an example how can you extract a specific value from JSONArry using stream APIs. You can change the filter condition or drop it according to your requirement.

How to store the values dynamically in string in java android?

In my project I need to store the values dynamically in a string and need to split that string with ",". How can I do that ? Please help me..
My Code:
static ArrayList<ArrayList<String>> listhere;
ArrayList<String> arropids;
String arropids1;
for(int q=0;q<listhere.size();q++)
{
arropids = listhere.get(q);
if(arropids.get(3).equals("1"))
{
arropids1 += arropids.get(0) + ",";
System.out.println("arropids1"+arropids1);
}
}
You must be getting NullPointerException as you havent initialized the String, initialize it as
String arropids1="";
It will resolve your issue, but I dont Recommend String for this task, as String is Immutable type, you can use StringBuffer for this purpose, so I recommend following code:
static ArrayList<ArrayList<String>> listhere;
ArrayList<String> arropids;
StringBuffer buffer=new StringBuffer();
for(int q=0;q<listhere.size();q++)
{
arropids = listhere.get(q);
if(arropids.get(3).equals("1"))
{
buffer.append(arropids.get(0));
buffer.append(",");
System.out.println("arropids1"+arropids1);
}
}
and finally get String from that buffer by:
String arropids1=buffer.toString();
In order to split the results after storing your parse in the for loop, you use the split method on your stored string and set that equal to a string array like this:
static ArrayList<ArrayList<String>> listhere;
ArrayList<String> arropids;
String arropids1 = "";
for(int q=0;q<listhere.size();q++) {
arropids = listhere.get(q);
if(arropids.get(3).equals("1"))
{
arropids1 += arropids.get(0) + ",";
System.out.println("arropids1"+arropids1);
}
}
String[] results = arropids1.split(",");
for (int i =0; i < results.length; i++) {
System.out.println(results[i]);
}
I hope that this is what you're looking for.

Categories

Resources