JSON DATA FETCHING AND PARSING FROM URL ON ANDROID
While developing an Android app, some operations are required to pull data from the Internet. The way Android connects with its own Asynctask is very long and troublesome. We can messed up after a while. So i search and used this libraries for a long time and i decided the best few libraries are retrofit, volley and fuel for HTTP Networking.
Currently the best is the Square Inc. behind the retrofit, it's powerful. The volley is Google. But i will tell you that fuel.
What Will You Learn?
You will learn how to draw data from an API based on the model you prepared and parse it.
Requirements
- Internet Permission in Manifest File
- Add this lines in gradle
compile 'com.github.kittinunf.fuel:fuel-gson:1.12.1'
compile 'com.google.code.gson:gson:2.8.2'
Difficulty
It's so easy to retrofit and volley.
Basic for those who know the REST API and data extraction. Otherwise is Intermediate
Description
We will print this to the log by pulling data from a sample json URL. I will create a data model and describe the use of parameters and headers.
I used Fake Online REST API on jsonplaceholder that powered by JSON Server(github project link) and lowdb(github project link)
Video Tutorial
Tutorial
At the beginning of my article, I was connecting with the async task;
public class HttpGetRequest extends AsyncTask<String, Void, String> {
public static final String REQUEST_METHOD = "GET";
public static final int READ_TIMEOUT = 15000;
public static final int CONNECTION_TIMEOUT = 15000;
@Override
protected String doInBackground(String... params){
String stringUrl = params\[0\];
String result;
String inputLine;
try {
//Create a URL object holding our url
URL myUrl = new URL(stringUrl);
//Create a connection
HttpURLConnection connection =(HttpURLConnection)
myUrl.openConnection();
//Set methods and timeouts
connection.setRequestMethod(REQUEST_METHOD);
connection.setReadTimeout(READ_TIMEOUT);
connection.setConnectTimeout(CONNECTION_TIMEOUT);
//Connect to our url
connection.connect()
//Create a new InputStreamReader
InputStreamReader streamReader = new
InputStreamReader(connection.getInputStream());
//Create a new buffered reader and String Builder
BufferedReader reader = new BufferedReader(streamReader);
StringBuilder stringBuilder = new StringBuilder();
//Check if the line we are reading is not null
while((inputLine = reader.readLine()) != null){
stringBuilder.append(inputLine);
}
//Close our InputStream and Buffered reader
reader.close();
streamReader.close();
//Set our result equal to our stringBuilder
result = stringBuilder.toString();
}
catch(IOException e){
e.printStackTrace();
result = null;
}
return result;
}
protected void onPostExecute(String result){
super.onPostExecute(result);
}
}
The above code are quoted from Json
Cromer
It's very complicated. Therefore it makes more sense to use the following.
- First step is add the libraries in the above requirements.
- We will create a data class according to the json structure on the site is https://jsonplaceholder.typicode.com/posts
data class Post(val userId: Int, val id: Int, val title: String, val body: String){
class deserialize: ResponseDeserializable<Array<Post>>{
override fun deserialize(content: String): Array<Post> = Gson().fromJson(content, Array<Post>::class.java)
}
}
- Then call fuel class and we used ResponseObject to synchronize Post deserialize function in our post data class.
FuelManager.instance.baseParams = listOf("params" to "something")
"https://jsonplaceholder.typicode.com/posts".httpGet().responseObject(Post.deserialize()){
request, response, result ->
val (contents, error) = result
Log.e("responseLog", response.toString())
Log.e("requestLog", request.toString())
contents?.forEach { content ->
Log.d("result", "${content.id}= title: ${content.title}")
}
}
Posted on Utopian.io - Rewarding Open Source Contributors
@umutadali, I like your contribution to open source project, so I upvote to support you.
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
Your contribution cannot be approved because it is not as informative as other contributions. See the Utopian Rules. Contributions need to be informative and descriptive in order to help readers and developers understand them.
You can contact us on Discord.
[utopian-moderator]
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
I added description and extra information. Would you please check again?
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
IN video you had better talk in detail as much as possible .please keep that in mind .hope for your more contributions
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit