How to store the values dynamically in string in java android? - 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.

Related

Handle comma separated string

Creating an app in which i want to get string from json but i have one key and multiple value so i don't know how to handle this.
"colours": "#fff600,#000000,#ffffff,#00000,#ff9900,#333333"
And want to use this color in different class:
final ValueAnimator colorAnimation = ValueAnimator.ofObject(new android.animation.ArgbEvaluator(), Color.RED, Color.BLUE,Color.WHITE,Color.YELLOW,Color.CYAN,Color.MAGENTA,Color.GREEN,Color.GRAY);
colorAnimation.setDuration(1400);
Put the value of colours in string variable and then split the string in following way and add it to an arraylist :
String[] arr = str.split(",");
ArrayList<String> arr1 = new ArrayList<String>();
for (int i=0; i<arr.length; i++){
arr1.add(arr[i]);
}
Get value of color and use string tokenizer with ',' delima like this:
StringTokenizer stringTokenizer = new StringTokenizer(colorValueString, ",");
Also it has stringTokenizer.nextToken to get the next color in string
You can get the value of colours as a string and then split the string into parts like this:
String colours = json.getString("colours");
Log.d(TAG, colours);
String items[] = colours.split(",");
for (String item : items) {
Log.d(TAG, item);
}
If you own the json
You should use JSONArray:
"colours": ["#fff600","#000000","#ffffff","#00000","#ff9900","#333333"]
And read it like
JSONObject json = ...;
JSONArray colorsArray = json.getJSONArray("colours");
for(int i = 0; i < colorsArray.length(); i++) {
String colorString = colorsArray.getString(i);
int color = Color.parseColor(colorString);
// you should probably also catch IllegalArgumentException for wrong input
}
If you don't own the json
You can read it as string and split around commas:
JSONObject json = ...;
String colorsString = json.getString("colours");
String[] colorStrings = colorsString.split(",");
for(String string : colorStrings) {
int color = Color.parseColor(string);
// you should probably also catch IllegalArgumentException for wrong input
}

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 save an array of strings with SharedPreferences?

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*"));

Extract array elements and create a String from them

I have got an array through Vector addittion like
[1!,2!,3!,4!]
I have to convert it into a string like
{1!2!3!4!}
..can you please tell me the name of few methods by which i can make it? Thanks all..
String getElement = null;
for(int j = 0;j<5;j++){
getElement = dynamicViewtagNames.elementAt(j);
}
I can get elements of this array like this..then I have to convert it into a string.
I'm not sure if I understand your question correctly, but if you just want to turn this:
[1!,2!,3!,4!]
into
{1!2!3!4!}
you can for example make use of the String.replace() or String.replaceAll() method.
String str = "[1!,2!,3!,4!]";
str = str.replace("[", "{");
str = str.replace("]", "}");
str = str.replace(",", "");
If [1!,2!,3!,4!] is a Vector containing the Strings you showed us above, you could do it like this using a StringBuffer:
// letz assume this vector has the following content: [1!,2!,3!,4!]
Vector<String> dynamicViewtagNames = new Vector<String>();
StringBuffer b = new StringBuffer();
b.append("{");
for(int i = 0; i < dynamicViewtagNames.size(); i++) {
b.append(dynamicViewtagNames.get(i))
}
b.append("}");
String mystring = b.toString();
Simple Solution
String names = names.replaceAll(",","");
names = names.replaceAll("[", "{");
names = names.replaceAll("]", "}");
Use this code,
StringBuilder str = new StringBuilder();
for (int i = 0; i<dynamicViewtagNames.length;i++){
str.append(dynamicViewtagNames[i])
}
str.toString();
or you can use:
Arrays.toString(dynamicViewtagNames);
Thanks

Array index out of bounds exception android

I am trying to get the data from database table via php file and displaying it in android. In php file I seperated each column with "#".
So now I am getting values like 4#2012-11-06#test1#test2. But for some columns there is not data. So the values are comng like 5###.
Here when I splitting with # and displaying the data it is throwing out of bounds exception. How can I resolve this issue?
Code:
String st="1#2012-10-30#test1#2#2012-10-30#test2#3#2012-11-06#test3#9##test1#21###22###23###";
String[] val = st.trim().split("#");
for (int i = 0; i < val.length; i++)
{
String str = val[i];
String arr[] = str.split("#");
System.out.println("arr0" + arr[0]);
System.out.println("arr1" + arr[1]);
System.out.println("arr2" + arr[2]);
}
try as using Pattern.compile to split your current string :
String your_string = "4#2012-11-06#test1#test2";
Pattern pattern = Pattern.compile("#");
String[] strarray =pattern.split(your_string);
for Handling if array index contain empty string change your code as:
for (int i = 0; i < val.length; i++)
{
String your_string =val[i];
Pattern pattern = Pattern.compile("#");
String[] strarray =pattern.split(your_string);
for(int j=0;j<strarray.length;j++){
if(strarray[j].trim().length() >0){
System.out.println("arr"+j+"::" + strarray[j]);
}
else{
}
}
}

Categories

Resources