Reputation: 71
I'm trying to parse a JSON Array in my Android App with some URLs in it to load into my SQLite DB, here is the code:
JSONArray pics = json.getJSONArray("bilder");
Gson gson = new Gson();
String obj = gson.toJson(pics);
String SQLiteDataBaseQuery = "INSERT INTO images_table (id,desc,imgurl) VALUES('"+i+"', '"+jr_desc+"', '"+obj+"');";
sqLiteDatabase.execSQL(SQLiteDataBaseQuery);
Reading out the DB with the Emulator I can see the String {"values":[URLS here]}. Is it normal that GSON writes this "values" in front of my String List?
So, now I want to call the information from my DB:
Cursor cursor;
Array_links = new ArrayList<String>();
SQLiteGallery sqLiteHelper;
SQLiteDatabase sqLiteDatabase;
sqLiteHelper = new SQLiteGallery(this);
sqLiteDatabase = sqLiteHelper.getWritableDatabase();
cursor = sqLiteDatabase.rawQuery("SELECT * FROM "+SQLiteGallery.TAB_NAME+"", null);
cursor.moveToPosition(0);
Array_links.add(cursor.getString(cursor.getColumnIndex(SQLiteGallery.table_imgurl)));
Gson gson = new Gson();
Type type = new TypeToken<List<String>>().getType();
List<String> img_urls = gson.fromJson(Array_links,type);
for(String url : img_urls)
{
System.out.println(url);
}
Android Studio gives me the following error:
TypeToken has protected access in 'com.google.gson.reflect.TypeToken'
What does that mean? Is my code wrong?
Thank you
Correct Code here:
Cursor cursor;
String urls;
SQLiteGallery sqLiteHelper;
SQLiteDatabase sqLiteDatabase;
sqLiteHelper = new SQLiteGallery(this);
sqLiteDatabase = sqLiteHelper.getWritableDatabase();
cursor = sqLiteDatabase.rawQuery("SELECT * FROM
"+SQLiteGallery.TAB_NAME+"", null);
cursor.moveToPosition(0);
urls =
cursor.getString(cursor.getColumnIndex(SQLiteGallery.table_imgurl));
Gson gson = new Gson();
Type type = new TypeToken<List<String>>(){}.getType();
List<String> img_urls = gson.fromJson(urls,type);
for(String url : img_urls)
{
System.out.println(url);
}
Error: Unable to start activity ComponentInfo{...}: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
Upvotes: 0
Views: 4006
Reputation: 29794
You're forgetting the {}
, your code is:
Type type = new TypeToken<List<String>>().getType();
It should be:
Type type = new TypeToken<List<String>>(){}.getType();
Upvotes: 2