i want to retrieve json data via url with android - 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.

Related

How to convert string json to url format in 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.

Parse nested object using GsonConverter with Retrofit2

I`m trying to convert the next JSON to object:
{
AccountName:"temnoi",
Parts:{
part-0:{
Name:"HOME",
UptimeSeconds:"2143943",
},
part-1:{
Name:"WORK",
UptimeSeconds:"2276958",
}
}
}
The problem is that Parts isn't an array so I don't have any idea how
to obtain them as List or any other data structure.
For now I have such DTO class
public class Info {
private String AccountName;
private List<Parts> Parts;
}
But obviously program crash as there are no array. I use Retrofit2 with GsonConverter.
Can anyone suggest something to solve this problem?
Unfortunately, as I don't have a lot of time, I came with the next solution.
I replace Retrofit2 by OkHTTP and Gson with built-in JSON parser.
After I get a response with OkHttpClient I manually convert JSON to my object.
JSONObject root = new JSONObject(responseFromServer);
JSONObject parts = root.getJSONObject("Parts");
Iterator<String> jsonPartsIterator = parts.keys();
List<Part> partsList = new ArrayList<>();
while (jsonPartsIterator.hasNext()) {
try{
String key = jsonRootIterator.next();
partsList.add(convertPartJsonToObject(computers.getJSONObject(key)));
} catch(Exception e){
// in case if there will be number '0' return empty List
}
}
Here Part convertPartJsonToObject(JSONObject object) is method to convert part-0, part-1... to object which I need.

How to add array as post parameter retrofit 2

I want to pass an array as parameter like this:
images[] = "Base64String A..."
images[] = "Base64String B..."
images[] = "Base64String C..."
images[] = "Base64String ..."
I'm using Laravel 5.1 on server side.
My controller to handle post data:
public function uploadTempImage(){
if (Input::has('images')) {
$images = Input::get('images');
$barcode_id =Input::get('barcode_id');
$upload_count=0;
foreach($images as $string_image) {
$image = base64_decode($string_image);
$filename = "$barcode_id$upload_count".time().date("d").date("m").date("Y").".jpeg";
$upload_count +=Storage::disk('local')->put("/tempImage/".$filename , $image);
}
return $upload_count;
}else{
return 'no file uploaded';
}
}
i use postman to test my server and its working..
please help me get over this.. thanks
TL;DR using arrays in form data like this is a bit problematic and hardly standardized. Avoid if possible.
Long version
Read this issue on retrofit's github
If the strings won't be too massive, consider using JSON as your transport vehicle, and declare a JSON array to store your base64 strings.

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.

Parsing Picasa API JSON Feed in android

Hi I am trying to implement a simple application showing picasa photos in android.
After many trials now I use the Google Java Api Client (Not the Gdata one), to fetch the Picasa Feed.
In my program, the first layer fields of JSON in the feed (e.g. version and encoding in the code below) can be succesfully mapped, so no problem with the feed and connection
However I am unable to map the second layer fields into Objects.
I use albumFeed = response.parseAs(AlbumFeed.class);
which will invoke the parser.
From the official sample I have this AlbumFeed.java
public class AlbumFeed {
// cannot be List
#Key
List<AlbumEntry> feed;
#Key
String version;
#Key
String encoding;
}
With List <AlbumEntry> feed ;
I will get this Error, which say List cannot be initiate
06-16 14:35:10.789: E/AndroidRuntime(1129): Caused by: java.lang.IllegalArgumentException: unable to create new instance of class java.util.List because it is an interface and because it has no accessible default constructor
I changed to
ArrayList<AlbumEntry> feed
no error will be shown but the ArrayList will be empty. Can anyone advise me the correct Way to map JSON to Objects using the given JsonObjectParser?
Many thanks if anyone can answer my question
more CODE
public class newApiActivity extends Activity {
HttpTransport transport = AndroidHttp.newCompatibleTransport();
static final JsonFactory JSON_FACTORY = new JacksonFactory();
public static HttpRequestFactory createRequestFactory(HttpTransport transport) {
return transport.createRequestFactory(new HttpRequestInitializer() {
public void initialize(HttpRequest request) {
// final JsonCParser jsoncparser = new JsonCParser(JSON_FACTORY);
request.setParser(new JsonObjectParser(GSON_FACTORY));
// request.setParser(jsoncparser);
GoogleHeaders headers = new GoogleHeaders();
headers.setApplicationName("APOD/1.0");
headers.setGDataVersion("2");
request.setHeaders(headers);
}
});
}
public void mainLogic(){
HttpRequest buildGetRequest = reqFactory.buildGetRequest(url);
HttpResponse response = buildGetRequest.execute();
albumFeed = response.parseAs(AlbumFeed.class);
}
}
where AlbumEntry.java will be something like
I am taking the xmlns to test the behavior)
public class AlbumEntry extends Entry {
#Key("xmlns")
public String xmlns;
}
The JSON Feed itself is like:
{"version":"1.0","encoding":"UTF-8",
"feed":{"xmlns":"http://www.w3.org/2005/Atom","xmlns$gphoto":"http://schemas.google.com/photos/2007,……}}
Stupid me. There is nothing to do with the android/ picasa api context.
After reading more on the GSON documentation, according to the json object {} will be a map but not an array . While array can be mapped to List, map can be mapped into an Object or Map
I changed to simple
#Key
AlbumEntry feed;
in AlbumFeed.java
It starts working.
A nice reference on GSON is here
Converting JSON to Java

Categories

Resources