List from model Kotlin not neatly arranged - android

I try to get list from mutable list and parse it to array become spinner array, here is my code;
fun getListLeague(context: Context): MutableList<League> {
val league: MutableList<League> = mutableListOf()
val leagueName = context.resources.getStringArray(R.array.leagueName)
val leagueId = context.resources.getStringArray(R.array.leagueId)
league.clear()
for (i in leagueName.indices) {
league.add(League(leagueName[i], leagueId[i]))
}
return league
}
Then I call it in my spinner in fragment, here is the code;
private lateinit var leagues: List<League>
leagues = getListLeague(requireContext())
val spinAdapter = ArrayAdapter(requireContext(), android.R.layout.simple_spinner_dropdown_item, leagues)
Log.e("LIST LEAGUE PREV", leagues.toString())
I try to see the list from Log above, and I expect the result is like below;
E/LIST LEAGUE PREV: English Premier League, English League Championship, Scottish Premier League, German Bundesliga, Italian Serie A, French Ligue 1, Spanish La Liga, so on :)
Then I try to run the app, but the log result is appear like below:
E/LIST LEAGUE PREV: [League(leagueName=English Premier League, leagueId=4328), League(leagueName=English League Championship, leagueId=4329), League(leagueName=Scottish Premier League, leagueId=4330), League(leagueName=German Bundesliga, leagueId=4331), League(leagueName=Italian Serie A, leagueId=4332), League(leagueName=French Ligue 1, leagueId=4334), League(leagueName=Spanish La Liga, leagueId=4335), League(leagueName=Greek Superleague Greece, leagueId=4336), League(leagueName=Dutch Eredivisie, leagueId=4337), League(leagueName=Belgian Jupiler League, leagueId=4338), League(leagueName=Turkish Super Lig, leagueId=4339), League(leagueName=Danish Superliga, leagueId=4340), League(leagueName=Portuguese Primeira Liga, leagueId=4344), League(leagueName=American Major League Soccer, leagueId=4346), League(leagueName=Swedish Allsvenskan, leagueId=4347), League(leagueName=Mexican Primera League, leagueId=4350), League(leagueName=Brazilian Brasileirao, leagueId=4351), League(leagueName=Ukrainian Premier League, leagueId=4354), League(leagueName=Russian Football Premier League, leagueId=4355), League(leagueName=Australian A-League, leagueId=4356), League(leagueName=Eliteserien, leagueId=4358), League(leagueName=Chinese Super League, leagueId=4359)]
The result is under my expectation, so where have I gone wrong?

You are getting both leagueID and leagueName in your getListLeague
val leagueId = context.resources.getStringArray(R.array.leagueId)
league.add(League(leagueName[i], leagueId[i]))
And you are returning both attributes,
return league
This is why you are getting leagueID in your Log.
Secondly, you are calling this
leagues = getListLeague(requireContext())
Log.e("LIST LEAGUE PREV", leagues.toString())
so you get your result as
League(leagueName=English Premier League
My suggestion is to understand what you're doing first before making changes to your codes.

Related

Changing html properties after fetching API data in android studio

I'm fetching data using API and the one of the data is a HTML formatted text.
The data fetched from the API
{
"id": 4632,
"title": "Soy-and-Ginger-Glazed Salmon with Udon Noodles",
"summary": "Soy-and-Ginger-Glazed Salmon with Udon Noodles might be a good recipe to expand your main course collection. This dairy free and pescatarian recipe serves 4 and costs <b>$5.91 per serving</b>. One serving contains <b>552 calories</b>, <b>48g of protein</b>, and <b>17g of fat</b>. 1 person were impressed by this recipe. From preparation to the plate, this recipe takes roughly <b>1 hour and 35 minutes</b>. This recipe from Food and Wine requires sesame seeds, lime juice, olive oil, and salmon fillets. Taking all factors into account, this recipe <b>earns a spoonacular score of 92%</b>, which is great. If you like this recipe, take a look at these similar recipes: Soy-and-Ginger-Glazed Salmon with Udon Noodles, Soy-and-Ginger-Glazed Salmon with Udon Noodles, and Soy-and-Ginger-Glazed Salmon with Udon Noodles."
}
The summary is a HTML formatted text and im using HTML.fromHtml() to display the displayable styled text. My question is, is it possible to change the properties inside the HTML such as text decoration of a link to another color?
RecipeDetails.java
private final RecipeDetailsListeners recipeDetailsListeners = new RecipeDetailsListeners() {
#SuppressLint("SetTextI18n")
#Override
public void didFetch(RecipeDetailsResponse response, String message) {
Picasso.get().load(response.image).into(recipeImage);
RecipeName.setText(response.title);
recipeSource.setText(response.sourceName);
if (response.sourceName == null){
recipeSource.setText("Unknown");
}
recipeServing.setText(response.servings + " Serving");
recipeTimePrepared.setText(response.readyInMinutes + " Min");
recipeScore.setText(String.valueOf(response.aggregateLikes) + " Likes");
recipeSummary.setText(Html.fromHtml(response.summary, Html.FROM_HTML_MODE_COMPACT));
IngredientListRecipeDetails.setHasFixedSize(true);
IngredientListRecipeDetails.setLayoutManager(new LinearLayoutManager(getBaseContext(), LinearLayoutManager.VERTICAL, false ));
adapter = new recipeDetailsIngredientAdapter(getBaseContext(), response.extendedIngredients);
IngredientListRecipeDetails.setAdapter(adapter);
}
#Override
public void didError(String message) {
customToast("Unsuccessful", message, "Failure");
}
};

Adjective position in a string resource

In French the position of the adjective can be before or after the noun. Depending of the length of the adjective, changing the position of the adjective can be mandatory to make a correct sentence. For example :
Bonne qualité nutritionnelle pour ce repas
Qualité nutritionnelle médiocre pour ce repas
I know plurals are implemented in Android, and also gender agreement with the SelectFormat class, but nothing on changing word order, e.g. adjective position, in a string resource.
You can use MessageFormat with a custom pattern. For that example:
String pattern = "{1, select, before {{0} qualité nutritionnelle} other {Qualité nutritionnelle {0}}} pour ce repas";
MessageFormat msgFmt = new MessageFormat(pattern, new ULocale("fr"));
Object args[] = {"Bonne", "before"};
Log.d("MessageFormatTAG",msgFmt.format(args));
Object args2[] = {"médiocre", "after"};
Log.d("MessageFormatTAG",msgFmt.format(args2))

Android multilanguage support: string formatting issue due to different placeholder counts

I'm making a french Android app and I'm trying to support English.
I use "placeholders" to format my strings, so I can adapt them to male and female users. For example, this string in my strings.xml file:
<string name="encouraging_comment">
Les %1$s sont compliqué%2$ss...
</string>
will become "Les hommes sont compliqués" ("Men are complicated") or "Les femmes sont compliquées" ("Women are complicated").
And there lies my problem. The string translation, as follows...
<string name="encouraging_comment">
%1$s are complicated...
</string>
...needs only one placeholder, when the french equivalent needs two.
How can I manage this issue ?
Thanks in advance.
Just omit the second placeholder from the English template string and use an empty string for the second argument (or any other string, it doesn't matter, the value will be ignored) when you render the string:
XML:
<string name="encouraging_comment">
%1$s are complicated...
</string>
Java:
getString(R.string.encouraging_comment, "women", "");
getString(R.string.encouraging_comment, "men", "");
This works because it's not an error if there are more arguments than placeholders, only if there are fewer arguments than placeholders.
I'm assuming that you'll have some kind of table or mapping where you look up the placeholder values based on language and gender. In pseudo-code:
(French, Female) -> ("femmes", "e")
(French, Male) -> ("hommes", "" )
(English, Female) -> ("women", "" )
(English, Male) -> ("men", "" )
AFAIK, you can do this by adding check in your code like
String result;
if ( Locale.getDefault().getLanguage().equals("en")){ // examples "en", "fr", "sp"
result= getString(R.string.encouraging_comment, myString);
}
else{
result= getString(R.string.encouraging_comment, myString, myStringTwo);
}
textView.setText(result);
Hope this helps you :)
One way to do this is create a string locale in your strings.xml
for English Strings.xml
<string name="locale">En</string>
for French Strings.xml
<string name="locale">Fr</string>
Then while setting string
switch (getString(R.string.locale)) {
case "Fr":
//set your string for French
break;
case "En":
//set your string for English
break;
}

json parsing without name in android

i have worked with json name value pair before works fine and great but below is my json object in which there is no name and only value. Can anyone tell is it possible to use this type of json in android if yes then how to extract values from this json object. or any related link will be great.
JSON OBJECT
{
"log_list": [
[
"21",
"doctorFisher",
"Pharmacy 1",
"patientfish",
"test",
"2014-08-25 05:58:18",
"record UCI tech FDNY icky shut rack soon sun TDK tell. ox it'll ohm URL did GCVO dash ugly dog did flood idiot fluff if if rid t-shirts didn't TechTV only chef doc scotch Rebekah an if lb tax scotch am ICN JCB JCB HGV JCB HGV in on pm tax UDC OK red uh HK ohm",
"<img id=\"prescription_image\" onClick=showPrescriptionDetails(\"3c59dc048e8850243be8079a5c74d079\") onmouseover=\"this.style.cursor='pointer'\" src=\"\" width=\"20\" height=\"20\">"
],
[
"20",
"doctortest12345",
"Pharmacy 1",
"testpatient12345",
"test",
"2014-08-25 03:57:32",
"she'd Urdu text scuff uno dad uno each ink why tough days ICO saved USCIS David rig though end FDIC UCI's for USCIS tend did for dog such vidi fly floor exited did DND hand bid GMD.",
"<img id=\"prescription_image\" onClick=showPrescriptionDetails(\"98f13708210194c475687be6106a3b84\") onmouseover=\"this.style.cursor='pointer'\" width=\"20\" height=\"20\">"
]
}
thanks in advance
Yes, that format would work and you can pretty easily use it.
Assuming you have a variable String json which contains that data:
JSONObject jsonObj = new JSONObject(json);
Now log_list would be parsed as a JSONArray like so:
JSONArray logJsonArray = jsonObj.getJSONArray("log_list");
Then you can iterate through that outer array very similar to how you would a normal array or ArrayList:
for(int outerArrayPos = 0; outerArrayPos < logJsonArray.length(); outerArrayPos++){
JSONArray innerArray = logJsonArray.getJSONArray(outerArrayPos);
for(int innerArrayPos = 0; innerArrayPos < innerArray.length(); innerArrayPos++){
String valueAtIndex = innerArray.getString(innerArrayPos); //innerArray
// Do whatever you want with the values here
}
}
That will parse your String, but figuring out how to actually use that data is going to be most of your struggle, so I hope the order in which the information is returned will always be the same for your sake.
If you can, I would definitely recommend using a JSONObject for the data that is currently contained in your inner array. e.g.
{
"log_list": [
{
"id": "21",
"name": "doctorFisher",
.....
}
]
}

parsing the Json Data

Here I am posting my Json Response below:
{"ResultSet":
{"Result":[
{"Phone":"(650) 473-9999",
"Distance":"2.59",
"MapUrl":"http://maps.yahoo.com/maps_result?q1=441+Emerson+St+Palo+Alto+CAgid1=28734629",
"Categories":
{"Category":[
{"content":"Salad Restaurants",
"id":"96926225"},
{"content":"Vegetarian Restaurants",
"id":"96926239"},
{"content":"Pizza",
"id":"96926243"},
{"content":"Wine",
"id":"96926864"},
{"content":"Alcoholic Beverages",
"id":"96929810"}]},
"City":"Palo Alto",
"Title":"Patxi's Chicago Pizza",
"State":"CA",
"Rating":
{"LastReviewDate":"1241373758",
"LastReviewIntro":"My husband brought me a slice of their pizza after I had heard glowing reviews from the Sarah and Vinnie morning show on Alice radio (they get theirs from the SF location). Anyway I had been very interested in trying what sounded like very special pizza. My husband and son went during a time when you can buy slices so waiting for the food wasnt an issue. I usually dont like pizza cold but by the time they got it home to me it was very luke warm. NOT A PROBLEM! I was amazed at how yummy it was and was having the hardest time NOT eating it while standing in the kitchen leaning over the pizza-to-go box! Im not sure of what the name of the slice was except that it did have sausage and possibly spinach in it. This was a week ago and Ive been craving it ever since. When we do go back we will either order ahead to save on the wait or go during pizza slice hours. Ive heard they also do NY style for those of you thin crust fans! Check it out!!",
"TotalReviews":"27",
"TotalRatings":"27",
"AverageRating":"4.5"},
"Address":"441 Emerson St",
"Latitude":"37.445242",
"Longitude":"-122.163427"}]}}
Noe I want to have the following data Parsed "Phone", "Distance", "City", "Title", "State" and only "AverageRating" from the Tag "Rating".
Can anybody please help in sorting this particularly.
Thanks,
David
I've written about this subject before here on SO, look at it here:
Json Parsing in Android Application
Posted some code:
String phone = null;
String distance = null;
String city = null;
String title = null;
String state = null;
String aveRat = null;
JSONObject jsonObject = new JSONObject(yourResponse);
JSONArray infoArray = jsonObject.getJSONArray("Result");
JSONArray ratingArray = jsonObject.getJSONArray("Rating");
for (int i = 0; i < infoArray.length(); i++) {
try {
phone = infoArray.getJSONObject(i).optString("Phone");
distance = infoArray.getJSONObject(i).optString("Distance");
city = infoArray.getJSONObject(i).optString("City");
title = infoArray.getJSONObject(i).optString("Title");
state = infoArray.getJSONObject(i).optString("State");
aveRat = ratingArray.getJSONObject(i).optString("AverageRating");
} catch (JSONException e) {
}
}

Categories

Resources