How to convert string json to url format in android - android

I'm trying to make a slider with this tutorial and it works very good. But when I try to get the image url from JSON with volley this url does not work. I want to convert the string to url, but my code is not working.
img1 = obj.getString("image_1");
URL myURL1 = new URL(img1);

Add app/gradle.app as a dependencies
compile 'com.google.code.gson:gson:2.6.2'
Now you need to create a Object.class according to your Json object. And all key names should same as your Object.class
Eg: Json object:
{
"id": 1,
"message": "This is example"
"url": "http://www.jsoneditoronline.org/"
}
Class object:
public class ExampleObject {
public long id;
public String message;
public String url;
}
Then in your Activity.java:
//jsonObj is your JSON object
ExampleObject obj = new Gson().fromJson(jsonObj, ExampleObject.class);
Now all the values are saved into your Object class.

If you want to load the url of the image retrieved in an imageview you can pass the string to an image processing library, for exemple Glide. Here's a good tutorial on how to set it up and use it: https://futurestud.io/tutorials/glide-getting-started.

The Android SDK contains a very useful Uri class. It exposes a Builder that can be used for property URL building (instead of string concatenation, that you are using). It also has a Uri.parse() method, that can create an instance from a String.

Related

Is there a transformItems equivalent in the Android Java Libraries for Algolia?

I have a use case where i would like to render the image associated with the hits returned from an Algolia search using the Algolia Java library for Android. I am currently developing on Pie . Here is what i am doing :
I use com.algolia.instantsearch.core.helpers.Searcher
I bind the results to a fragment which has a layout with the algolia attributes for images
<ImageView
algolia:attribute='#{"image_url"}'
>
The trouble is that the response JSON only stores the name of the JPG image which needs to be displayed. I need to dynamically add the base site URL and some more path specifiers . I tried doing something like this
algolia:attribute='https://somedomain.com/somepath1/ProductImages/#{"BaseProductId"}/thumbnails/#{"image_url"}
But that was not accepted.
I am looking for a way to transform the results so i can build the complete URL and place it in the image_url and then use it in the layout as stated in the first code fragment.
Is there any way to do it ?
I solved it by adding a listener and updating the hits object as seen below.
searcher.registerResultListener(new AlgoliaResultsListener() {
#Override
public void onResults(#NonNull SearchResults results, boolean isLoadingMore) {
for (int i=0;i<results.hits.length();i++){
try {
JSONObject obj = results.hits.getJSONObject(i);
String image_url_file = obj.getString("image_url");
String base_product_id = obj.getString("BaseProductId");
String full_image_path = "https://somedomain.com/somPath/ProductImages/"+base_product_id+"/Original/"+image_url_file;
results.hits.getJSONObject(i).put("image_url",full_image_path);
}catch(Exception exx){
}
}
}
}
);

Android: Handle different type of value with GSON

In my app, I get and parse a JSON stream from a wordpress (RESP API v2) website.
I use, OKHTTP, RETROFIT with GSON converter to read and parse the stream into my objects.
Usually, my GSON converter expect an object but, because of a recent update, the website gives me a boolean (false). The value isn't set yet.
This is my question: "Can I handle different type of values for the same variable name with GSON Serialize and how?"
Thank you!
This is my object:
public static class StageProfileImage {
//////////////////////////////////////////////////
// Variables
//////////////////////////////////////////////////
#SerializedName("url")
private String stageProfileImageUri;
//////////////////////////////////////////////////
//////////////////////////////////////////////////
// Setters & Getters
//////////////////////////////////////////////////
public String getStageProfileImageUri() {
return stageProfileImageUri;
}
public void setStageProfilUri(String stageProfileImageUri) {
this.stageProfileImageUri = stageProfileImageUri;
}
/////////////////////////////////////////////
}
Important: I can't modify the stream.
try #SerializedName(value = "url", alternate = {"altkey1", "altkey2"})
Edit: Changed to a more generic example.
Thanks but it isn't my problem. In fact, GSON can't convert the stream from the website because instead of this:
"stage_profile_image" : {
...
}
My stream give me that:
"stage_profile_image" : false
In the first one, I get an object but in the second one I get a boolean which is not the type of value it expects and GSON is unable to do the convertion.

parse json android and show it in textview

I am new to android developing, my website returns posts with following format in json:
post= {
'artist':'xxxx',
'title':'xxxx',
'text':'xxxx',
'url':'http://xxxx'
}
I know something about receiving a file from the net and saving it to a SD card, but I want to do it on fly, parse it and show in on some text view, can you please give me some simple code for this?
I tried searching but I can't find a good tutorial for this, so this is the last place I'm coming to solve my problem.
A good framework for parsing XML is Google's GSON.
Basically you could deserialize your XML as follows (import statements left out):
public class Post {
private String artist, title, text, url;
public Post() {} // No args constructor.
}
public class Main {
public static void main(String[] args) {
Gson gson = new Gson();
String jsonString = readFromNetwork(); // Read JSON from network...
Post post = gson.fromJson(jsonString, Post.class);
// Use post instance populated with your JSON data.
}
}
Read more in GSON's user guide.

Using JSON to create an object in Groovy/Grails

I have a Groovy/Grails website that is being used to send data to Android clients via JSON. I have created both the Android client and the Groovy/Grails website; and they can output the same objects in JSON.
I can successfully create the respective objects in Android by mapping the JSON output to Java objects, however I was wondering if it's possible to use the JSON output to create a new domain object in Groovy/Grails? Is there a way of passing the JSON output to a controller action so that object will be created?
Here is an example of the JSON that I'd like to send;
{
"class":"org.icc.callrz.BusinessCard.BusinessCard",
"id":1,
"businessCardDesigns":[],
"emailAddrs":[
{
"class":"org.icc.callrz.BusinessCard.EmailAddress",
"id":1,
"address":"chris#krslynx.com",
"businessCard":{
"_ref":"../..",
"class":"org.icc.callrz.BusinessCard.BusinessCard"
},
"index":0,
"type":{
"enumType":"org.icc.callrz.BusinessCard.EmailAddress$EmailAddressType",
"name":"H"
}
},
{
"class":"org.icc.callrz.BusinessCard.EmailAddress",
"id":2,
"address":"cb#i-cc.cc",
"businessCard":{
"_ref":"../..",
"class":"org.icc.callrz.BusinessCard.BusinessCard"
},
"index":1,
"type":{
"enumType":"org.icc.callrz.BusinessCard.EmailAddress$EmailAddressType",
"name":"W"
}
}
]
}
The "class" matches to the Domain I'd like to save to, the ID is the ID of the Domain, then each item within the businessCardDesigns and emailAddrs needs to be saved using similar methods (in the Domain the businessCardDesigns and emailAddrs are ArrayLists). Many thanks in advance!
SOLUTION:
#RequestMapping(method = RequestMethod.POST, headers = "Accept=application/json")
public ResponseEntity<String> createFromJson(#RequestBody String json) {
Owner.fromJsonToOwner(json).persist();
return new ResponseEntity<String>(HttpStatus.CREATED);
}
Using the built-in Grails JSON converter makes this easier than the other answers, in my opinion:
import grails.converters.JSON
class PersonController {
def save = {
def person = new Person(JSON.parse(params.person))
person.save(flush:true)
}
}
The other benefits are:
There's no need to muck around in any config files
The resulting JSON object can be manipulated, if necessary, before assigning properties
It's far clearer in the code what's happening (we're parsing a JSON object and setting the properties on the Person entity)
I know you already accepted an answer but if I'm reading your question right, there's a built in "Grails" way to do this.
Create an entry for your action in URLMappings.groovy and turn on request parsing. For example, I create RESTful mappings like so:
"/api/bizCard/save"(controller: "businessCard", parseRequest: true) {
action = [POST: "save"]
}
And then in you controller
def save = {
def businessCardInstance = new BusinessCard(params.businessCard)
....
businessCardInstance.save(flush:true)
}
this might work for you
http://static.springsource.org/spring-roo/reference/html/base-json.html

i want to retrieve json data via url with android

i'm working on a API, and i want to take the json data that is display in an adress like this : https://api.empireavenue.com/profile/info/?apikey=YOURAPIKEY&username=TICKER&password=PASSWORD
and take this data to display it on my app .
Thanks.
The input to the parseJson method should be whatever you get back from the HTTP request. This also assumes the format is something like:
{"rootKey":{"intVal":1}}
You will have to modify the order in which you query objects depending on the structure.
private static final ROOT_JSON_KEY = "rootKey";
private static final INT_VALUE_NAME = "intVal";
public void parseJson(String webServiceResponse) {
JSONObject json = new JSONObject(webServiceResponse);
JSONObject rootObject = json.getJSONObject(ROOT_KEY);
int intValues = rootObject.getInt(INT_VALUE_NAME);
}
EDIT: Sorry, stupid coding error.

Categories

Resources