How to start an android project coders view - android

I've been searching for the past week on how to develop an android project, read some on android developers page and on other websites like here, but no text was complete.
i have this project - i'm a php developer not a java, but could understand a bit about java lately.
the thing is i want to develop an android app using my website, i did output a json type data from my website, and gonna use them on the android app, i did the async request on android and could read the data form the website but :
first question: how to parse the json data correctly and convert it to array on android, i did that through:
Iterator<String> itr = myObject.keys();
while (itr.hasNext()) {
...
i don't know if that's the correct way, when i try to convert my json object to array, it gives me type mismatch.
second and more importantly:
how can create a "Block" like facebook posts style, or twitter style blocks, you know - blocks of json data, is it a linearlayout ? what do i call it ? and how can i add it to the UI dynamically, cuz these blocks are pulled from the website json data. so they are arrays...of blocks..
i'm kinda confused still, i need a start point.
Thank you!

excellent tutorial for beginners for android development
http://thenewboston.org/list.php?cat=6
and for your first question - how to parse json data correctly,
you can try using gson to convert the json data into POJO
otherwise you'd have to do myObject.opt(key) to make sure it is there

First question: you should use a library to parse JSON, it's simpler that way. Try gson. You should create a class, which holds the parsed object, like:
public class Taxi implements Serializable {
private static final long serialVersionUID = 1L;
#SerializedName("idTaxi")
private Integer idTaxi;
#SerializedName("name")
private String name;
//getter, setters, constructor, etc
}
Then when you get the JSON object, you can parse it:
Gson gson = new Gson();
Reader reader = new InputStreamReader(SOURCE_STREAM);
Taxi[] response = gson.fromJson(reader, Taxi[].class);
Second question: i think a ListView would be good for you. You can read a full tutorial about it here

Related

Is there any way to directly handle json in android/java without convert [duplicate]

I was wondering if somewhere out there exists a java library able to query a JSONObject. In more depth I'm looking for something like:
String json = "{ data: { data2 : { value : 'hello'}}}";
...
// Somehow we managed to convert json to jsonObject
...
String result = jsonObject.getAsString("data.data2.value");
System.out.println(result);
I expect to get "hello" as output.
So far, the fastest way I have found is using Gson:
jsonObject.getAsJsonObject("data").getAsJsonObject().get("data2").getAsJsonObject("value").getAsString();
It's not actually easy to write and read. Is there something faster?
I've just unexpectedly found very interesting project: JSON Path
JsonPath is to JSON what XPATH is to XML, a simple way to extract parts of a given document.
With this library you can do what you are requesting even easier, then my previous suggestion:
String hello = JsonPath.read(json, "$.data.data2.value");
System.out.println(hello); //prints hello
Hope this might be helpful either.
While not exactly the same, Jackson has Tree Model representation similar to Gson:
JsonNode root = objectMapper.readTree(jsonInput);
return root.get("data").get("data2").get("value").asText();
so you need to traverse it step by step.
EDIT (August 2015)
There actually is now (since Jackson 2.3) support for JSON Pointer expressions with Jackson. So you could alternatively use:
return root.at("/data/data2/value").asText();
First of all, I would recommend consider JSON object binding.
But in case if you get arbitrary JSON objects and you would like process them in the way you described, I would suggest combine Jackson JSON processor along with Apache's Commons Beanutils.
The idea is the following: Jackson by default process all JSON's as java.util.Map instances, meanwhile Commons Beanutils simplifies property access for objects, including arrays and Map supports.
So you may use it something like this:
//actually it is a Map instance with maps-fields within
Object jsonObj = objectMapper.readValue(json, Object.class);
Object hello = PropertyUtils.getProperty(jsonObj, "data.data2.value")
System.out.println(hello); //prints hello
You can use org.json
String json = "{ data: { data2 : { value : 'hello'}}}";
org.json.JSONObject obj = new org.json.JSONObject(json);
System.out.println(obj.query("/data/data2/value"));
I think no way.
Consider a java class
class Student {
Subject subject = new Subject();
}
class Subject {
String name;
}
Here if we want to access subject name then
Student stud = new Student();
stud.subject.name;
We cant access name directly, if so then we will not get correct subject name. Like here:
jsonObject.getAsJsonObject("data")
.getAsJsonObject()
.get("data2")
.getAsJsonObject("value")
.getAsString();
If you want to use same like java object then use
ClassName classObject = new Gson().fromJson(JsonString, ClassName.class);
ClassName must have all fields to match jsonstring. If you have a jsonobject inside a jsonobject then you have to create separate class like I'm doing in Student and Subject class.
Using Java JSON API 1.1.x (javax.json) one can make use of new JavaPointer interface. Instance implementing this interface can be considered to some extend as kind of XPath expression analog (see RFC-6901 for details). So in your case you could write this:
import javax.json.*;
//...
var jp = Json.createPointer("/data/data2/value");
System.out.println(jp.getValue(jsonObject));
In 1.1.4 version of JSON there's also nice addition to JsonStructure interface (which is implemented by JsonObject and JsonArray), namely getValue(String jsonPointer). So it all comes down to this simple one-liner:
System.out.println(jsonObject.getValue("/data/data2/value"));

Serilize custom ArrayList to JSON

I'm working on fixing an issue on an Android app using Java. I have a custom ArrayList which I want to pass to a server as JSON. I just want to know is this possible? When I pass in an ArrayList of type String it passes to the server perfectly fine. Any help or links to articles on this would be extremely helpful.
I have used GSON library from Google for converting ArrayList or even collection of custom complex type to JSON.
GSON provides you capability to register custom serializer/deserializers as well. See documentation.
To start with try following code snippet to serialize an ArrayList.
ArrayList<CustomObject> arrayList = ...
Gson gson = new Gson();
String serializedJson = gson.toJson(arrayList);

How to read JSON array and display image in Android

I am developing android listing images app where I got array from server side. But I have issue to read array or don't know how to get it.
Below array i got from server API call:
{"lists":["http:\/\/xyz.com\/projects\/photo\/birthday\/1.jpg","http:\/\/xyz.com\/projects\/photo\/birthday\/3.jpg","http:\/\/xyz.com\/projects\/photo\/birthday\/4.jpg"],"Status":"1"}
How to read it and display images in loop.
Thanks
If you are using gson library for parsing json respose then you could simply write a separate class
like this
public class ImageResponse{
public String Status;
public List<String> lists;
}
NOTE: when creating a class the object names of the class should match with the tag names from the server..
Then using gson
ImageResponse detail = (new Gson()).fromJson(
response.toString(), ImageResponse.class);
where response is your response from the server
now u can access the list like
List<String> images =details.lists;
Now you have all the images in the list form, you can load the images using Picasso[lets say in a listview]
Picasso.with(context).load(images[0]).into(imageView);
For using this you should add GSON library to your dependency in your app gradle
compile 'com.google.code.gson:gson:2.2.4'
There are many other method too, feel free to search and find out may be there will be more optimized code than this..

Object XML mapping in Android

I am developing a client-server Model-based application in which client is in Android and server in PHP.
I want to transfer product information for example Name,Price,Description, from client to server.
I have read that through marshaling/unmarshaling or serialization it can be achieved but all tutorials and example are in Java. But I need in Android. Please guide me to implement in Android. Or there is any other way to implement? Any example will b appreciated. Thanks.
Have a look on json. Google provides a nice Library called "Gson" for that.
To stick to your example, a json representation send from your server via http could be:
{"name":"foo", "price":"1000", "description":"this is an item description"}
In your app, you have a class MyObject.class
public class MyObject {
private String name;
private double price;
private String description;
// all your other methods
}
Then you can just do:
MyObject obj = new Gson().fromJson(jsonString, MyObject.class)
and voila, made an object out of the string in one line. Just be sure that the variables have the same name in the json representation and the class, then Gson does all the work for you. You can also make a String representation out of the object with String jsonString = new Gson().toJson(obj).
I'm using SimpleXML http://simple.sourceforge.net/
And I'm happy with it, it's a light jaxb like!

How to parse json page using gson?

I have a large json page which contains url:http://akhilmadanan.tk/Akhil/database.php.
While i am parsing this page using normal json parsing method it shows "OutOfMemoryError". For this i heard about GSON. Please any body help me get how to read the datas from below page using GSON.
any tutorial?
Here'a good tutorial:
http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html
You can also check out their official user guide:
https://sites.google.com/site/gson/gson-user-guide
Hope this helps :-)
Instead of returning all the data, why don't you break it into chunks? That would require less memory at processing time.
Thats assuming you have access to the database level/response.
You can definitely go to links provided by others which are helpful
For brief you can add GSON library in your lib folder.
and use like this.
Gson gson=new Gson();
To get object from json
Model model=gson.fromJson(json,Model.class);
To convert to json
String json=gson.toJson(model);
I run your code and there are 3010 items of object
[
{
"cust_no":"70105615002",
"cust_name":"akhil",
"address":"kajffjkhfhhkjsd",
"area":"58695",
"ranges":"4586",
"plot":"69896",
"multifactor":"85758",
"electricity_meterno":"7895",
"water_meterno":"69358",
"gas_metrno":"78956",
"traffic_code":"4587855",
"last_meter":"58695",
"previous_reading":"25638",
"date":"589687",
"current_usage":"789654",
"current_balance":"45876",
"last_recipt":"236584"
},....
Now make a model equivalent to above name like
#SerializedName("cust_no")
private Long custNo;
#SerializedName("cust_name")
private Long custName;
..........
remember to add one list of same class type like
#SerializedName("custname")
private List<Customer> customerList;
and generate getters and setters of that Customer class;
after this
parse your data like this
CustomerModel customerModel=gson.fromJson(json,Customer.class);
you get all your data in customerModel;
To access data just use list of that class.
List<Customer> customerList=customerModel.getCustomerList();
Log.v("APP_NAME",""+customerList.size());

Categories

Resources