How to pass ArrayList to Local Database - java

I have my database created and parsed my xml to an arraylist to show in a listview. I am trying to save that arraylist to the database but the problem is I needed to tie the database to my Model and now it wants me to pass it the model when I need to pass it the ArrayList. I tried to change the addEmployee() method in the database to accept an ArrayList but then I am not able to get the getters from the model class to set the data.
I have been trying for a couple days and I am just completly stuck on how to get my parsed data to save into a SQLite database.
//Add new employee
public boolean addEmployee(Employee employee) {
SQLiteDatabase database = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ID, employee.getEmployee_number());
values.put(KEY_FIRST_NAME, employee.getFirst_name());
values.put(KEY_LAST_NAME, employee.getLast_name());
values.put(KEY_PHONE_NUMBER_MOBILE, employee.getPhone_mobile());
values.put(KEY_PHONE_NUMBER_OFFICE, employee.getPhone_office());
values.put(KEY_HAS_DIRECT_REPORTS, employee.getHas_direct_reports());
values.put(KEY_EMAIL, employee.getEmail());
values.put(KEY_COST_CENTER, employee.getCost_center_id());
//Inserting Row
database.insert(TABLE_EMPLOYEE, null, values);
database.close();
return true;
}
public void getXMLData() {
OkHttpClient client = getUnsafeOkHttpClient();
Request request = new Request.Builder()
.url(getString(R.string.API_FULL_URL))
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(Call call, final Response response) throws IOException {
final String responseData = response.body().string();
final InputStream stream = new ByteArrayInputStream(responseData.getBytes());
final XMLPullParserHandler parserHandler = new XMLPullParserHandler();
final ArrayList<Employee> employees = (ArrayList<Employee>) parserHandler.parse(stream);
mEmployees.clear();
mEmployees.addAll(employees);
DatabaseHandler databasehandler = new DatabaseHandler(getApplicationContext());
db = databasehandler.getWritableDatabase();
databasehandler.onCreate(db);
databasehandler.addEmployee(employees);
ArrayList<Employee> mTopList = databasehandler.getAllEmployees(); //this is empty
//tell adapter on the UI thread its data changed
runOnUiThread(new Runnable() {
#Override
public void run() {
mTopListViewAdapter.notifyDataSetChanged();
mBottomListViewAdapter.notifyDataSetChanged();
mMangerList.setVisibility(View.VISIBLE);
directReportListView.setVisibility(View.VISIBLE);
mProgressBar.setVisibility(View.GONE);
}
});
}
});
}

I tried to change the addEmployee() method in the database to accept an ArrayList but then I am not able to get the getters from the model class to set the data.
Don't you just need a loop?
final DatabaseHandler databasehandler = new DatabaseHandler(getApplicationContext());
final ArrayList<Employee> employees = (ArrayList<Employee>) parserHandler.parse(stream);
for (Employee e : employees) {
databasehandler.addEmployee(e);
}
If you really want to make a method with a list, same idea...
public boolean addEmployees(List<Employee> employees) {
SQLiteDatabase database = this.getWritableDatabase();
for (Employee e : employees) {
ContentValues values = new ContentValues();
values.put(KEY_ID, e.getEmployee_number());
...
database.insert(TABLE_EMPLOYEE, null, values);
}
database.close();
return true;
}
Tip Use a CursorAdapter if you want to show a SQLite database in a ListView, then you won't be shuffling an ArrayList in memory.

Related

I can't save DB file with MAPDB

I doing a project with GWT and use mapDB for DB. if I create a new object i can read it, but when close the project and restart I lost all data, I see that it never creates a file to save.
this is my code:
Method for create and add new object Student(e)
#Override
public void addStudent(String mail, String password) throws IllegalArgumentException {
Studente u = new Studente("G", "A", mail, password, "22-08-1999", 000001);
loadDB();
map.put(String.valueOf(map.size() + 1), u);
db.commit();
db.close();
}
Method for read data from DB
#Override
public void getStudents() {
loadDB();
Studente[] studenti = new Studente[map.size()];
int j = 0;
for( String i: map.getKeys()){
studenti[j] = map.get(i);
j++;
}
db.close();
}
Method loadDB
private void loadDB(){
this.db = getDb("studenti.db");
this.map = this.db.hashMap("studentiMap").counterEnable().keySerializer(Serializer.STRING).valueSerializer(new SerializerStudente()).createOrOpen();
}
Method getDB
private DB getDb(String nomeDB) {
ServletContext context = this.getServletContext();
synchronized (context) {
DB db = (DB)context.getAttribute("DB");
if(db == null){
db = DBMaker.fileDB(nomeDB).make();
context.setAttribute("DB", db);
}
return db;
}
}
Thanks you so much
P.s.
Sorry for my english

Fetching data from an API with JSON and storing two objects in a single row of an Array Adapter

I've got this code with fetches the "rate" data from an API, along with "rate", I need to get the "name". If I get "name" it often binds it below the "rate".
I need it to join on the same row of the List View, so it is like [Rate Name].
I need to get two objects of a JSON Array and bind it to the array adapter so I can display two objects in the same row of a List View so it is more user friendly.
The code below is of the AsyncTask, the code works fine but I need to add one more object and make sure it is displayed as one rate - one name and then iterating through the loop and adding more as needed in the same order.
public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
// the url of the web service to call
String yourServiceUrl = "eg: URL";
#Override
protected void onPreExecute() {
}
String filename = "bitData";
#Override
protected String doInBackground(String... arg0) {
try {
// create new instance of the httpConnect class
httpConnect jParser = new httpConnect();
// get json string from service url
String json = jParser.getJSONFromUrl(yourServiceUrl);
// parse returned json string into json array
JSONArray jsonArray = new JSONArray(json);
// loop through json array and add each currency to item in arrayList
//Custom Loop Initialise
for (int i = 1; i < 8; i++) {
JSONObject json_message = jsonArray.getJSONObject(i);
// The second JSONObject which needs to be added
JSONObject json_name = jsonArray.getJSONObject(i);
if (json_message != null) {
//add each currency to ArrayList as an item
items.add(json_message.getString("rate"));
String bitData = json_message.getString("rate");
String writeData = bitData + ',' +'\n';
FileOutputStream outputStream;
File file = getFileStreamPath(filename);
// first check if file exists, if not create it
if (file == null || !file.exists()) {
try {
outputStream = openFileOutput(filename, MODE_PRIVATE);
outputStream.write(writeData.getBytes());
outputStream.write("\r\n".getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// if file already exists then append bit data to it
else if (file.exists()) {
try {
outputStream = openFileOutput(filename, Context.MODE_APPEND);
outputStream.write(writeData.getBytes());
outputStream.write("\r\n".getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
// below method will run when service HTTP request is complete, will then bind text in arrayList to ListView
#Override
protected void onPostExecute(String strFromDoInBg) {
ListView list = (ListView) findViewById(R.id.rateView);
ArrayAdapter<String> rateArrayAdapter = new ArrayAdapter<String>(BitRates.this, android.R.layout.simple_expandable_list_item_1, items);
list.setAdapter(rateArrayAdapter);
}
}
Just Create Custom Class Messsage:
public class Item{
private String name;
private String rate;
public void Message(String n, String r){
this.name=n;
this.rate=r;
}
// create here getter and setter
}
Now in your background, you have to add name and rate in Message class
Public class MainAcitity extends Activity{
public static List<Item> items= new ArrayList<>();// define in inside the class
// this has to be down on background
Item i=new Item(json_message.getString("name"),json_message.getString("rate"));
items.add(i);
Now pass this listmessge onPostExecute :
ListView list = (ListView) findViewById(R.id.rateView);
ArrayAdapter<String> rateArrayAdapter = new ArrayAdapter<String>(BitRates.this, android.R.layout.simple_expandable_list_item_1, items);
list.setAdapter(rateArrayAdapter);
Is that any helpful for you.
Follow this link.You will get my point.
https://devtut.wordpress.com/2011/06/09/custom-arrayadapter-for-a-listview-android/

Initialized foreign key in dynamic table

.I start to write diet planner project and this is my database tables .I use external database and define tables foreign key there and copy it in asset folder and then connect it to my project.
standardUnit,Foods and standardFoodUnit are 3 tables which have static data and I filled them before,but EatenFood table is dynamically filled after Calculations.
I use model class and try to write databaseAdapter with androidhive database tutorial instruction.but because I started android recently I don't have any vision about it.
try to read book or online tutorial but they mixing up me more. now this is my question,I want to know for EatenFood table foreign key how can I put food-id value?I defined food_id INTEGER REFERENCES Foods ( _id ) in database before but in databaseAdapter class for insert or update or get function I don't know how can behave with this foreign key.
this is model class for EatenFood table
public class EatenFood {
int eatenfoodid;
boolean breakfast;
boolean lunch;
boolean snack;
boolean appetizers;
boolean dinner;
Data day;
String equivalent;
boolean dairy;
boolean vegetables;
boolean fruit;
boolean meat_bean_egg;
boolean bread_cereals;
boolean fat;
boolean suger;
double unitsum;
int food_id;
public boolean isAppetizers() {
return appetizers;
}
public void setAppetizers(boolean appetizers) {
this.appetizers = appetizers;
}
public Data getDay() {
return day;
}
public void setDay(Data day) {
this.day = day;
}
public double getUnitsum() {
return unitsum;
}
public void setUnitsum(double unitsum) {
this.unitsum = unitsum;
}
public int getFood_id() {
return food_id;
}
public void setFood_id(int food_id) {
this.food_id = food_id;
}
//all remaining getter and setter .........}
model class for food table
public class Foods {
int foodid;
String foodname;
boolean breakfast;
boolean lunch;
boolean snack;
boolean appetizers;
boolean dinner;
boolean mainfood;
boolean secondary;
public boolean isAppetizers() {
return appetizers;
}
public void setAppetizers(boolean appetizers) {
this.appetizers = appetizers;
}
public int getFoodid() {
return foodid;
}
public void setFoodid(int foodid) {
this.foodid = foodid;
}
//all remaining getter and setter .........}
DatabaseAdapter Functions
public class DatabaseAdapter {
private final String TAG = "DatabaseAdapter";
private DatabaseOpenHelper openHelper;
public Long insertEatenFood(EatenFood eatenfood) {
SQLiteDatabase myDataBase = null;
Long id = -1L;
try {
ContentValues values = new ContentValues();
values.put(TABLE_EATENFOOD_BREAKFAST, eatenfood.isBreakfast());
values.put(TABLE_EATENFOOD_LUNCH, eatenfood.isLunch());
values.put(TABLE_EATENFOOD_SNACK, eatenfood.isSnack());
values.put(TABLE_EATENFOOD_APPETIZERS, eatenfood.isAppetizers());
values.put(TABLE_EATENFOOD_DINNER, eatenfood.isDinner());
// values.put(TABLE_EATENFOOD_DATA, eatenfood.getDay().getClass());
values.put(TABLE_EATENFOOD_EQUIVALENT, eatenfood.getEquivalent());
values.put(TABLE_EATENFOOD_DAIRY, eatenfood.isDairy());
values.put(TABLE_EATENFOOD_VEGETABLES, eatenfood.isVegetables());
values.put(TABLE_EATENFOOD_FRUIT, eatenfood.isFruit());
values.put(TABLE_EATENFOOD_MEAT_BEAN_EGG,
eatenfood.isMeat_bean_egg());
values.put(TABLE_EATENFOOD_BREAD_CEREALS,
eatenfood.isBread_cereals());
values.put(TABLE_EATENFOOD_FAT, eatenfood.isFat());
values.put(TABLE_EATENFOOD_SUGER, eatenfood.isSuger());
values.put(TABLE_EATENFOOD_UNITSUM, eatenfood.getUnitsum());
myDataBase = openHelper.getWritableDatabase();
id = myDataBase.insert(TABLE_EATENFOOD, null, values);
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
} finally {
if (myDataBase != null && myDataBase.isOpen())
myDataBase.close();
}
return id;
}
// update EateanFood table =====================================================
public int updateEatenFood(EatenFood eatenfood) {
SQLiteDatabase myDataBase = null;
int count = -1;
try {
myDataBase = openHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(TABLE_EATENFOOD_BREAKFAST, eatenfood.isBreakfast());
values.put(TABLE_EATENFOOD_LUNCH, eatenfood.isLunch());
values.put(TABLE_EATENFOOD_SNACK, eatenfood.isSnack());
values.put(TABLE_EATENFOOD_APPETIZERS, eatenfood.isAppetizers());
values.put(TABLE_EATENFOOD_DINNER, eatenfood.isDinner());
// values.put(TABLE_EATENFOOD_DATA, eatenfood.getDay().getClass());
values.put(TABLE_EATENFOOD_EQUIVALENT, eatenfood.getEquivalent());
values.put(TABLE_EATENFOOD_DAIRY, eatenfood.isDairy());
values.put(TABLE_EATENFOOD_VEGETABLES, eatenfood.isVegetables());
values.put(TABLE_EATENFOOD_FRUIT, eatenfood.isFruit());
values.put(TABLE_EATENFOOD_MEAT_BEAN_EGG,
eatenfood.isMeat_bean_egg());
values.put(TABLE_EATENFOOD_BREAD_CEREALS,
eatenfood.isBread_cereals());
values.put(TABLE_EATENFOOD_FAT, eatenfood.isFat());
values.put(TABLE_EATENFOOD_SUGER, eatenfood.isSuger());
values.put(TABLE_EATENFOOD_UNITSUM, eatenfood.getUnitsum());
count = myDataBase
.update(TABLE_EATENFOOD, values, TABLE_EATENFOOD_ID + "=?",
new String[] { String.valueOf(eatenfood
.getEatenfoodid()) });
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
} finally {
myDataBase.close();
}
return count;
}
// Getting All EatenFood ================================================
public ArrayList<EatenFood> getEatenfoods() {
ArrayList<EatenFood> result = null;
SQLiteDatabase myDataBase = null;
Cursor cursor = null;
try {
myDataBase = openHelper.getWritableDatabase();
cursor = myDataBase.query(TABLE_EATENFOOD, new String[] { "*" }, null, null,
null, null, null);
if (cursor.moveToFirst()) {
result = new ArrayList<EatenFood>();
do {
result.add(extractEatenFood(cursor));
} while (cursor.moveToNext());
}
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
finally {
if (cursor != null) {
cursor.close();
}
myDataBase.close();
}
return result;
}
// extractEatenFood=============================================================
private EatenFood extractEatenFood(Cursor cursor){
EatenFood eatenfood = new EatenFood();
eatenfood.setEatenfoodid(cursor.getInt(cursor.getColumnIndex(TABLE_EATENFOOD_ID)));
eatenfood.setBreakfast(cursor.getInt(cursor.getColumnIndex(TABLE_EATENFOOD_BREAKFAST)) != 0);
eatenfood.setLunch(cursor.getInt(cursor.getColumnIndex(TABLE_EATENFOOD_LUNCH))!=0);
eatenfood.setSnack(cursor.getInt(cursor.getColumnIndex(TABLE_EATENFOOD_SNACK))!=0);
eatenfood.setAppetizers(cursor.getInt(cursor.getColumnIndex(TABLE_EATENFOOD_APPETIZERS))!=0);
eatenfood.setDinner(cursor.getInt(cursor.getColumnIndex(TABLE_EATENFOOD_DINNER))!=0);
// ???????????????????????? baraye day k sabt beshe
eatenfood.setEquivalent(cursor.getString(cursor.getColumnIndex(TABLE_EATENFOOD_EQUIVALENT)));
eatenfood.setDairy(cursor.getInt(cursor.getColumnIndex(TABLE_EATENFOOD_DAIRY))!=0);
eatenfood.setVegetables(cursor.getInt(cursor.getColumnIndex(TABLE_EATENFOOD_VEGETABLES))!=0);
eatenfood.setFruit(cursor.getInt(cursor.getColumnIndex(TABLE_EATENFOOD_FRUIT))!=0);
eatenfood.setBread_cereals(cursor.getInt(cursor.getColumnIndex(TABLE_EATENFOOD_BREAD_CEREALS))!=0);
eatenfood.setFat(cursor.getInt(cursor.getColumnIndex(TABLE_EATENFOOD_FAT))!=0);
eatenfood.setSuger(cursor.getInt(cursor.getColumnIndex(TABLE_EATENFOOD_SUGER))!=0);
eatenfood.setFood_id(cursor.getInt(cursor.getColumnIndex(TABLE_EATENFOOD_F_FOODID)));
return eatenfood ;
}
Whenever you want to add a food into you're eatenfood table. You have to call getFoodid function on you're specific food object and get the food_id and after that insert into database with insertEatenFood function in you're DatabaseAdapter class.
It's better you mention you're whole example of you're question that's makes it more easy to help you.
Maybe you got a problem about how can you find the food_id's that you want to insert into you're eatenfood table. It's better to write you're algorithms after that you find out which food_id's gonna be needed for you're different users.

Save HashMap data into SQLite

I'm Trying to save data from Json into SQLite. For now I keep the data from Json into HashMap.
I already search it, and there's said use the ContentValues. But I still don't get it how to use it.
I try looking at this question save data to SQLite from json object using Hashmap in Android, but it doesn't help a lot.
Is there any option that I can use to save the data from HashMap into SQLite?
Here's My code.
MainHellobali.java
// Hashmap for ListView
ArrayList<HashMap<String, String>> all_itemList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_helloballi);
all_itemList = new ArrayList<HashMap<String, String>>();
// Calling async task to get json
new getAllItem().execute();
}
private class getAllItem extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
all_item = new JSONArray(jsonStr);
// looping through All Contacts
for (int i = 0; i < all_item.length(); i++) {
JSONObject c = all_item.getJSONObject(i);
String item_id = c.getString(TAG_ITEM_ID);
String category_name = c.getString(TAG_CATEGORY_NAME);
String item_name = c.getString(TAG_ITEM_NAME);
// tmp hashmap for single contact
HashMap<String, String> allItem = new HashMap<String, String>();
// adding each child node to HashMap key => value
allItem.put(TAG_ITEM_ID, item_id);
allItem.put(TAG_CATEGORY_NAME, category_name);
allItem.put(TAG_ITEM_NAME, item_name);
// adding contact to contact list
all_itemList.add(allItem);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
}
I have DatabasehHandler.java and AllItem.java too.
I can put it in here if its necessary.
Thanks before
** Add Edited Code **
// looping through All Contacts
for (int i = 0; i < all_item.length(); i++) {
JSONObject c = all_item.getJSONObject(i);
String item_id = c.getString(TAG_ITEM_ID);
String category_name = c.getString(TAG_CATEGORY_NAME);
String item_name = c.getString(TAG_ITEM_NAME);
DatabaseHandler databaseHandler = new DatabaseHandler(this); //error here "The Constructor DatabaseHandler(MainHellobali.getAllItem) is undefined
}
As mentioned by #birdy you can just store the JSON data as String inside your database.
In my case I've already done the same thing you are trying to achieve, in my case I've just created an abstract datasource that will be extended for any JSON object I will set in my database.
But basically you just need a method to convert a JSONObject to a ContentValues object.
public ContentValues jsonToContentValues(JSONObject json) {
ContentValues values = new ContentValues();
values.put("MY_COLUMN", json.optString("MY_JSON_VALUE"));
return values;
}
After you have your content value object all set you just need to insert the values on your database.
return database.insert("MY_TABLE_NAME", null, contentValues);
If what you need is to store JSON data - just store it as a text. Than after taking it back from database you can again parse it into map.

Android, AsyncTask inside AsyncTask doInBackground

I have no idea how to solve problem, which I met while designing API for Android.
API must contain a method which will be able to get JSON Object from specific URL. So, I decide to put into the method AsyncTask to achieve that.
After execution method from this API I need populate a ListView, but I do not know how. As far as I know it is not possible to put AsyncTask( from method in my API) into other AsyncTask.
Any ideas, solutions, suggestions?
EDIT:
In the other words I want to create a method which will call restful services and get JSON.
This method will be executed (from other package) to populate ListView with the result.
My AsyncTask:
protected String doInBackground(HashMap<String,Boolean>... args)
{
JSONArray readings=null;
JSONObject json = getReadingsFromDB(args[0]);
try
{
int i;
readings = json.getJSONArray(TAG_READINGS);
for(i =0; i<readings.length();i++)
{
JSONObject ob = readings.getJSONObject(i);
ReadingH newReading = new ReadingH();
HashMap<String,String> map = new HashMap<String, String>();
String id;
String date;
String humidity;
String temp;
if(!ob.isNull(TAG_TEMPERATURE))
{
temp = ob.getString(TAG_TEMPERATURE);
newReading.setValue(TAG_TEMPERATURE, temp);
map.put(TAG_TEMPERATURE, temp);
}
if(!ob.isNull(TAG_ID))
{
id = ob.getString(TAG_ID);
newReading.setValue(TAG_ID, id);
map.put(TAG_ID, id);
}
if(!ob.isNull(TAG_DATE))
{
date = ob.getString(TAG_DATE);
map.put(TAG_DATE, date);
newReading.setValue(TAG_DATE, date);
}
if(!ob.isNull(TAG_HUMIDITY))
{
humidity= ob.getString(TAG_HUMIDITY);
map.put(TAG_HUMIDITY, humidity);
newReading.setValue(TAG_HUMIDITY, humidity);
}
readingsListH.add(newReading);
readingsList.add(map);
}
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String file_url)
{
// pDialog.dismiss();
a.runOnUiThread(new Runnable()
{
public void run()
{
ListAdapter adapter = new SimpleAdapter(
a,readingsList,
R.layout.reading_item,new String[]{TAG_ID,TAG_DATE,TAG_TEMPERATURE},
new int[]{R.id.ReadingID,R.id.ReadingDate,R.id.ReadingTemperature});
a.setListAdapter(adapter);
}
});
}
doInBackground will be in my new method, but code from onPostExecute will be there where new method will be executed.
Regards

Categories

Resources