web-dev-qa-db-ja.com

android)のSQLiteデータベースにJSONデータを挿入します

JSON配列のデータをSQLiteデータベースに挿入したいと思います。 Java応答を取得するために、CategoryHelper.JavaとAndroidJSONParsingActivity.Javaの2つのクラスを作成しました。コードを実行すると、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配列データをデータベースに挿入する方法や間違っている場所を教えてください。すべての応答はかなりです。

8
ADB

アクティビティのdatabaseHelperoncreateオブジェクトを使用する前に初期化するのを忘れています。

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

databaseHelperをインスタンス化することはありません。 nullオブジェクトでメソッドを呼び出すことはできません。

5

そして、ここでもう1つ小さな問題があります。

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

EXISTSの後にスペース文字を忘れました。次のようになります。

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