Substring in android [closed] - android

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Hi guys I'm newbie in android dev.. can you help me with this one? I am trying to get the filename in string. I know that I need to substring it but I failed to get the right output. For example I have the string value of:
{"Filename":"23476-love-823873.jpg","ChunkId":1,"ChunkLength":201929,"FileLength":12122}
and I want to get only the filename which is "23476-love-823873.jpg" How can I do that? Thanks for helping.

You've got structured data there, so you shouldn't do this blindly with a substring. Instead, you can parse your string as JSON and then access the appropriate property of the new object. There's an Android JSON library that you can import from org.json. Specifically, you'll want to use the parser here: http://developer.android.com/reference/org/json/JSONTokener.html

Given:
yourstring= {"Filename":"23476-love-823873.jpg","ChunkId":1,"ChunkLength":201929,"FileLength":12122}
Try this Code:
int startindex,endindex;
startindex=indexOf(':');
endindex=indexOf(',');
String filename= yourstring.substring(startindex,endindex);

It looks like a structured object( HashMap, NameValuePair, JSON etc.).
Anyway, If its a String,
String mString = "{\"Filename\":\"23476-love-823873.jpg\",\"ChunkId\":1,\"ChunkLength\":201929,\"FileLength\":12122}";
if(mString.contains("Filename")){
int start=mString.indexOf("Filename")+11;// If file name is not at beginning, have to do like this.
int end=mString.indexOf(",", start)-1;//-1 for excluding a double code
String filename=mString.substring(start, end);
}

then if that string is json response and you are sure that you will consistently get that string format then it is applicable to use the approach given by #Abhishek. See my sample below, same as what he gave.(a very little revision).
String sample = "{"Filename":"23476-love-823873.jpg","ChunkId":1,"ChunkLength":201929,"FileLength":12122}";
Log.d("string", sample);
int startindex,endindex;
startindex = sample.indexOf(':');
endindex = sample.indexOf(',');
String filename= sample.substring(startindex + 1,endindex);
Log.d("result", filename);
your log will be like this:
string {"Filename":"23476-love-823873.jpg","ChunkId":1,"ChunkLength":201929,"FileLength":12122}
result "23476-love-823873.jpg"

It's look like a JSON string, there are many ways for you to parse it.
Refer to same question on SO: Sending and Parsing JSON Objects

The standard approach will be using a JSON library to de-serialize the String into a Java object or Map and then get the property value. If it is too heavy, you can use Regular Expression.

Related

Parse several JSONOBject into an array in android [duplicate]

This question already has answers here:
how to parse JSONArray in android
(3 answers)
Closed 7 years ago.
From the server I get a string with exactly the following format:
[{"valueOne", "341", "valueTwo": "1432"}, {"valueOne", "6483", "valueTwo": "3267"}]
I understand that it is two JSONObject into an array, but ..
Howparse this?
My intention is to have all the concatenated string values, like this:
Strings values = (341 + 1432 + 6483 + 3267);
I guess I must first convert the string that I have received from the server to JSONObject, but do not know how to continue.
In this example there are two JSONObjects, but sometimes may contain three or more.
Many times I get values from JSONObjects values, but I have never seen in this case. I searched for information but can not find a solution that is useful to me.
I appreciate the help
greetings!
JsonArray jArray= <your parsed array>;
for(int i=0;i<=jArray.lenght()-1;i++)
{
String valueOne=jArray.getJsonObject(i).getString("ValueOne");
String valueTwo=jArray.getJsonObject(i).getString("ValueTwo");
}
you can do whatever you want with the values.

How to parse nested JSON object in android [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I want to parse the verse_nr and verse from the bellow JSON data.can anyone help me..
{"book":[{"book_ref":"Ps","book_name":"Psalms","book_nr":"19","chapter_nr":"16","chapter":{"8":{"verse_nr":"8","verse":"I have set the LORD always before me: because he is at my right hand, I shall not be moved."}}}],"direction":"LTR","type":"verse","version":"kjv"}
You'll need to use a JSON Parser library. Here's an example with org.json. parser.
JSONObject root = new JSONObject(inputJSON);
JSONObject chapter = root.getJSONArray("book")
.getJSONObject(0).getJSONObject("chapter");
JSONObject verse = chapter.getJSONObject(JSONObject.getNames(chapter)[0]);
Basically, you just chain the JSON getters till you reach the verse object. Once there, you can access the values with getString() as
System.out.println(verse.getString("verse_nr"));
System.out.println(verse.getString("verse"));
Output :
8
I have set the LORD always before me: because he is at my right hand, I shall not be moved.
You must iterate over it using JSONObject and JSONArray.
You can generate classes using: http://www.jsonschema2pojo.org/ Just make sure to check 'Json' as opposed to 'Json Schema' since this is the raw json. Then you can use gson to automatically turn this into the those generated classes. A guide on doing so:
http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html
If this is coming from a server, I'd recommend using the wonderful Retrofit library which would allow you to do all the above with just a few lines of code; a tutorial of doing this can be found here: http://inaka.net/blog/2014/10/10/android-retrofit-rest-client/
Anyways if want to ignore making your life easier with the above solutions, to manually do this you'll do something like the following:
String jsonLiteral = /* your json remember to escape the double quotes */
JSONObject root = new JSONObject(jsonLiteral);
// Get Strings from a JSONObject as
String direction = root.getString("direction");
// You have a single element array, so you need to get that
JSONObject singleElement = root.getJSONArray("book").getJSONObject(0);
// Then you can Strings from it like direction above
String bookRef = singleElement.getString("book_ref");
You can also get a pretty output to inspect the json structure by using:
http://jsonformatter.curiousconcept.com/

Searching a string from large text file of 10 Mb [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have a large file of about 10 MB, I want to search a specific string, and this specific string may be used a lot of times in 10 Mb text file. I need results where this specific string is used. I want to do search like Google. For example when i write a string then google comes with matching Patterns . Your suggestions will be appreciated.
file formate
he is going to school.
we should do best deeds.
we should work hard.
.
.
.
.
Always speak truth.
i have search edit field in my application.
user write "should" in search edit field.and press search button.
a list should be opened in which searched words come with it's complete line.
for example result should be
we should do best deeds.
we should work hard.
A simple way to search a file and get a match "with context" is to use grep. For example, to match every line with "hello", and print one line before and three lines after, you would do
grep -b1 -a3 'hello' myBigFile.txt
You can use grep -E to allow for a wide range of PCRE regex syntax.
Without more detail it would be hard to give you a better answer.
EDIT 2
Now that you have explained your problem more clearly, here is a possible approach:
InputStream fileIn;
BufferedReader bufRd;
String line, pattern;
pattern = "should"; // get the pattern from the user, do not hard code. Example only
fileIn = new FileInputStream("myBigTextfile.txt");
bufRd = new BufferedReader(new InputStreamReader(fis, Charset.forName("UTF-8")));
while ((line = bufRd.readLine()) != null) {
if(line.contains(pattern)) {
System.out.println(line); // echo matching line to output
}
}
// Done with the file
br.close();
If you need to match with wildcards, then you might replace the line.contains with something that is a little more "hard core regex" - for example
matchPattern = Pattern.compile("/should.+not/");
(only need to do that once - after getting input, and before opening file) and change the condition to
if (matchPattern.matcher(line).find())
Note - code adapted from / inspired by https://stackoverflow.com/a/7413900/1967396 but not tested.
Note there are no for loops... maybe the boss will be happy now.
By the way - if you edit your original question with all the information you provided in the comments (both to this answer and to the original question) I think the question can be re-opened.
If you expect the user to do many searches it may be faster to read the entire file into memory once. But that's outside of the scope of your question, I think.

adding string as integer [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
in my application i have got 0.00 in edit text.next when i enter 2or3 or any digit its getting concat with 0.00 and getting 0.003.
if(item.equals("0.00")){
item=item+string;}
i changed the code.but this time too its getting an error
if(item.equals("0.00")){
int a=Integer.parseInt(item.toString());
int b=Integer.parseInt(string.toString());
int c=a+b;
item=String.valueOf(c);}
If you are using decimal places then you will want to use a data type that supports those, such as double. Try this:
double d = Double.parseDouble(item.toString());
NOTE: If both your variables are of string type, then you won't need to use toString()
You want O.OO but still using Integer. Try using FLOAT.
Also, FLOAT is NEVER a perfect value. So you might have .XX added.
You have an error, because "0.00" has decimal places, so it is parsed as a floating point number, not integer.
Parse it as a double:
String item = "0.00";
double result = Double.parseDouble(item) + 0.03; // result is 0.03

How to extract the string variable in android? [duplicate]

This question already has an answer here:
How to extract this string variable in android?
(1 answer)
Closed 9 years ago.
String test=["1","Low-level programming language",true]
Here i want to extract this string value and as i need to get only second value like "Low-level programming language".How to get this value using string functions in android?
Per your comment, I'm assuming that you have a single string that contains the entire text (including the brackets). In general, splitting comma-separated values is a fairly tricky process. For your specific string, though, it's kind of easy:
String test = "[\"1\",\"Low-level programming language\",true]";
String[] pieces = test.split(",");
String middle = pieces[1];
// now strip out the quotes:
middle = middle.substring(1, middle.length() - 1);
In general, you might want to look at using a general CSV parser like Apache Commons CSV or openCSV.
Alternatively, if this is JSON data (which looks more likely than CSV), take a look at using one of the Java JSON libraries listed here (scroll down the page to see the list).

Categories

Resources