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
Related
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
}
I am trying to send an array with a bunch of objects back to android?
I tried String Builder like so:
StringBuilder sb = new StringBuilder();
sb.append("[");
for(int i = 0; i <usersChanged.size(); i++) {
DatabaseUser userChange = usersChanged.get(i);
if(userChange.getIsFollowingType() == 0) {
String userIdStr = "{userId:" + userChange.getUserId() + ",";
String followingStr = "following:" + String.valueOf(userChange.getIsFollowingType())+ "}]";
sb.append(userIdStr).append(followingStr);
but I am doing something wrong here. On my server side I am using node.js and would parse the array if I send over a string no problem, but this is not sending a string version of the array? What do I need to change on my string builder? Or is there a more efficient way to send over the list of usersChanged - (which is List)
I am using retrofit if there is a way to do it easy with that.
Your code will send things like
[{userId: someuserid, following: someparameter}]
You need to have the double quote (" ") sent over as well.
for(int i = 0; i <usersChanged.size(); i++) {
DatabaseUser userChange = usersChanged.get(i);
if(userChange.getIsFollowingType() == 0) {
String userIdStr = "{\"userId\":\"" + userChange.getUserId() + "\",";
String followingStr = "\"following\":\"" + String.valueOf(userChange.getIsFollowingType())+ "\"}]";
sb.append(userIdStr).append(followingStr);
You should also probably move the "]" to after the loop.
EDIT:
Forgot to mention this, but you can definitely use JSONArray and JSONObject to make your life easier.
JSONArray jsonArray = new JSONArray();
for(...){
JSONObject jsonObject = new JSONObject();
jsonObject.put("userId", userChange.getUserId());
jsonObject.put("following", String.valueOf(userChange.getIsFollowingType()));
jsonArray.put(jsonObject);
}
Then send over the jsonArray.
in the code example below would converting the function to use StringBuilder make it more efficient and be worth it? and
how to convert the convertStringToInputString function to use StringBuilder? StringBuilder does not have a replace method.
// converts String to type of String that can be inserted into database, no space, no eof characters
public String convertStringToInputString(String standardString){
String str = standardString.replace(" ", "XspaceX");
String str2 = str.replace("\n", "XendoflineX");
return str2;
}
// fills table with information to be put into JSON String object
public void fillTable(){
initialField.a[0] = convertStringToInputString("");
initialField.a[1] = convertStringToInputString("");
initialField.a[2] = convertStringToInputString("");
initialField.a[3] = convertStringToInputString("");
initialField.a[4] = convertStringToInputString("");
initialField.a[5] = convertStringToInputString("");
initialField.a[6] = convertStringToInputString("");
initialField.a[7] = convertStringToInputString("");
initialField.a[8] = convertStringToInputString("");
initialField.a[9] = convertStringToInputString("");
// continue with more 120 more lines like this
Why not just inline your string manipulations? I think it improves readability and avoids creating unnecessary functions and objects.
initialField.a[0] = string.replace(" ","space").replace("\n","newline");
you can use
StringBuilder.replace(int start, int end, String str)
here
start - The beginning index, inclusive.
end - The ending index, exclusive.
str - String that will replace previous contents.
So you can use StringBuilder.indexOf method to find the index then use the above method to replace it.
I don't understand what you are doing, but you could use stringbuilder's append method like so:
public String toString(whateverType initialField) {
StringBuilder sB = new StringBuilder();
for (int i = 0; i<initialField.length; i++) {
sB.append(initialField[i];
}
String str2 = sB.toString();
return str2;
}
As a result of the two for-loops below I should get the word an Album name, but I get this name in reverse order. For example if I expect "LINK", I get "KNIL"... Where am I going wrong?
Here is the code:
jsonobj = new JSONObject(param);
JSONObject datajson = jsonobj.getJSONObject("data");
JSONArray news = datajson.getJSONArray(TAG_NEWS);
JSONArray actual = datajson.getJSONArray("actual");
for(int i = 0; i < news.length(); i++){
JSONObject c = news.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String title = c.getString(TAG_TITLE);
String album = c.getString(TAG_ALBUM);
TextView tv = (TextView) findViewById(R.id.imgtest);
//tv.setText(album);
if(!(album == "null")){
String var[] = album.split("|");
for(int a=0;a<var.length;a++){
String t = var[a].intern();
String al = ((TextView) findViewById(R.id.imgtest)).getText().toString();
String b = t+al;
tv.setText(b);
}
}else{
break;
}
}
This line is adding the newest letter t to the beginning of your existing String al:
String b = t+al;
However rather than simply switching this line around (b = al + t), I recommend a faster method:
String album = c.getString(TAG_ALBUM).replaceAll("|", "");
TextView tv = (TextView) findViewById(R.id.imgtest);
tv.setText(album);
I looks like you only wanted to remove the "|" character from your album String, so just use String.replaceAll().
If you need album split into an array, then when you rebuild the String don't waste your time calling findViewById() on a view that you already have. In fact you already have the String, so there is no need to use getText() either:
String var[] = album.split("|");
StringBuilder builder = new StringBuilder();
for(int a=0;a<var.length;a++)
builder.append(a);
// use builder.toString() when you want the cleaned album name.
To add the latest letter t to the end of the current string al:
b = al + t
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.