How to get data from internet using JSON Object in android

Dear readers,

In android programming using the internet for the advanced functionality of our applications is one of steps towards  the advanced programming. Mostly or we can say that 90% of android applications are based on internet either directly or indirectly. So, in this article we are going to learn how to get internet permission from our mobile phones, how to download data from internet and how to show data in our mobile phone.

Getting internet permission :- In android if we want to access internet from mobile phones so first of all we will have get permission for the same from user i.e. phone.

First of all go to AndroidManifest.xml. Its path is “app -> src -> main -> AndroidManifest.xml”.

<uses-permission android:name=”android.permission.INTERNET” /> 

Write the above code in AndroidManifest.XML file either above of <application> tag or below </application> tag

This statement asks for the permission for the use of internet at the time of installation itself.

Layout for the app -: For this app initially we want just one Button and one MultiLine EditText. Button for downloading data and Multiline EditText for displaying the text i.e. downloaded data.

XML code of layout :-

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.rockfamily.ietperm.MainActivity">
    <EditText
        android:id="@+id/data"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"/>
    <Button
        android:id="@+id/btDownload"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Download
        android:layout_below="@+id/data"
        android:layout_centerHorizontal="true"
        android:onClick="down"/>
</RelativeLayout>

Java code for downloading and showing data in our app -:

package com.rockfamily.ietperm;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONObject;
import java.net.URI;
import java.net.URLConnection;
import java.util.Scanner;

public class MainActivity extends AppCompatActivity {
EditText data;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
data=(EditText)findViewById(R.id.data);
}
public void down(View v)
{
downloadData dd=new downloadData();
dd.execute();
}

/***********************************************************************************/

public class downloadData extends AsyncTask{
@Override
protected Object doInBackground(Object[] objects) {
String out=””;
try{
URI uri=new URI(“http://computer-programmers.in/profile.html”);
URLConnection co=uri.toURL().openConnection();
Scanner sc=new Scanner(co.getInputStream());
while (sc.hasNextLine()){
String ln=sc.nextLine();
out=out+ln+”\n”;
}
return out;
}
catch (Exception ex)
{
return ex;
}
}
@Override
public void onPostExecute(Object o){
super.onPostExecute(o);
try {
if (o instanceof Exception) {
throw (Exception) o;
}
String str=””+o;
JSONObject obj=new JSONObject(str);
JSONArray arr=obj.getJSONArray(“profile”);
JSONObject obj1=new JSONObject(arr.getString(0));
String data1=obj1.getString(“id”);
String data2=obj1.getString(“name”);
data.setText(data1+”\n”+data2);
}
catch (Exception ex)
{
Toast.makeText(MainActivity.this, ex.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
}

In above code we can see one extra class in within MainActivity.java.class named downloadData which extends AsyncTask class. On the click of the button down function is invoked and in that function downloadData class is called.
In that class there is a function named doInBackground() which does all the function in background i.e. in a seperate thread. If this is not done the our app may become irresponsive until the data gets downloaded from internet. Therefore we have to do the downloading function in background.
In that function URI stands for UniversalResourceIdentifier. URI accepts the website i.e. location from where data is to be downloaded. URL stands for UniformResourceLocator. We change URI to URL. After that we establlish connection from the server, of the given URL, by using URLConnection con=url.opeConnection();
Now we take the input  using Scanner class and store in a local variable and at the end we return that downloaded data.
After the data is returned class automatically calls its next functions named onPostExecute(). In this function we show the downloaded data in our multiline EditText. We use JSONObject to typecast the data JSONObject. JSONObjects basically has two parts  {“name:value”}. JSONArray further picks only the data part of that JSOObject whose name is given.We can JSONArray same as normal format of array. After taking the value part of the JSONObject we just show the data wherever we want (in our case it is EditText).

Leave a Reply