First Android App | Step 3 | Getting data from Server using AsyncTask JSON

Welcome back!! We are well on our way to building our first android app - a complete E-Commerce Application.

I assume you would have gone through Step 1 and Step 2 becoming coming here. If you haven't, please go through them as well.

In this step, we are trying to create the Splash screen for our Application, create database and tables and also fetch data from Server in JSON format through AsyncTask.

Please watch our video to get a detailed understanding of how the code works.



The source code is attached.

The RESTful API which is being called is http://lawgo.in/lawgo/city?format=json


JSONParser.java

package com.zing.basket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONException;
import org.json.JSONObject;

public class JSONParser {
    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";
 
    // constructor
    public JSONParser() {
 
    }
    
    public JSONObject getJSONFromUrl(String url) throws Exception {
      
     // Making HTTP request
      try {
          
         HttpParams httpParameters = new BasicHttpParams();
         int timeoutConnection = 20000;
         HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
         // Set the default socket timeout (SO_TIMEOUT) 
         // in milliseconds which is the timeout for waiting for data.
         int timeoutSocket = 25000;
      // defaultHttpClient
         DefaultHttpClient httpClient = new DefaultHttpClient();
         httpClient.setParams(httpParameters);
         //HttpPost httpPost = new HttpPost(url);
        HttpGet httpPost = new HttpGet(url);
         HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

          HttpResponse httpResponse = httpClient.execute(httpPost);
          
          HttpEntity httpEntity = httpResponse.getEntity();
          is = httpEntity.getContent();          
       
          
          /*HttpClient httpclient = new DefaultHttpClient();
          HttpPost httppost = new HttpPost(url);
          HttpResponse response = httpclient.execute(httppost);
          HttpEntity entity = response.getEntity();
          is = entity.getContent();*/

      } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
      } catch (ClientProtocolException e) {
          e.printStackTrace();
      } catch (IOException e) {
          e.printStackTrace();
      }
       
      try {
          BufferedReader reader = new BufferedReader(new InputStreamReader(
                  is, "iso-8859-1"), 8);
          StringBuilder sb = new StringBuilder();
          String line = null;
          while ((line = reader.readLine()) != null) {
              sb.append(line + "\n");
          }
          is.close();
          json = sb.toString();
          //Log.d("string","string is "+json);
      } catch (Exception e) {
          //Log.e("Buffer Error", "Error converting result " + e.toString());
      }

      // try parse the string to a JSON object
      try {
          jObj = new JSONObject(json);
      } catch (JSONException e) {
          //Log.e("JSON Parser", "Error parsing data " + e.toString());
      }

      // return JSON String
      return jObj;
  }
 
}


activity_start_screen.xml



 

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#B22222"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".StartScreen">

    <TextView
        android:id="@+id/SelectCityText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="107dp"
        android:gravity="center"
        android:text="@string/app_name"
        android:textColor="#F8F8FF"
        android:textSize="40sp"/>

<RelativeLayout>


StartScreen.java


package com.zing.basket;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ActionBar;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.widget.Toast;

public class StartScreen extends Activity {
 
    SQLiteDatabase sqLite;
 
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_start_screen);
  
 //initializing the action bar and hiding it. 
 ActionBar actionBar = getActionBar();
 actionBar.hide();
  
   
 //create a database if it doesnt exist, if it exists, it will open the database.
  
 sqLite=this.openOrCreateDatabase("basketbuddy", MODE_PRIVATE, null);
  
 sqLite.execSQL("CREATE TABLE IF NOT EXISTS USER (USER_ID VARCHAR,NAME VARCHAR,EMAIL VARCHAR)");
 sqLite.execSQL("CREATE TABLE IF NOT EXISTS CITY_LIST (ID INTEGER primary key autoincrement,CITY_NAME VARCHAR)" );
 sqLite.execSQL("CREATE TABLE IF NOT EXISTS USER_PREF (ID INTEGER primary key autoincrement,CITY_NAME VARCHAR default 'NONE', VOICE_ON VARCHAR, NOTIF VARCHAR)" );
 sqLite.execSQL("CREATE TABLE IF NOT EXISTS CHECKLIST (ID INTEGER primary key autoincrement, PRODUCT_NAME VARCHAR, PRODUCT_CHECKED VARCHAR)");
 sqLite.execSQL("CREATE TABLE IF NOT EXISTS PRODUCT_MASTER (ID INTEGER primary key autoincrement, PRODUCT_CODE INTEGER, PRODUCT_DIVISION INTEGER, PRODUCT_DEPARTMENT INTEGER"+ 
 "PRODUCT_GF INTEGER, PRODUCT_F INTEGER, PRODUCT_SUBF INTEGER, PRODUCT_NAME VARCHAR, PRODUCT_BARCODE INTEGER, PRODUCT_GRAMMAGE VARCHAR, PRODUCT_MRP INTEGER, PRODUCT_BBPRICE INTEGER)");
 sqLite.execSQL("CREATE TABLE IF NOT EXISTS CART (ID INTEGER primary key autoincrement, PRODUCT_CODE INTEGER, PRODUCT_DIVISION INTEGER, PRODUCT_DEPARTMENT INTEGER"+ 
 "PRODUCT_GF INTEGER, PRODUCT_F INTEGER, PRODUCT_SUBF INTEGER, PRODUCT_NAME VARCHAR, PRODUCT_BARCODE VARCHAR, PRODUCT_GRAMMAGE VARCHAR, PRODUCT_MRP INTEGER, PRODUCT_BBPRICE INTEGER, PRODUCT_QTY INTEGER, PRODUCT_VALUE INTEGER)");
  
 //call asynctask to fetch list of city to populate the dropdown. 
  
 updateList ul=new updateList();
 ul.execute();
  
    }
 
    class updateList extends AsyncTask<Void, Void, String>
    {
 JSONParser jParser;
 String url=new String();
  
 @Override
 protected void onPreExecute() {
    super.onPreExecute();
    url="http://lawgo.in/lawgo/city?format=json";
    jParser = new JSONParser();
 }
   
   
 @Override
 protected String doInBackground(Void... params) 
 {
     try
       {
  JSONObject json=jParser.getJSONFromUrl(url);
  Cursor sample;
  try 
  {
      JSONArray jar=json.getJSONArray("city");
        Log.d("arindam", ""+jar.length());
      
                    for(int i=0;i<jar.length();i++)
        {
      
   JSONObject j=jar.getJSONObject(i);
     
   //check if the city is already there in citylist.
   sample=sqLite.rawQuery("SELECT CITY_NAME FROM CITY_LIST WHERE CITY_NAME='"+j.getString("cityname")+"'",null);
   
   if(sample.moveToFirst())
   {
    continue;
   }
   else
   {
    sqLite.execSQL("insert into CITY_LIST (CITY_NAME) VALUES ('"+j.getString("cityname")+"')");
    Log.d("arindam",j.getString("cityname"));
   }
      
      }
  } catch (JSONException e) 
  {
      // TODO Auto-generated catch block
        return "perror";
  }
    
    }
    catch(Exception e)
    {
  e.printStackTrace();
  return "error";
    }
   
    return "success";
        }
  
 protected void onPostExecute(String result) 
 { 
    super.onPostExecute(result);
    if(result.equals("perror"))
    {
   moveTaskToBack(true);
   Toast.makeText(getApplicationContext(), "Error!!! Oops..that was humiliating. Could you please try again", Toast.LENGTH_LONG).show();
    }
    else if(result.equals("error"))
    {
   moveTaskToBack(true);
   Toast.makeText(getApplicationContext(), "Please Check your Internet Connection", Toast.LENGTH_LONG).show();
    }
    else
    {
   new Handler().postDelayed(new Runnable(){
   @Override
   public void run()
   {
        
    Cursor c=sqLite.rawQuery("SELECT CITY_NAME FROM USER_PREF",null); 
    Log.d("arindam" ,"c count"+c.getCount());
    if (c.getCount()== 0)
   {
     sqLite.execSQL("INSERT INTO USER_PREF (CITY_NAME, VOICE_ON, NOTIF) VALUES('NONE','Y','Y')");
   }
       
    
    Cursor d=sqLite.rawQuery("SELECT CITY_NAME FROM USER_PREF",null);
    Log.d("arindam" ,"d count"+d.getCount());
       
    if(d.moveToFirst())
    { 
     Log.d("arindam" ,"d NONE"+d.getString(0));
     if(d.getString(0).equals("NONE"))
        {
         //Intent intent=new Intent(StartScreen.this,CityScreen.class);
         //startActivity(intent);
        }
        else
        {
         //Intent intent=new Intent(StartScreen.this,HomeScreen.class);
         //startActivity(intent);
        }
     finish(); 
    }
      }
   },1000);
       }
     }
 }
 
 @Override
 protected void onPostCreate(Bundle savedInstanceState) {
  super.onPostCreate(savedInstanceState);
 }
 
 @Override
 public void onDestroy()
 {
  super.onDestroy();
  sqLite.close();
 }

}

AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.zing.basket"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="18" />
 
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.zing.basket.StartScreen"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        
    </application>
    

</manifest>





2 comments:

  1. if we want to fetch data from database how we can do that ? instead of server ..
    like if i want to change city name how can i do that

    ReplyDelete
    Replies
    1. That is very simple. Write a SQLite query to read all the rows from your city name table. Once read, populate the city names into the same ArrayList that we are populating the data from JSON. Rest all remains the same.

      Delete