JsonParsing and Sqlite Database in Android

Introduction

This article explains the parsing of data and storing it in a SQLite database. Android Studio is used to create the sample.
JSON is the acronym for JavaScript Object Notation. JSON data is in two forms, one object data and another is array data that you need to parse to get the real data.

SQLite Database is an open source data base provided by every Android system. SQLite database is used to create, read and update a database in an Android system. To use the SQLite database you need to extend the SQLiteOpenHelper class. The SQLite open helper class provides the onCreate() and onUpgrade() methods to create an upgrade database.

Step 1


Create a project like this:

CreateProjectJsonParsing

Step 2

Create an XML file with this:

<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:paddingLeft="@dimen/activity_horizontal_margin"

    android:paddingRight="@dimen/activity_horizontal_margin"

    android:paddingTop="@dimen/activity_vertical_margin"

    android:paddingBottom="@dimen/activity_vertical_margin"

    tools:context=".MainActivity"

    android:background="#f610">

 

    <TextView

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:id="@+id/textView1"

        android:textStyle="bold"

        android:textColor="#ffffff"

        android:textSize="15dp"

        />

 

    <ListView

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:id="@+id/listView"></ListView>

 

 

</RelativeLayout>


Step 3

Create a Java class file with this:

package com.jsonparsingexample2;

import android.os.Bundle;

import android.app.Activity;

import android.view.Menu;

import android.widget.ArrayAdapter;

import android.widget.ListView;

import android.widget.TextView;

import org.json.JSONArray;

import org.json.JSONException;

import org.json.JSONObject;

 

import java.util.ArrayList;

 

public class MainActivity extends Activity {

 

   String ParsingDta= "{\"Employee\":[{\"id\":\"101\",\"name\":\"sonoo jaiswal\",\"salary\":\"50000\"},{\"id\":\"102\",\"name\":\"vimal jaiswal\",\"salary\":\"600000\"}]}";

   TextView textView1;

    ArrayList arrayList;

    String str="";

    ListView listView;

    Database database;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        database=new Database(this);

       // this.deleteDatabase("EmployeeDatabase.db");

        database.getWritableDatabase();

        textView1=(TextView)findViewById(R.id.textView1);

        listView=(ListView)findViewById(R.id.listView);

        try

        {

          JSONObject jsonObject=new JSONObject(ParsingDta);

          JSONArray jsonArray= jsonObject.getJSONArray("Employee");

          for(int i=0;i<jsonArray.length();i++)

          {

              JSONObject jsonObject1=jsonArray.getJSONObject(i);

              String id=jsonObject1.getString("id").toString();

              String name=jsonObject1.getString("name").toString();

              String salary=jsonObject1.getString("salary").toString();

              database.insertData(id,name,salary);

             str+="\n Employee"+i+ "\n name:"+name+"\n id:"+id+"\n salary:" +salary+"\n";

              //textView1.setText(str);

        }

    }

    catch(JSONException e)

    {

e.printStackTrace();

    }

        arrayList=database.fetchData();

        ArrayAdapter adapter=new ArrayAdapter(getApplicationContext(),android.R.layout.activity_list_item,android.R.id.text1,arrayList);

       listView.setAdapter(adapter);

    }

    @Override

    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.

        getMenuInflater().inflate(R.menu.main, menu);

        return true;

    }}


Step  4

Create another Java class file with this:

package com.jsonparsingexample2;

import android.content.ContentValues;

import android.content.Context;

import android.database.Cursor;

import android.database.sqlite.SQLiteDatabase;

import android.database.sqlite.SQLiteOpenHelper;

import android.util.Log;

import android.widget.ArrayAdapter;

 

import java.util.ArrayList;

 

/**

 * Created by vivek on 10/29/13.

 */

public class Database extends SQLiteOpenHelper {

 

    public Database(Context context)

    {

        super(context, "EmployeeDatabase.db", null, 1);

    }

    @Override

    public void onCreate(SQLiteDatabase db) {

    String tableEmp="create table emp(id text,name text,salary text)";

    db.execSQL(tableEmp);

    }

    @Override

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    public void insertData(String id,String name, String salary)

    {

        SQLiteDatabase sqLiteDatabase=this.getWritableDatabase();

        ContentValues values=new ContentValues();

        values.put("id",id);

        values.put("name",name);

        values.put("salary",salary);

        sqLiteDatabase.insert("emp",null,values);

    }

    public ArrayList fetchData()

    {

        ArrayList<String>stringArrayList=new ArrayList<String>();

        String fetchdata="select * from emp";

        SQLiteDatabase sqLiteDatabase=this.getReadableDatabase();

        Cursor cursor=sqLiteDatabase.rawQuery(fetchdata, null);

        if(cursor.moveToFirst()){

           do

            {

                stringArrayList.add(cursor.getString(0));

                stringArrayList.add(cursor.getString(1));

                stringArrayList.add(cursor.getString(2));

             } while (cursor.moveToNext());

        }

    return stringArrayList;

    }

}

 

Step  5

Android Manifest.xml file
 

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.jsonparsingexample2"

    android:versionCode="1"

    android:versionName="1.0" >

 

    <uses-sdk

        android:minSdkVersion="7"

        android:targetSdkVersion="16" />

 

    <application

        android:allowBackup="true"

        android:icon="@drawable/ic_launcher"

        android:label="@string/app_name"

        android:theme="@style/AppTheme" >

        <activity

            android:name="com.jsonparsingexample2.MainActivity"

            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>

Step  6

Fetch data stored in a SQLite Database:


JsonArrayData.jpg

Up Next
    Ebook Download
    View all
    Learn
    View all