How to Call a Service using HTTP URL Connection Method






3.43/5 (7 votes)
In this tutorial, we are going to call a service using GET Method and populate sample JSON data in Recycler view without using any external library.
The Sample JSON
This is very simple JSON which gives us list of GAME OF THRONES details where each node contains some information like War Names, location, region, attacker king and defender king.
JSON Sample:-
[
{
"name": "Battle of the Golden Tooth",
"attacker_king": "Joffrey/Tommen Baratheon",
"defender_king": "Robb Stark",
"location": "Golden Tooth",
"region": "The Westerlands"
},
{
"name": "Battle at the Mummer's Ford",
"attacker_king": "Joffrey/Tommen Baratheon",
"defender_king": "Robb Stark",
"location": "Mummer's Ford",
"region": "The Riverlands"
}
]
You can get this JSON data by accessing:
URL: https://blogurl-3f73f.firebaseapp.com/
I am assuming that you have basic knowledge of JSON format.
Creating a New Project
Create a new project in Android Studio from File ⇒ New Project by filling the required details.
As we need to make network requests, we need to add INTERNET
permission in AndroidManifest.xml.
<uses-permission android:name="android.permission.INTERNET" />
Populating Data in Recycler View
To enable Recycler View & Card View element, you need to add the dependency in build.gradle file:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:25.1.0'
testCompile 'junit:junit:4.12'
compile 'com.android.support:cardview-v7:25.0.1'
compile 'com.android.support:recyclerview-v7:25.0.1'
}
Before making the http call, let’s add a button and RecyclerView
first in our Main Activity. Open the layout file of main activity (activity_main.xml) and add a Button
and RecyclerView
element.
<Button
android:id="@+id/btnCreateConnection"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Create Connection"/>
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
As we are getting the JSON by making HTTP call, I am adding an Async
class GetWarInfo
to make http calls on background thread. Add the following method in your main activity class.
In doInBackground()
method, HTTP_URL_CONNECTION_GET()
is called to get the json from URL. Once the json is fetched, it is parsed and each contact is added to array list.
Also note that I have used getJSONArray()
or getJSONObject()
method depending on the type of node.
package com.bytemachine.urlconnectionwithrecyclerview;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
// declaring variables
Button btnCreateConnection;
RecyclerView recyclerView;
List<ModelWarDetails> listWarDetails=new ArrayList<>();
RecyclerViewAdapter adapter;
LinearLayoutManager llm;
//onCreate calls when the application loads for the first time.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView= (RecyclerView) findViewById(R.id.recyclerView);
llm=new LinearLayoutManager(this);
recyclerView.setLayoutManager(llm);
btnCreateConnection= (Button) findViewById(R.id.btnCreateConnection);
//setting click event on Button
btnCreateConnection.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//executing Async task class to create HTTP connection
new FetchWarsInfo().execute();
}
});
}
/**
* Async task class to get json response by making HTTP call
* Async task class is used because
* you cannot create a network connection on main thread
*/
public class FetchWarsInfo extends AsyncTask<Void, Void, Void> {
ProgressDialog progressDialog;
static final String URL_STRING =
"https://blogurl-3f73f.firebaseapp.com/";
String response;
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setCancelable(false);
progressDialog.setMessage("Please wait. Fetching data..");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setProgress(0);
progressDialog.show();
}
@Override
protected Void doInBackground(Void... voids) {
/*
creatingURLConnection is a function use to establish connection
*/
response = creatingURLConnection(URL_STRING);
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
progressDialog.dismiss();
Toast.makeText(getApplicationContext(),
"Connection successful.",Toast.LENGTH_SHORT).show();
try{
if(response!=null && !response.equals("")){
/*
converting JSON response string into JSONArray
*/
JSONArray responseArray = new JSONArray(response);
if(responseArray.length()>0){
/*
Iterating JSON object from JSON Array one by one
*/
for(int i=0;i<responseArray.length();i++){
JSONObject battleObj = responseArray.getJSONObject(i);
//creating object of model class(ModelWarDetails)
ModelWarDetails modelWarDetails = new ModelWarDetails();
/*
fetching data based on key from JSON and setting into model class
*/
modelWarDetails.setName(battleObj.optString("name"));
modelWarDetails.setAttacker_king
(battleObj.optString("attacker_king"));
modelWarDetails.setDefender_king
(battleObj.optString("defender_king"));
modelWarDetails.setLocation(battleObj.optString("location"));
//adding data into List
listWarDetails.add(modelWarDetails);
}
//calling RecyclerViewAdapter constructor by passing context and list
adapter = new RecyclerViewAdapter(getApplicationContext(),listWarDetails);
//setting adapter on recyclerView
recyclerView.setAdapter(adapter);
// to notify adapter about changes in list data(if changes)
adapter.notifyDataSetChanged();
}
}else {
Toast.makeText(getApplicationContext(),
"Error in fetching data.",Toast.LENGTH_SHORT).show();
}
}catch (Exception e){
e.printStackTrace();
}
}
}
public String creatingURLConnection (String GET_URL) {
String response = "";
HttpURLConnection conn ;
StringBuilder jsonResults = new StringBuilder();
try {
//setting URL to connect with
URL url = new URL(GET_URL);
//creating connection
conn = (HttpURLConnection) url.openConnection();
/*
converting response into String
*/
InputStreamReader in = new InputStreamReader(conn.getInputStream());
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
jsonResults.append(buff, 0, read);
}
response = jsonResults.toString();
}catch(Exception e){
e.printStackTrace();
}
return response;
}
}
Create another layout file named list_war_details.xml with the following content. This will be used to render a single list item view.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:elevation="4dp"
android:layout_margin="8dp"
app:cardCornerRadius="4dp"
app:cardBackgroundColor="#FFFFFF"
android:id="@+id/layoutCard">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:padding="16dp">
<ImageView
android:layout_width="36dp"
android:layout_height="36dp"
android:id="@+id/imageView2"
android:src="@drawable/image_crown1"/>
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="8dp"
android:paddingRight="8dp"
android:paddingBottom="8dp"
android:paddingTop="8dp">
<TextView
android:text="TextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/txtName"
android:paddingTop="4dp"
android:paddingBottom="4dp"
android:textSize="18sp"
android:textColor="#000000" />
<TextView
android:text="TextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/txtLocation"
android:paddingBottom="4dp"
android:textSize="12sp" />
</LinearLayout>
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="0.1dp"
android:background="#d1d1d1"></View>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="8dp"
android:paddingBottom="8dp">
<TextView
android:text="Attacker King"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/txtAttackerKing"
android:layout_weight="1"
android:paddingTop="4dp"
android:paddingBottom="4dp" />
<TextView
android:text="Defender King"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/txtDefenderKing"
android:layout_weight="1"
android:gravity="right"
android:paddingBottom="4dp"
android:paddingTop="4dp" />
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
After adding the RecyclerView
widget, let’s start writing the adapter
class to render the data.
For that, you need to create a model class named ModelWarDetails.java and declare name
, location
, attacker_king
, defender_king
. Also, add the getter/setter methods to each variable.
Create a DAO (Data Access Object) commonly known as Modal
class named ModelWarDetails.java. Declare variables (name
, location
, attacker_king
and defender_king
) and generate getter and setter.
: You can generate getter and setter by pressing alt + insert.
package com.bytemachine.urlconnectionwithrecyclerview;
class ModelWarDetails {
private String name;
private String location;
private String attacker_king;
private String defender_king;
private String defender_king1;
String getName() {
return name;
}
void setName(String name) {
this.name = name;
}
String getLocation() {
return location;
}
void setLocation(String location) {
this.location = location;
}
String getAttacker_king() {
return attacker_king;
}
void setAttacker_king(String attacker_king) {
this.attacker_king = attacker_king;
}
String getDefender_king() {
return defender_king;
}
void setDefender_king(String defender_king) {
this.defender_king = defender_king;
}
}
Now create a class named RecyclerViewAdapter.java and add the below code. Here, onCreateViewHolder()
method inflates list_war_details.xml. In onBindViewHolder()
method, the appropriate war data (name
, location
, attacker_king
and defender_king
) set to each row.
The getItemCount()
method gives the size of the list.
package com.bytemachine.urlconnectionwithrecyclerview;
import android.content.Context;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
class RecyclerViewAdapter extends
RecyclerView.Adapter<RecyclerViewAdapter.ViewHolderWarDetails> {
// declaring variables
private Context context;
private List<ModelWarDetails> listWarDetails;
//constructor
RecyclerViewAdapter(Context context, List<ModelWarDetails> listWarDetails) {
this.context = context;
this.listWarDetails = listWarDetails;
}
@Override
public ViewHolderWarDetails onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.list_war_details,parent,false);
ViewHolderWarDetails viewHolderWarDetails = new ViewHolderWarDetails(view);
return viewHolderWarDetails;
}
@Override
public void onBindViewHolder(ViewHolderWarDetails holder, int position) {
//setting data on each row of list according to position.
holder.txtName.setText(listWarDetails.get(position).getName());
holder.txtLocation.setText(listWarDetails.get(position).getLocation());
holder.txtAttackerKing.setText(listWarDetails.get(position).getAttacker_king());
holder.txtDefenderKing.setText(listWarDetails.get(position).getDefender_king());
}
//returns list size
@Override
public int getItemCount() {
return listWarDetails.size();
}
class ViewHolderWarDetails extends RecyclerView.ViewHolder{
// declaring variables
TextView txtName, txtLocation, txtAttackerKing,txtDefenderKing;
CardView layoutCard;
ViewHolderWarDetails(View v) {
super(v);
txtName = (TextView) v.findViewById(R.id.txtName);
txtLocation = (TextView) v.findViewById(R.id.txtLocation);
txtAttackerKing = (TextView) v.findViewById(R.id.txtAttackerKing);
txtDefenderKing = (TextView) v.findViewById(R.id.txtDefenderKing);
layoutCard = (CardView) v.findViewById(R.id.layoutCard);
}
}
}
Now if you run the app, you can see the War Details displayed in a list manner.
Please feel free to contact me on bytemachines.inc@gmail.com.
Happy coding!