ContentValue对未从RAW JSON中插入SQLite数据库



我正在尝试将我的原始json文件插入我的表名称 insectsTable

这是我在BugsContract类中定义了我的列名称的地方:

import android.provider.BaseColumns;
/**
 * Created by man on 9/19/2017.
 */
public class BugsContract
{
    public static final class BugEntry implements BaseColumns
    {
        public static final String TABLE_NAME = "insectTable";
        public static final String COLUMN_NAME = "friendlyName";
        public static final String COLUMN_SCIENTIFIC = "scientificName";
        public static final String COLUMN_CLASS = "classification";
        public static final String COLUMN_IMAGE = "imageAsset";
        public static final String COLUMN_DANGER = "dangerLevel";
    }
}

在我的bugsdbhelper类中定义如下:

import android.content.ContentValues;
import android.content.Context;
import android.content.res.Resources;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.google.developer.bugmaster.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
/**
 * Database helper class to facilitate creating and updating
 * the database from the chosen schema.
 */
public class BugsDbHelper extends SQLiteOpenHelper
{
    private static final String TAG = BugsDbHelper.class.getSimpleName();
    private static final String DATABASE_NAME = "insect.db";
    private static final int DATABASE_VERSION = 1;
    //Used to read data from res/ and assets/
    private Resources mResources;
    Context context;
    SQLiteDatabase db;

    public BugsDbHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        mResources = context.getResources();
        db = this.getWritableDatabase();
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE "+BugsContract.BugEntry.TABLE_NAME+" ("+ BugsContract.BugEntry._ID + " INTEGER AUTOINCREMENT"+BugsContract.BugEntry.COLUMN_NAME+" TEXT, "
        + BugsContract.BugEntry.COLUMN_SCIENTIFIC + " TEXT," + BugsContract.BugEntry.COLUMN_CLASS+" TEXT,"+
        BugsContract.BugEntry.COLUMN_IMAGE + " TEXT," + BugsContract.BugEntry.COLUMN_DANGER + " INTEGER);");
        Log.d(TAG, "Database created successfully");
        try
        {
            readInsectsFromResources(db);
        } catch(IOException e)
        {
            e.printStackTrace();
        } catch(JSONException e)
        {
            e.printStackTrace();
        }
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + BugsContract.BugEntry.TABLE_NAME);
        onCreate(db);
    }

    private String readJsonDataFromFile() throws IOException
    {
        InputStream inputStream = null;
        StringBuilder builder = new StringBuilder();
        try
        {
            String jsonDataString = null;
            inputStream = mResources.openRawResource(R.raw.insects);
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            while((jsonDataString = bufferedReader.readLine()) != null)
            {
                builder.append(jsonDataString);
            }
        }finally
        {
            if(inputStream != null)
            {
                inputStream.close();
            }
        }
        Log.d("Suck", builder.toString());
        return new String(builder);
    }
    /**
     * Streams the JSON data from insect.json, parses it, and inserts it into the
     * provided {@link SQLiteDatabase}.
     *
     * @param db Database where objects should be inserted.
     * @throws IOException
     * @throws JSONException
     */
    private void readInsectsFromResources(SQLiteDatabase db) throws IOException, JSONException
    {
        try {
            final String NAME            = "friendlyName";
            final String SCIENTIFIC_NAME = "scientificName";
            final String CLASSIFICATION  = "classification";
            final String IMAGE_ASSET     = "imageAsset";
            final String DANGER_LEVEL    = "dangerLevel";
            //Parse resource into key/values
            final String rawJson = readJsonDataFromFile();
            JSONArray j_array = new JSONArray(rawJson);
            for (int i = 0; i < j_array.length(); ++i) {
                String friendlyName;
                String scientificName;
                String classification;
                String image;
                int dangerLevel;
                JSONObject jsonObj = j_array.getJSONObject(i);
                friendlyName = jsonObj.getString(NAME);
                scientificName = jsonObj.getString(SCIENTIFIC_NAME);
                classification = jsonObj.getString(CLASSIFICATION);
                image = jsonObj.getString(IMAGE_ASSET);
                dangerLevel = jsonObj.getInt(DANGER_LEVEL);
                ContentValues contentValues = new ContentValues();
                contentValues.put(BugsContract.BugEntry.COLUMN_NAME, friendlyName);
                contentValues.put(BugsContract.BugEntry.COLUMN_SCIENTIFIC, scientificName);
                contentValues.put(BugsContract.BugEntry.COLUMN_CLASS, classification);
                contentValues.put(BugsContract.BugEntry.COLUMN_IMAGE, image);
                contentValues.put(BugsContract.BugEntry.COLUMN_DANGER, dangerLevel);
                db.insert(BugsContract.BugEntry.TABLE_NAME, null, contentValues);
                Log.d(TAG, "Inserted successfully" + contentValues);
            }
        }catch(Exception e)
        {
            Log.e(TAG, e.getMessage(), e);
            e.printStackTrace();
        }
    }
}

,我的json文件在资源文件夹中的原始文件夹中定义:

"insects": [
    {
      "friendlyName": "Black Widow",
      "scientificName": "Latrodectus mactans",
      "classification": "Arachnida",
      "imageAsset": "spider.png",
      "dangerLevel": 10
    },
    {
      "friendlyName": "Brown Recluse",
      "scientificName": "Loxosceles reclusa",
      "classification": "Arachnida",
      "imageAsset": "spider.png",
      "dangerLevel": 10
    },

上面只是JSON的一个样本。每次我运行程序时,数据库和表和表的列都会成功创建,但是JSON并未插入这些列中。我为我的数据写了contentValue,但它们似乎不起作用。

我已经处理了几天的问题,并且无法提供解决方案,所以帮忙!

首先,在BugsDbHelperonCreate中,代码:

" INTEGER AUTOINCREMENT"

应该是:

" INTEGER PRIMARY KEY AUTOINCREMENT,"

请不要忘记将,终于。

那么JSON文件可能是这样的:

{
    "insects": [
        {
            "friendlyName": "BlackWidow",
            "scientificName": "Latrodectusmactans",
            "classification": "Arachnida",
            "imageAsset": "spider.png",
            "dangerLevel": 10
        },
        {
            "friendlyName": "BrownRecluse",
            "scientificName": "Loxoscelesreclusa",
            "classification": "Arachnida",
            "imageAsset": "spider.png",
            "dangerLevel": 10
        }
    ]
}

readInsectsFromResources中,代码:

JSONArray j_array = new JSONArray(rawJson);

应该是:

JSONObject rawJSONObject = new JSONObject(rawJson);
JSONArray j_array = rawJSONObject.getJSONArray("insects");

我已经运行了上面的代码,并且有效。

希望它有帮助。

最新更新