8

我想将 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);

            }
        });



    }

}

日志猫:

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 数组数据插入数据库或我做错了什么。每一个反应都是可观的。

4

3 回答 3

13

你忘记在使用它之前初始化 ActivitydatabaseHelper中的对象。oncreate

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        databaseHelper=new CategoryHelper(AndroidJSONParsingActivity.this);
        //your code here..........
于 2013-01-21T15:06:55.120 回答
5

你永远不会实例化databaseHelper. 您不能在空对象上调用方法。

于 2013-01-21T15:06:37.447 回答
4

这里还有一个小问题:

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

EXISTS 后您忘记了空格字符。它应该看起来像这样:

db.execSQL("DROP TABLE IF EXISTS "+ TABLE_NAME);
于 2014-05-23T17:30:57.717 回答