将JSON数据插入到android中的SQLite数据库中

时间:2013-01-21 15:02:32

标签: android json sqlite android-sqlite sqliteopenhelper

我想将JSON数组中的数据插入到SQLite数据库中。我创建了两个类CategoryHelper.java和AndroidJSONParsingActivity.java来获取java响应。当我运行代码时,在databaseHelper.saveCategoryRecord(id,name);我的API工作正常,并向我提供数据。

我的代码如下:

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)

请指导我如何将JSON数组数据插入数据库或我做错了。每一个回应都是可观的。

3 个答案:

答案 0 :(得分:13)

在使用之前,您忘记在databaseHelper的Activity中初始化oncreate对象。

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        databaseHelper=new CategoryHelper(AndroidJSONParsingActivity.this);
        //your code here..........

答案 1 :(得分:5)

您永远不会实例化databaseHelper。您无法在null对象上调用方法。

答案 2 :(得分:4)

你还有一个小问题:

db.execSQL("DROP TABLE IF EXISTS"+ TABLE_NAME);

EXISTS之后你忘记了空格。它应该是这样的:

db.execSQL("DROP TABLE IF EXISTS "+ TABLE_NAME);