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

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).

Related

create object from random String

I have a string like this "*POS0210X/Hello from ECR/T64999"
In the string above X/ is and indicator of a type and /T a field. I want to create objects from those strings. Given that i know all the special combinations above, whats the best way to do it in kotlin?
PS there can be up to 10 different fields and the combination of them generate different objects

Android Parse a JSON String With Quotes in Keys and Values

Android JSON parsing is rather straightforward until it comes to have json reserved characters in your keys/values. I have JSON coming from an HTTP socket whose response is put into a string variable. It looks like this
{"ZboAdtPw4bA":"Ben Heck"s PlayStation 4 Slim Teardown","iC4qIx72_Cc":"Ben Heck's Xbox Slim Teardown"}
See the double quotation in the first value? It even screws up on StackOverflows web page. How am I supposed to escape/prevent this from happening? If I do a:
response = response.replace("\"", "");
Then all the double quotation get replaced, not just the ones in the key/value pair. This is because its all contained in one string at the moment. I am wondering if there is an easy way to do this with android. And of course, java answers are acceptable to. Now I could do this since its just a single dimensional key/value pair easily, I may not even need JSON, but I would like to adhere to standards.
you are simply trying to ruin the basic of a JSON .
you simply add
"/"" to the java code .
other than that its not possible for the parser to differentiate between the quotations from the JSON format or the quotations in the string .

Android: how to parameterize which resource to use at runtime? [duplicate]

This question already has answers here:
Access resource string by string name in array
(2 answers)
Closed 7 years ago.
Think about a list of parameters and their respective intervals of discrete integer values:
a[1-N], b[1-M], c[1-K], d[1-J]
a, b, c, d are the variables while between square brackets there are intervals of their possible values.
At runtime if they are
a=1, b=2, c=3, d=5
then I'd like to get the resource with
name = R.string.string_1_2_3_5
Is it possible?
I wouldn't want to make a series of cascade switches for each variable to finally pick a resource. I know this could work but is there another way?
You can use Java reflection like in here.
If you need to retrieve strings like that more than once, in order to get fast access, you should first construct a hashtable with the field names of R.string as keys (maybe when you launch the app).

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/

how to create a system update for my mobile app [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I am developing a mobile app, for both Android and BlackBerry.
I've uploaded my latest application for OTA installation by including version code and version name into a plain text file on the server.
Within my app, how do I convert code version and version name from the plain-text format on my server to a string. I want to do this so I can have the app compare it's current version against what is available on the server, so that if a newer version on the server, the user will be offered an update to download.
Let's say you upload a file to your server, that contains a single line:
1.2.3.4
The process is similar for Android and BB:
1- Retrieve the file from the server. You'll probably have a byte array as result.
2- Convert it to a String with the proper encoding. In case the txt only contains numbers and dots, the encoding is not really important since these are ASCII chars, and ASCII chars are compatible with most usual default encodings like UTF-8 and ISO-8859. So we could probably instantiate the string without dealing with the encoding, like this: String fileContent = new String(byte[] downloadedData). Otherwise, make sure you know in advance the txt file encoding and instantiate the string with that encoding.
3- Split the string using the dots as separators. In Android you can do it like this: String[] splitted = String.split(fileContent, '.'), or use a StringTokenizer. In BB, as it is based in CLDC, this method in String is not available so you should code it yourself, or use/port one from a well tested library (like Apache Commons' org.apache.commons.lang3.StringUtils.split). After this step you'll have an array of strings, each string being a number ({"1","2","3","4"} in the example).
4- Now create a int array of the same length, and convert each string in the array to its equivalent int, using Integer.parseInt(splitted[i]) on each element i.
5- Get the version for your app and perform the same steps to get an array of int. In BB, you can call ApplicationDescriptor.currentApplicationDescriptor().getVersion(). In Android, PackageInfo.versionCode or PackageInfo.versionName, depending on what you have specified in the manifest.
6- Notice both arrays don't need to be of the same length. You could have written "1.2.3.4" in your txt, but have "1.2.3" in your AndroidManifest.xml or BlackBerry_App_Descriptor.xml. Normalize both resulting int arrays to have the same length (the lenght of the longer one), and fill the added elements with zeroes. Now you'll have two int arrays (in the example, txtVersion = {1,2,3,4} and appVersion = {1,2,3,0}). Iterate comparing versions one by one. The rule is: if txtVersion[i] > appVersion[i], then you are out of date and an upgrade is needed.
This answer is for the android part only.
To get the app version number and name from your application, you can do the following (as suggested by #ColorWP.com
Getting the app version and name:
String version_number = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
String version_name = getPackageManager().getPackageInfo(getPackageName(), 0).versionNumber;
To read your file from the net:
URL url = new URL("http://www.your.site/your.txt");
URLConnection connect = url.openConnection();
BufferedReader txtreader = new BufferedReader(new InputStreamReader(connect.getInputStream()));
String line = txtreader.readLine();
while (line != null) {
/* Code to Read your variables in this loop
(let us assume these would be:
server_app_version
server_app_name)
*/
}
Make sure you add Internet permission, as suggested by #ColorWP.com
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
Compare the version:
if (server_app_version.compareTo(version_number) != 0 || server_app_name.compareTo(version_name) != 0){
// Notify user to download the new version
}
Instead of using txt files it is better to output JSON from your server (Android provides some useful JSON decoding and encoding methods).
Setup the URL to the page that outputs the JSON as a static final variable in your Update activity, download it using any method you like. The following answer may be useful.
Afterwards, parse the JSON string by using the code in this answer.
When you get the newest version of the app from your server as string or int you can compare it to the local app's version which you can get using:
PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
String version = pInfo.versionCode;
// To get the version name use pInfo.versionName
Remember to add the INTERNET permission so your app can connect online:
<uses-permission android:name="android.permission.INTERNET"></uses-permission>

Categories

Resources