how to apply the url encoder for the usersName in android - android

Hi in the below code output of usersName is [user3, user1, user2] in this output after , symbol it's giving space.
For that How to apply the urlencoder for usersName.
Final output I want like this usersName=[user3,user1,user2]
java
public String CreateGroup(String groupname,String username,
ArrayList<FriendInfo> result) throws UnsupportedEncodingException {
List<String> usersName = new ArrayList<String>();
for (int i = 0; i < result.size(); i++) {
usersName.add(result.get(i).userName);
}
String params = "groupname="+ URLEncoder.encode(groupname,"UTF-8") +
"&username="+ URLEncoder.encode(this.username,"UTF-8") +
"&password="+ URLEncoder.encode(this.password,"UTF-8") +
"&friendUserName=" +usersName+
"&action=" + URLEncoder.encode("CreateGroup","UTF-8")+
"&";
Log.i("PARAMS", params);
return socketOperator.sendHttpRequest(params);
}

Since you're passing arguments through http you need to encode the spaces by replacing them with "+" or "%20".
Your for should look like this:
for (int i = 0; i < result.size(); i++) {
usersName.add(result.get(i).userName.replace(" ","+"));
}
If you remove the spaces like the other anwser sugested your usernames would have incorrect information like "JohnSmith" instead of "John Smith"
Finaly since you're using your list you should do this:
"&friendUserName=" +usersName.toString().replace(" ","+")

Try to change this:
usersName.add(result.get(i).userName);
to this:
usersName.add(result.get(i).userName.replaceAll("\\s",""));
This is under the assumption that your userName is the one that includes the whitespace and not the userNames List.

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
}

How to past an array of objects to server from android?

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.

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{
}
}
}

new line on comma within string

I have an EditText view which will allow the user to edit an address field. I want any text with a comma before it to be put on a new line so for example the following:
Some St., Some City, Some post code would be presented as:
Some St.,
Some City,
Some post code
Anyone know how I could do this?
Perhaps you could perform a String.replace() to replace all commas with ,\n
so,
String s = "Some St., Some City, Some post code"
s = s.replace(",",",\n");
You then might have to do something to remove the whitespace
Alternatively, to remove all whitespace:
String s = "Some St., Some City, Some post code";
String strings[] = s.split(",");
for(int i = 0; i < strings.length; i++){
strings[i] = strings[i].trim();
strings[i] += ",\n";
}
s = "";
for(int i = 0; i < strings.length; i++)
s += strings[i];

Categories

Resources