我正在尝试使用我的RAW 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文件在resources文件夹的raw文件夹中定义:
"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不会插入到这些列中。我为我的数据编写了ContentValues,但它们似乎无法正常运行。
我已经解决了这个问题已经好几天了,而且还没有能够提供解决方案,所以对此有所帮助会很棒!
答案 0 :(得分:1)
首先,在BugsDbHelper
的{{1}}中,代码为:
onCreate
应该是:
" 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);
我已经运行了上面的代码,但它确实有效。
希望它有所帮助。