Json object returns with brackets - android

I'm trying to parse an Json object and it has this data:
"ingredients":["White bread","Bratwurst","Onions","Tomato ketchup","Mustard","Curry powder"]
When I return the value, the textview prints this :
[White bread,Bratwurst,Onions,Tomato ketchup,Mustard,Curry powder]
I want to remove the brackets but I cant. I'm doing this so far:
List<String> mIngredientArray = new ArrayList<>();
JSONArray ingredients = null;
Sandwich mSandwich = new Sandwich();
ingredients = mJsonObject.getJSONArray("ingredients");
for(int i=0; i<ingredients.length();i++){
mIngredientArray.add(ingredients.getString(i));
}
mSandwich.setIngredients(mIngredientArray);
The textview code:
ingredientsTV.setText(sandwich.getIngredients().toString());
But doesnt works. Any idea about how to solve it?
REQUIRED OUTPUT:-
White bread, Bratwurst, Onions, Tomato ketchup, Mustard, Curry powder

If you just want to remove the brackets, you can use regex like this
strIngredients = sandwich.getIngredients().toString();
strIngredients = strIngredients.replaceAll("\\[", "").replaceAll("\\]","");
ingredientsTV.setText(strIngredients);

You could just replace the bracket characters as suggested, but that doesn’t strike me as the most direct solution. You need to specify how the List object is converted to a string — something like:
String.join(“, “, mIngredientArray)

Finally, I used this line of code to solve my problem:
ingredientsTv.setText(sandwich.getIngredients().toString().replace("[","").replace("]",""));
When I tried to use ReplaceAll, the IDE said that I need to use 24 as minimunSdkVersion but I was using 16 so that's the reason I use replace instead of ReplaceAll. And it works finally.

Related

How to display n records per line in Logcat in Android Studio?

The following code convert a list to a string and display to Logcat, but all records are displayed in one line. I hope to display top 10 records per line in Logcat in Android Studio 3.0, how can I do ?
Note: Log.e("My", logList.joinToString("<Br/>", limit =10, truncated = "...more...")) doesn't work
val logList=LogHandler().getListAllLog()
Log.e("My", logList.joinToString("|", limit =10, truncated = "...more..."))
val strings = ArrayList<String>()
strings.add("This is line1")
strings.add("This is line2")
strings.add("This is line3")
display(strings)
You should iterator list. Try this:
fun display(strings: List<String>) {
for (str in strings) {
Log.e("YourTag", str)
}
}
you can chop up your List using chunked() method.
e.g. if you want to log 10 records per line, then just call chunked(10).
//assuming logList is an array of String.
//you can use logList.chunked directly if it is a List.
val batchSize = 10 //chop up to 10 per batch
logList.asList().chunked(batchSize)
.forEach{subList -> Log.d("My", subList.joinToString("|" )) }
You can simply use "\n" for new line,in logs.
For example:
Log.e(TAG,"Hello \n World");
which will give output as
Hello
World
I hope this helps,thank you.
if its not your answer,please ignore this answer.

Converting HTML escape sequence to Java

I am receiving a string using REST APIs.
JSONObject obj = new JSONObject(output);
JSONArray contacts = obj.getJSONArray("results");
JSONObject result = contacts.getJSONObject(0);
..
String brandName = result.getString("productName");
In some cases productName comes as Dri-FIT™ Element Half Zip.
I want to show it as "Dri-FIT™ Element Half Zip" in Android, but it shows up in the TextView as Dri-FIT™ Element Half Zip.
Can anyone help me as to how to convert the HTML escape sequence to a valid Java escape sequence so that I can view it?
You can try this. I think this is the best way to show your special symbol.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
tv.setText(Html.fromHtml("Dri-FIT™ Element Half Zip", Html.FROM_HTML_MODE_COMPACT));
}else{
tv.setText(Html.fromHtml("Dri-FIT™ Element Half Zip"));
}
Please replace &#8482 to \u2122 (2122 is hex for 8482)

Extra line breaks at end of text

I seem to be getting what seems like some extra line breaks after using this method to set the text of a TextView
message.setText(Html.fromHtml( message ));
How can I remove these? They cause my layout to get warped since it adds two extra lines to the output.
The string was saved to my sqlite database via Html.toHtml( editText.getText() ).trim();
Initial string input : hello
Log output of the message variable: <p dir="ltr">hello</p>
you can use this lines ... totally works ;)
i know your problem solved but maybe some one find this useful .
try{
string= replceLast(string,"<p dir=\"ltr\">", "");
string=replceLast(string,"</p>", "");
}catch (Exception e) {}
and here is replaceLast ...
public String replceLast(String yourString, String frist,String second)
{
StringBuilder b = new StringBuilder(yourString);
b.replace(yourString.lastIndexOf(frist), yourString.lastIndexOf(frist)+frist.length(),second );
return b.toString();
}
For kotlin you can use
html.trim('\n')
Looks like toHtml assumes everything should be in a <p> tag. I'd strip off the beginning and ending <p> and </p> tags before writing to the database.
This is working as below in Kotlin.
val myHtmlString = "<p>Test<\/p>"
HtmlCompat.fromHtml(myHtmlString.trim(), FROM_HTML_MODE_COMPACT).trim('\n')

Removing newline from string

Here's my issue:
I have a database and it is full of episodes of a tv show. One column denotes the episode number. I want to display the episodes in a list like this:
Episode 1
Episode 2
Episode 3
etc.
I'm using my own adapter class that extends SimpleCursorAdapter to do this...
Since I had formatting errors I am using Android.R.layout.simple_list_item_1 and Android.R.id.text1
Basically the only reason I have a custom adapter is so I can do something like this:
textView.setText("Episode " + cursor.getString("column_for_episode_number");
The problem is, I get a list that looks like this:
Episode
1
Episode
2
Episode
3
When I try something like this(which worked in a different portion of my code):
String text = "Episode " + cursor.getString("blah");
text = text.replaceAll("\\n","");
I get the exact same list output :(
Why don't I use create a custom view with two textboxes next to each other? It is hard for me to get that to look pretty :/
text.replaceAll(System.getProperty("line.separator"), "");
There is a mistake in your code. Use "\n" instead of "\\n"
String myString = "a string\n with new line"
myString = myString.replaceAll("\n","");
Log.d("myString",myString);
Check if there is new line at the beginning before you replace and do the same test again:
for(int i=0; cursor.getString("blah").length()-1; i++)
{
if(cursor.getString("blah").charAt(i)=='\\n') <-- use the constant for the line separator
{
Log.i("NEW LINE?", "YES, WE HAVE");
}
}
Or use the .contains("\n"); method:
Check the xml for the width of the textview as well.
Why are you using getString() when you are fetching an integer? Use getInt() and then use Integer.toString(theint) when you are setting the values in a textview.
This could help you:
response = response.replaceAll("\\s+","");
It sounds like you are hitting wrapping issues rather than newline issues. Change this:
String text = "Episode " + cursor.getString("blah");
To this:
String text = "Episode" + cursor.getString("blah");
And see if that changes the output. Post your layout xml please?
this worked for my (on android 4.4):
(where body is a string with a newline entered from an EditText view on handset)
for (int i=0; i<body.length(); i++) {
if (body.charAt(i) == '\n' || body.charAt(i) == '\t') {
body = body.substring(0, i) + " " + body.substring(i+1, body.length());
}
}
have you tried
cursor.getString("blah").trim()

android dynamical binding

I want to work dynamically therefore I want to bind text views dynamically I think an example would explain me the best
assuming I want to bind 7 image views i can do it like this :
Country = (EditText)findViewById(R.id.CountryEditText);
City = (EditText)findViewById(R.id.CityEditText);
LivinigCreture = (EditText)findViewById(R.id.LivingCretureE);
Nature =(EditText)findViewById(R.id.NatureEditText);
Inanimate = (EditText)findViewById(R.id.InanimateEditText);
KnowenPersonality = (EditText)findViewById(R.id.KnowenPersonalityEditText);
Occupation = (EditText)findViewById(R.id.OccupationEditText);
but lets change 7 with NUMOFFILEDS as a final where i want to do the previous ?
myImages = new ImageView [7];
for (int i = 0; i<7;i++,????)
myImages[i] = (ImageView)findViewById(R.id.initialImageView01);
notice : in my R file the R.id.initialImageView01 - R.id.initialImageView07 are not generate in a cont gap between them therefore I don't know how to make this architecture possible .
and if there's a way can someone show me an example how to work dynmiclly (like using jsp on android combined way or something ?)
id its possiable to do so constant times is it possible to build an the same xml constant num of times like jsp does
thank u pep:)
You can store the IDs themselves in an array at the beginning of your Activity; that way you'll only need to write them once and you can index them afterwards.
Something like:
int[] initialImageViewIds = {
R.id.CountryEditText,
R.id.CityEditText,
R.id.LivingCretureE,
R.id.NatureEditText,
R.id.InanimateEditText,
R.id.KnowenPersonalityEditText,
R.id.OccupationEditText
};
Then you can access them with:
myImages = new ImageView [7];
for (int i = 0; i<7;i++) {
myImages[i] = (ImageView)findViewById(initialImageViewIds[i]);
}
If that's not enough and you really want to get the IDs dynamically, I suppose you can use reflection on the R.id class, possibly with something like R.id.getClass().getFields() and iterate on the fields to check if their names interest you. Check reference for the Class class, too.

Categories

Resources