Hello Everyone I am newbie in Android, I need to parse json object and display it in listView and at the same time to save those data in SQLite, but whenever I run the project exception is caught ... the database is created without any data or value in it.
here is the code by which I am trying:
Bundle bundle = getIntent().getExtras();
String rfiItems = bundle.getString("allData");
final ArrayList<HashMap<String, String>> mylist4 = new ArrayList<HashMap<String, String>>();
try{
JSONObject jObj = new JSONObject(rfiItems);
JSONArray data4 = jObj.getJSONArray("data");
//data4 = json4.getJSONArray("data");
//Toast.makeText(getApplicationContext(), data4.toString(), Toast.LENGTH_LONG).show();
for(int i=0;i<data4.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = data4.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("rfi_data1", "" + e.getString("country"));
map.put("rfi_data4", "" + e.getString("state"));
map.put("rfi_data5", "" + e.getString("city"));
map.put("rfi_data6", "" + e.getString("name"));
map.put("rfi_data7", "" + e.getString("about"));
DatabaseHelper databaseHelper = new DatabaseHelper(this);
SQLiteDatabase db = databaseHelper.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(DatabaseHelper.COUNTRY, e.getString("country"));
cv.put(DatabaseHelper.CITY, e.getString("state"));
cv.put(DatabaseHelper.STATE, e.getString("city"));
cv.put(DatabaseHelper.NAME, e.getString("name"));
cv.put(DatabaseHelper.ABOUT, e.getString("about"));
db.insert("Baranzan", DatabaseHelper.COUNTRY, cv);
db.close();
mylist4.add(map);
}
}catch(JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
ListAdapter adapter4 = new SimpleAdapter(this, mylist4 , R.layout.item_list4,
new String[] { "rfi_data1", "rfi_data4","rfi_data5","rfi_data6","rfi_data7"},
new int[] { R.id.rfi_item_type, R.id.rfi_status,R.id.rfi_title,R.id.rfi_change_date,R.id.rfi_responded_date });
setListAdapter(adapter4);
and databaseclass code:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "myonlydb.db";
public static final String ID = "id";
public static final String COUNTRY = "country";
public static final String STATE = "state";
public static final String CITY = "city";
public static final String NAME = "name";
public static final String ABOUT = "about";
public static final String TAG = "Form"; // optional
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE mytable (_id INTEGER PRIMARY KEY AUTOINCREMENT, country TEXT, state TEXT, city TEXT, name TEXT, about TEXT, );");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
android.util.Log.v("mytable", "Upgrating database will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS mytable");
onCreate(db);
}
Any help will really be appreciated , THANKS A LOT