Android : Split string with { character - android

I have an string
String name = "\"edge_followed_by\":{\"count\":46199005},\"followed_by_viewer\":false,"
I want only this 46199005.
But { shows an error, when try to split the string
String[] separated = name.split("edge_followed_by\":{\"count\":");
Showing a suggestion , number expected and want me to replace with *.
Can anyone help me in this.

Just replace { with \{.
split is trying to use it as a part of regular expression.

Ideally, you should use JSON to parse this if you have proper structure. but if you want to get only the number you can split it using ":" and then split using "}". it should give you the exact number.

Why not to use:
String[] separated = name.split(":");
separated[2].split("}")[0];

Your string is not exact JSON object otherwise you can simply do json parsing and get the count value.
You can get count value using subtring operations like below:
String name = "\"edge_followed_by\":{\"count\":46199005},\"followed_by_viewer\":false,";
String substr = name.substring(name.indexOf("\"count\":") + 10);
String finalstr = substr.substring( 0, substr.indexOf("},"));
Log.d("Extracted_Value", finalstr); // output -> 46199005
There can be multiple ways. This is just one. Hope it will help you!

Related

How do I read only a specific part of the string in Android Studio?

If a send a string in the following format: 1234,1234,1234,1234; from Arduino to Android Studio (java (intelliJ)) based. with the amount of characters between every komma changing. How do i make it so that my code only reads the string from for example 0 to the , Or from the first , to the second ,?
If you are using Java, I would recommend looking into the Java.String.split() method. This method will split your string in an array of strings, depending on your delimiter. For example :
String s = "1234,1234,1234,1234";
String[] result = s.split(",");
You can split the input string based on any special character,in your case ,, as follows
String inputString = "1234,1234,1234,1234";
String[] separated = inputString.split(",");
Log.i("MainActivity",separated[0]) // prints the first string which is 1234
// to loop over all strings
for(String s : separated){
Log.i("MainActivity",s)
}

How can i get few characters from String?

I want to retrieve few characters from string i.e., String data on the basis of first colon (:) used in string . The String data possibilities are,
String data = "smsto:....."
String data = "MECARD:....."
String data = "geo:....."
String data = "tel:....."
String data = "MATMSG:....."
I want to make a generic String lets say,
String type = "characters up to first colon"
So i do not have to create String type for every possibility and i can call intents according to the type
It looks like you want the scheme of a uri. You can use Uri.parse(data).getScheme(). This will return smsto, MECARD, geo, tel etc...
Check out the Developers site: http://developer.android.com/reference/android/net/Uri.html#getScheme()
Note: #Alessandro's method is probably more efficient. I just got that one off the top of my head.
You can use this to get characters up to first ':':
String[] parts = data.split(":");
String beforeColon = parts[0];
// do whatever with beforeColon
But I don't see what your purpose is, which would help giving you a better solution.
You should use the method indexOf - with that you can get the index of a certain char. Then you retrieve the substring starting from that index. For example:
int index = string.indexOf(':');
String substring = string.substring(index + 1);

need to retrieve data from the database

I have a very long string in the database that needs to be retrieved into a swipe view.
But,the problem is that the string comprises of set of "\n\n"
Whenever it is separated with this expression i need to put it in another slide,i mean i am using SWIPE view here..
if(tablecolumn==\\n\\n)
{
code to break it to parts
}
Is this how i should be doing it?
If i am wrong,how to break this string to different parts and enable it into SWIPE VIEW in to different swipe view?
You can simply break your string comprising of a special character like this :-
String str ="mynameisjhon.yournameisdash.bla";
, here you have a string concatenated with " . " (period character)
to break this string do this :-
StringTokenizer st = new StringTokenizer(str, "."); //break the string whenever "." occurs
String temp =st.nextToken(); // it will have "my name is jhon" break
String temp2 = st.nextToken();// it will have "your name is dash"
String temp3 = st.nextToken();//it will have "bla"
now your string is breaked into parts!
Anything else?
Load the whole string into your ViewAdapter and seperate it via substring
or load the string in your Activity/Fragment seperate it via substring, put the strings in an ArrayList, an initiate your ViewAdapter with the ArrayList as data source
either way use substring

Not able to get name/value pairs from JSON object, when using variable

Not able to get name/value pairs from JSON object, when using the variable but able to read it when hard coding the name.
To better explain :
1) My JSON object is like this -
{.....
{ "rates":{ "name1": value1, "name2": value2 ...etc }
...}
2) I am able to read this object in my android app.
3) Now this rate object name value pairs, i am trying to read based on user input -
String s1 = '"'+name1+'"'; // here name1 i got from user input, & converted into string
4) Now when i am trying to get the value from rates object, i am getting null exception -
JSONObject rateObject = jObject.getJSONObject("rates"); //able to get
complete object
String rate1 = (String) rateObject.get(s1); // giving NULL exception
5) But if i use hard code string, it works -
String rate1 = (String) rateObject.get("name1"); // working
Any pointers why its not working while using variable.
thanks
Thanks for suggestions, i sorted out the problem. There are 2 mistakes i was doing - 1) Using the quotes as correctly pointed out by others and 2) casting the double value to string. Correcting both has resolved my problem :)
In terms of your final code snippet, you are actually doing
String rate1 = (String) rateObject.get("\"name1\""); //note the extra quotes
because you have bookended the user input string with double-quote characters. You just want the input string itself with no bookending. The quotes in the JSON notation serve to delineate each key name; the quotes are not part of the key name itself.
You need to omit the quotes when you create s1:
String s1 = name1;
Or, if name1 is not a String already:
String s1 = name1.toString();
Replace:
String s1 = '"'+name1+'"';
with:
String s1 = name1;

Android String Array Manipulation

I have a lengthy string in my Android program.
What I need is, I need to split each word of that string and copy that each word to a new String Array.
For eg: If the string is "I did android program" and the string array is named my_array then each index should contain values like:
my_array[0] = I
my_array[1] = did
my_array[2] = Android
my_array[3] = Program
A part of program which I did looks like this:
StringTokenizer st = new StringTokenizer(result,"|");
Toast.makeText(appointment.this, st.nextToken(), Toast.LENGTH_SHORT).show();
while(st.hasMoreTokens())
{
String n = (String)st.nextToken();
services1[i] = n;
Toast.makeText(appointment.this, st.nextToken(), Toast.LENGTH_SHORT).show();
}
Can any one please suggest some ideas..
Why not use String.split() ?
You can simply do
String[] my_array = myStr.split("\\s+");
Since '|' is a special character in regular expression, we need to escape it.
for(String token : result.split("\\|"))
{
Toast.makeText(appointment.this, token, Toast.LENGTH_SHORT).show();
}
You can use String.split or Android's TextUtils.split if you need to return [] when the string to split is empty.
From the StringTokenizer API docs:
StringTokenizer is a legacy class that
is retained for compatibility reasons
although its use is discouraged in new
code. It is recommended that anyone
seeking this functionality use the
split method of String or the
java.util.regex package instead.
Since String is a final class, it is by default immutable, which means you cannot make changes to your strings. If you try, a new object will be created, not the same object modified. Therefore if you know in advance that you are going to need to manipulate a String, it is wise to start with a StringBuilder class. There is also StringBuffer for handling threads. Within StringBuilder there are methods like substring():
substring(int start)
Returns a new String that contains a subsequence of characters currently contained in this character sequence.
or getChars():
getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Characters are copied from this sequence into the destination character array dst.
or delete():
delete(int start, int end)
Removes the characters in a substring of this sequence.
Then if you really need it to be a String in the end, use the String constructor(s)
String(StringBuilder builder)
Allocates a new string that contains the sequence of characters currently contained in the string builder argument.
or
String(StringBuffer buffer)
Allocates a new string that contains the sequence of characters currently contained in the string buffer argument.
Although to understand when to use String methods and when to use StringBuilder, this link or this might help. (StringBuilder comes in handy with saving on memory).

Categories

Resources