Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert JSON data into the SQLite database in android

I want to insert the data from JSON array into the SQLite database. I have created two classes CategoryHelper.java and AndroidJSONParsingActivity.java to get the java response. When I run the code got the exception in databaseHelper.saveCategoryRecord(id,name); My API is working fine and giving me the data.

My code is below:

CategoryHelper.java

package com.androidhive.jsonparsing;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class CategoryHelper {
    private static final int DATABASE_VERSION = 2;
    private static final String DATABASE_NAME = "category.db";
    private static final String TABLE_NAME = "tbcategory";
    public static final String CATEGORY_COLUMN_ID = "_id";
    public static final String CATEGORY_COLUMN_NAME = "name";
    Category openHelper;
    private SQLiteDatabase database;

    public CategoryHelper(Context context){
        openHelper = new Category(context);
        database = openHelper.getWritableDatabase();
    }
    public void saveCategoryRecord(String id, String name) {
        ContentValues contentValues = new ContentValues();
        contentValues.put(CATEGORY_COLUMN_ID, id);
        contentValues.put(CATEGORY_COLUMN_NAME, name);
        database.insert(TABLE_NAME, null, contentValues);
        }
    public Cursor getTimeRecordList() {
        return database.rawQuery("select * from " + TABLE_NAME, null);
        }
    private class Category extends SQLiteOpenHelper {

        public Category(Context context) {
            // TODO Auto-generated constructor stub
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            // TODO Auto-generated method stub
            db.execSQL("CREATE TABLE " + TABLE_NAME + "( "
                    + CATEGORY_COLUMN_ID + " INTEGER PRIMARY KEY, "
                    + CATEGORY_COLUMN_NAME + " TEXT )" );

        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            // TODO Auto-generated method stub
            db.execSQL("DROP TABLE IF EXISTS"+ TABLE_NAME);
            onCreate(db);
        }

    }
}

AndroidJSONParsingActivity.java

package com.androidhive.jsonparsing;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class AndroidJSONParsingActivity extends ListActivity {

    // url to make request
    private static String url="API TO GET THE DATA";
    // JSON Node names
    private static final String TAG_CATEGORY = "categories";
    private static final String TAG_CATEGORY_ID = "category_id";
    private static final String TAG_NAME = "name";
    private static final String TAG_IS_ACTIVE = "is_active";
    // contacts JSONArray
    JSONArray contacts = null;
    private CategoryHelper databaseHelper;
    //private SQLiteDatabase mydatabase = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // Hashmap for ListView
        ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();

        // Creating JSON Parser instance
        JSONParser jParser = new JSONParser();

        // getting JSON string from URL
        JSONObject json = jParser.getJSONFromUrl(url);

        try {
            // Getting Array of Contacts
            contacts = json.getJSONArray(TAG_CATEGORY);

            // looping through All Contacts
            for(int i = 0; i < contacts.length(); i++){
                JSONObject c = contacts.getJSONObject(i);

                // Storing each json item in variable
                String id = c.getString(TAG_CATEGORY_ID);
                String name = c.getString(TAG_NAME);
                String  is_active = c.getString(TAG_IS_ACTIVE);

                databaseHelper.saveCategoryRecord(id,name);

                // creating new HashMap
                HashMap<String, String> map = new HashMap<String, String>();

                // adding each child node to HashMap key => value
                map.put(TAG_CATEGORY_ID, id);
                map.put(TAG_NAME, name);
                map.put(TAG_IS_ACTIVE, is_active);
                // adding HashList to ArrayList
                contactList.add(map);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }


        /**
         * Updating parsed JSON data into ListView
         * */
        ListAdapter adapter = new SimpleAdapter(this, contactList,
                R.layout.list_item,
                new String[] { TAG_NAME, TAG_IS_ACTIVE, TAG_CATEGORY_ID }, new int[] {
                        R.id.name, R.id.email, R.id.mobile });

        setListAdapter(adapter);

        // selecting single ListView item
        ListView lv = getListView();

        // Launching new screen on Selecting Single ListItem
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // getting values from selected ListItem
                String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
                String cost = ((TextView) view.findViewById(R.id.email)).getText().toString();
                String description = ((TextView) view.findViewById(R.id.mobile)).getText().toString();

                // Starting new intent
                Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
                in.putExtra(TAG_NAME, name);
                in.putExtra(TAG_IS_ACTIVE, cost);
                in.putExtra(TAG_CATEGORY_ID, description);
                startActivity(in);

            }
        });



    }

}

LOGCAT:

01-21 20:13:49.226: E/AndroidRuntime(301): FATAL EXCEPTION: main
01-21 20:13:49.226: E/AndroidRuntime(301): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.androidhive.jsonparsing/com.androidhive.jsonparsing.AndroidJSONParsingActivity}: java.lang.NullPointerException
01-21 20:13:49.226: E/AndroidRuntime(301):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
01-21 20:13:49.226: E/AndroidRuntime(301):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
01-21 20:13:49.226: E/AndroidRuntime(301):  at android.app.ActivityThread.access$2300(ActivityThread.java:125)
01-21 20:13:49.226: E/AndroidRuntime(301):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
01-21 20:13:49.226: E/AndroidRuntime(301):  at android.os.Handler.dispatchMessage(Handler.java:99)
01-21 20:13:49.226: E/AndroidRuntime(301):  at android.os.Looper.loop(Looper.java:123)
01-21 20:13:49.226: E/AndroidRuntime(301):  at android.app.ActivityThread.main(ActivityThread.java:4627)
01-21 20:13:49.226: E/AndroidRuntime(301):  at java.lang.reflect.Method.invokeNative(Native Method)
01-21 20:13:49.226: E/AndroidRuntime(301):  at java.lang.reflect.Method.invoke(Method.java:521)
01-21 20:13:49.226: E/AndroidRuntime(301):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
01-21 20:13:49.226: E/AndroidRuntime(301):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
01-21 20:13:49.226: E/AndroidRuntime(301):  at dalvik.system.NativeStart.main(Native Method)
01-21 20:13:49.226: E/AndroidRuntime(301): Caused by: java.lang.NullPointerException
01-21 20:13:49.226: E/AndroidRuntime(301):  at com.androidhive.jsonparsing.AndroidJSONParsingActivity.onCreate(AndroidJSONParsingActivity.java:65)
01-21 20:13:49.226: E/AndroidRuntime(301):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
01-21 20:13:49.226: E/AndroidRuntime(301):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)

Please guide me how can I insert the JSON array data into the database or where I am doing wrong. Every response is appreciable.

like image 506
ADB Avatar asked Jan 21 '13 15:01

ADB


People also ask

How do I insert a JSON file into SQLite?

The SQLite json_insert() function allows us to insert a new value into a JSON document. We pass the original JSON as the first argument when we call the function, followed by a path that specifies where to insert the new value, followed by the value to insert. We can also insert multiple key/value pairs if required.

Can we store JSON data in SQLite?

SQLite stores JSON as ordinary text. Backwards compatibility constraints mean that SQLite is only able to store values that are NULL, integers, floating-point numbers, text, and BLOBs. It is not possible to add a sixth "JSON" type. SQLite does not (currently) support a binary encoding of JSON.

Where do I put JSON files on Android?

Where to put assets folder and JSON file. You will need to create the assets folder inside src/main, together with java and res folder. Then put JSON file inside assets folder.


1 Answers

you forget to initialize databaseHelper object in oncreate of Activity before using it.

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        databaseHelper=new CategoryHelper(AndroidJSONParsingActivity.this);
        //your code here..........
like image 121
ρяσѕρєя K Avatar answered Oct 18 '22 14:10

ρяσѕρєя K