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
Related
I am trying to export data from a PostgreSQL DB where the volume of data i have to export is near about 1 million. I have tried various approach but didn't get a solution for it.Even if i am using the postman for the calling the API , which i have written to export the csv, the postman is shutting down.I am using react.js to download the but there it is loading for hours. I am posting the code for the export
public String populateCsvReport(SearchDto searchDto){
List<DetailRecord> myDetailRecord = itsCustomRepo.getDetail(searchDto);
StringWriter sw = new StringWriter();
try(CSVPrinter csvPrinter = new CSVPrinter(sw,CSVFormat.DEFAULT.withHeader("Supplier Number"
"Supplier name"........
)){
myDetailRecord.forEach(mydetail->{
csvPrinter.printRecord(
mydetail.getSuplNum(),
mydetail.getSuplName(),
......................
)
});
return myDetailRecord;
Now Here i have also tried to change my code as
myDetailRecord.forEach(mydetail->{
mydetail.getSuplNum(),
mydetail.getSuplName(),
......................
});
csvPrinter.printRecord(
myDetailRecord
);
But it's didn't create an impact on my code.
And in my controller i am doing like
#Getmapping(path="/get-export-detail/csv"){
public RespnseEntity<String> generateMydetailExport(SearchDto searchDto){
return ResponseEntity.ok()
.header("Content-Disposition","attachment;fileName="+"myDetails.csv")
.contentType(MediaType.parseMediaType("text/csv"))
.body(callingService.populateCSVForDetail(searchDto));
And here i am using the react.js code to export the file
const exportOnClick=()=>{
callingDetailsService.export(param)
.then(response)=>{
let mime = "test/csv";
let fileName = "myDetail.csv";
util.downloadFile(response.data,fileName,mime);
Here is my custom repository Code
#Repository
public class ItsCustomRepo{
#PersistanceContext
private EntityManager entityManager;
public List<DetailRecord> getDetail(List<SearchCriteria> params){
List<DetailRecord> listOfDetail = new ArrayList<>();
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<DetailEntity> cQuery = cb.createQuery(DetailEntity.class);
Root<DetailEntity> rootE = cQuery.from(DetailEntity.class);
String sqlQuery = "select ............."
if(params.size()>0){
for(SearchCriteria param:params){
if(param.getValue()!=null && param.getValue()!=""){
if(param.getOperation().equalIgnoreCase(CriteriaOperationEnum.GREATER_THAN_OR_EQUAL.getOperation()){
if(rootE.get(param.getKey()).getJavaType()==LocalDate.class){
}else if(param.getOperation().equalIgnoreCase(CriteriaOperationEnum.LESS_THAN_OR_EQUAL.getOperation()
//some op
}else{ if(param.getOPeration().equalsIgnoreCase(CriteriaOperationEnum.LIKE.getOperation())){
//some op
}
}
Query query = entityManager.createNativeQuery(sqlQuery);
List<Object[]> objectList = query.getResultList();
int count = objectList.size();
objectList.forEach(glObject->{
DetailRecord detailRecord = DetailRecord.builder()
.supl_num(glObject[0])
...................
listOfDetail .add(detailRecord);
});
return listOfDetail;
My code is simple by i don't understand where it is getting failed, i am checking the count of the DB while running the Query and it is fast , and also i can see while debugging the code is smoothly coming to the controller but after that it is hanging for hours and hours.I have tried using opencsv,apache- poi etc. Can't understand where it is failing, someone please help me.
Here is some sample code that generates some CSV with two methods. The first one is similar to yours -- it gets all rows in a list and then creates csv. The second method is more "streaming" in that it writes out the rows as soon as it can get them from the database. With 1M rows, that makes a big difference.
import org.h2.jdbcx.JdbcDataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.List;
import java.util.function.Consumer;
public class CsvSample {
static class Player {
int id;
String name;
int teamId;
Player(int id, String name, int temId) {
this.id = id;
this.name = name;
this.teamId = temId;
}
}
interface PlayerRepo {
void save(Player player);
List<Player> findPlayers(int teamId);
int processPlayers(int teamId, Consumer<Player> callback);
}
static class SimplePlayerRepo implements PlayerRepo {
JdbcTemplate jdbc;
SimplePlayerRepo(JdbcTemplate jdbc) {
this.jdbc = jdbc;
this.jdbc.execute("create table if not exists Player(id int primary key, name varchar(30), team int)");
}
#Override
public void save(Player player) {
int n = jdbc.update(
"update Player set name=?, team=? where id=?",
player.name, player.teamId, player.id);
if (n == 0) {
jdbc.update(
"insert into Player(name, team, id) values (?, ?, ?)",
player.name, player.teamId, player.id);
}
}
#Override
public List<Player> findPlayers(int teamId) {
return jdbc.query(
"select id, name, team from Player where team=?",
(rs, n) -> new Player(rs.getInt(1), rs.getString(2), rs.getInt(3)),
teamId);
}
#Override
public int processPlayers(int teamId, Consumer<Player> callback) {
return jdbc.query(
"select id, name, team from Player where team=?",
rs -> {
int n = 0;
while (rs.next()) {
Player p = new Player(rs.getInt(1), rs.getString(2), rs.getInt(3));
callback.accept(p);
}
return n;
},
teamId);
}
}
public static void main(String[] args) throws Exception {
JdbcDataSource dataSource = new JdbcDataSource();
dataSource.setUrl("jdbc:h2:mem:csvsample;DB_CLOSE_DELAY=-1");
PlayerRepo repo = new SimplePlayerRepo(new JdbcTemplate(dataSource));
// add some players
repo.save(new Player(1, "Kobe", 1));
repo.save(new Player(2, "LeBron", 1));
repo.save(new Player(3, "Shaq", 1));
repo.save(new Player(4, "Kareem", 1));
repo.save(new Player(5, "Magic", 1));
repo.save(new Player(6, "Larry", 2));
repo.save(new Player(7, "Jason", 2));
// generate CSV from List
repo.findPlayers(1).forEach(player -> {
System.out.println(player.id + "," + player.name);
});
System.out.println("----");
// generate CSV with callback
repo.processPlayers(1, player -> {
System.out.println(player.id + "," + player.name);
});
}
}
So, in you case I would add a method to your repository class. It should contain all the logic from your getDetail method until you get to the line that says Query query = entityManager.createNativeQuery(sqlQuery);:
public int processSearchResults(List<SearchCriteria> params, Consumer<DetailRecord> callback){
// instead of this:
// Query query = entityManager.createNativeQuery(sqlQuery);
Session session = entityManager.unwrap(Session.class);
return session.doWork(new Work() {
#Override
public void execute(Connection connection) throws SQLException {
Statement stmt = connection.createQuery();
ResultSet rs = stmt.executeQuery(sqlQuery);
int n = 0;
while (rs.next()) {
DetailRecord detailRecord = DetailRecord.builder()
.supl_num(rs.getObject(1))
// .....
.build();
callback.accept(detailRecord);
n++;
}
rs.close();
stmt.close();
return n;
}
});
}
Then, your generateMydetailExport may look something like this:
#Getmapping(path="/get-export-detail/csv", produces="text/csv") {
public void generateMydetailExport(SearchDto searchDto, PrintWriter out) {
CSVPrinter csvPrinter = new CSVPrinter(out, CSVFormat.DEFAULT.withHeader("Supplier Number", /* ... */));
itsCustomRepo.processSearchResults(searchDto, detail -> {
csvPrinter.printRecord(
mydetail.getSuplNum(),
mydetail.getSuplName(),
// .....
);
});
}
I'm using an external sqlite database rather than creating one in my android studio project since the database will have some already populated data in it. But I have to insert some more data as well.
And when I insert any new data, it shows the new data but as I close my android app and open again to see the data, the newly inserted data through the app are somehow deleted, only prepopulated data are shown.
I am using DB browser for sqlite to create the external sqlite database and pre-populate it with some data there. In my android studio project, I added this database into my assets folder and implemented SQLiteOpenHelper class to access this database. Reading the data from the database table is a success. Now as I insert new data I can read the new data temporarily as well. Temporarily in the sense that after i close my app the new data are lost.
the table of my external sqlite database:
CREATE TABLE `table_name` (
`Id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
`Content` TEXT NOT NULL
);
SQLiteOpenHelper class:
public class ProcessExternalDBHelper {
private static final String DATABASE_NAME = "database_name.db";
private static final int DATABASE_VERSION = 1;
private static String DATABASE_PATH = "";
private static final String DATABASE_TABLE = "table_name";
private static final String KEY_ROWID = "Id";
private static final String KEY_CONTENT = "Content";
private ExternalDbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
private static class ExternalDbHelper extends SQLiteOpenHelper {
public ExternalDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
if (Build.VERSION.SDK_INT >= 17) {
DATABASE_PATH = context.getApplicationInfo().dataDir +
"/databases/";
} else {
DATABASE_PATH = "/data/data/" + context.getPackageName() +
"/databases/";
}
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int
newVersion) {
}
}
public ProcessExternalDBHelper(Context context) {
ourContext = context;
}
//for reading
public ProcessExternalDBHelper openRead() throws SQLException {
ourHelper = new ExternalDbHelper(ourContext);
ourDatabase = ourHelper.getReadableDatabase();
return this;
}
//for writing
public ProcessExternalDBHelper openWrite() throws SQLException{
ourHelper = new ExternalDbHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close() {
if (ourHelper != null) {
ourHelper.close();
}
}
//Create database in activity
public void createDatabase() throws IOException {
createDB();
}
//Create db if not exists
private void createDB() {
boolean dbExists = checkDatabase();
if (!dbExists) {
openRead();
try {
this.close();
copyDatabase();
} catch (IOException ie) {
throw new Error("Error copying database");
}
}
}
private boolean checkDatabase() {
boolean checkDB = false;
try {
String myPath = DATABASE_PATH + DATABASE_NAME;
File dbfile = new File(myPath);
checkDB = dbfile.exists();
} catch (SQLiteException e) {
}
return checkDB;
}
private void copyDatabase() throws IOException {
InputStream myInput = null;
OutputStream myOutput = null;
String outFileName = DATABASE_PATH + DATABASE_NAME;
try {
myInput = ourContext.getAssets().open(DATABASE_NAME);
myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
} catch (IOException ie) {
throw new Error("Copydatabase() error");
}
}
//To show all available contents in my database
public List<Model> findallContents() {
List<Model> mContents = new ArrayList<>();
String[] columns = new String[]{KEY_CONTENT};
Cursor cursor = ourDatabase.query(DATABASE_TABLE, columns, null, null,
null, null, null);
int iContent = cursor.getColumnIndex(KEY_CONTENT);
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext())
{
Model model= new Model();
model.setContent(cursor.getString(iContent));
mContents.add(model);
}
cursor.close();
return mContents;
}
public void addContent(String content) {
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_CONTENT, content);
ourDatabase.insert(DATABASE_TABLE, null, contentValues);
ourDatabase.close();
}
}
My Model.java class:
public class Model {
private String mContent;
public String getContent() {
return mContent;
}
public void setContent(String content) {
this.mContent = content;
}
}
Finally my activity class where i read and write the data:
public class MainActivity extends AppCompatActivity {
private EditText editText_Content;
private ImageButton imageButton_Save;
private List<Model> mContentsArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ProcessExternalDBHelper myDbHelper = new ProcessExternalDBHelper(this);
try {
myDbHelper.createDatabase();
} catch (IOException ioe) {
throw new Error("Unable to CREATE DATABASE");
} finally {
myDbHelper.close();
}
initialize();
GetContents();
imageButton_Save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!(editText_Content.getText().toString().trim().isEmpty()))
{
SaveContents();
}
}
});
}
private void initialize() {
editText_Content = findViewById(R.id.editText_contents);
imageButton_Save = findViewById(R.id.imageButton_save);
mContentsArrayList = new ArrayList<>();
}
//GetContents and show them later in my RecyclerView
private void GetContents() {
try {
mContentsArrayList.clear();
ProcessExternalDBHelper autoProcess = new
ProcessExternalDBHelper(this);
autoProcess.openRead();
mContentsArrayList.addAll(autoProcess.findallContents();
autoProcess.close();
} catch (Exception e) {
}
}
//For saving content into database
private void SaveContents() {
String content = editText_Content.getText().toString();
try {
ProcessExternalDBHelper autoProcess = new
ProcessExternalDBHelper(this);
autoProcess.openWrite(); //for writing into database
autoProcess.addContent(content);
autoProcess.close();
editText_Content.getText().clear();
} catch (Exception e) {
}
}
}
Finally I am using DB Browser for Sqlite (ver 3.10.1), android studio (ver 3.0.1), minSdkVersion 19.
I am expecting the newly inserted data into the database to be saved and later seen even when i close my app and and restart the app later. Thank You!
Your issue is that DATABASE_PATH isn't being reset and is therefore empty when createDatabase is invoked.
Therefore the check to see if the database exists fails to find the database (it's looking purely for the file database_db.db at the highest level of the file system, as such the file will not exist) and the database is copied overwriting the database that has data saved into it.
I'd suggest the following changes :-
private boolean checkDatabase() {
File dbfile = new File(ourContext.getDatabasePath(DATABASE_NAME).getPath());
if ( dbfile.exists()) return true;
File dbdir = dbfile.getParentFile();
if (!dbdir.exists()) {
dbdir.mkdirs();
}
return false;
}
This has the advantage that if the databases directory doesn't exist that it will be created and that it relies solely on the database name for the path.
There is also no need for the try/catch construct.
and optionally :-
private void copyDatabase() throws IOException {
InputStream myInput = null;
OutputStream myOutput = null;
String outFileName = ourContext.getDatabasePath(DATABASE_NAME).getPath(); //<<<<<<<<<< CHANGED
try {
myInput = ourContext.getAssets().open(DATABASE_NAME);
myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
} catch (IOException ie) {
throw new Error("Copydatabase() error");
}
}
Note if the above are applied there is no need for the SDK version check as the getDatabasePath method gets the correct path.
I try to use a sqlite database but the problem shows "no such table", the code works on some devices and some show that message.
class DatabaseHelper extends SQLiteOpenHelper {
private final String mDatabaseName;
private final Context mContext;
private final String mPath;
DatabaseHelper(Context context, String database, String path){
super(context,database,null,1);
this.mContext=context;
this.mDatabaseName=database;
this.mPath=path;
_createDatabase();
}
private void _createDatabase() {
if(_checkDatabase()){
return;
}
getReadableDatabase();
try {
_copyDatabase();
}catch (Exception e){
}
}
private void _copyDatabase() throws IOException {
InputStream inputStream = mContext.getAssets().open(mDatabaseName);
FileOutputStream fileOutputStream = new FileOutputStream(mPath+mDatabaseName);
byte[] bytes = new byte[1024];
do{
int n;
if((n=inputStream.read(bytes)) <= 0){
fileOutputStream.flush();
fileOutputStream.close();
return;
}
fileOutputStream.write(bytes,0,n);
}while (true);
}
private boolean _checkDatabase() {
return mContext.getDatabasePath(mDatabaseName).exists();
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
And database adapter look this
class DatabaseAdapter
{
private SQLiteDatabase database;
private DatabaseHelper databaseHelper;
DatabaseAdapter(Context context, String database, String path){
databaseHelper = new DatabaseHelper(context, database, path);
}
void open(){
try{
database = databaseHelper.getReadableDatabase();
}
catch (SQLiteException e)
{
database = databaseHelper.getReadableDatabase();
}
}
boolean isOpened()
{
return this.database != null && this.database.isOpen();
}
Cursor _get_rows()
{
Cursor cursor = database.rawQuery("SELECT * FROM rows ORDER BY RANDOM() LIMIT 4;", null);
cursor.moveToFirst();
return cursor;
}
}
And database controller look this
public class DatabaseController {
private static DatabaseAdapter databaseAdapter;
public static Cursor _get_rows()
{
if(!databaseAdapter.isOpened()){
databaseAdapter.open();
}
return databaseAdapter._get_rows();
}
public static void initilization(Context activity) {
String dbName= "data.db";
databaseAdapter = new DatabaseAdapter(activity.getApplicationContext(),dbName,"/data/data/"+activity.getApplicationInfo().packageName+"/databases/");
}
}
i use in activity like this
DatabaseController.initilization(this);
Cursor c = DatabaseController._get_rows();
I could not find a solution to this problem, the database was already copied to the entire directory
I suspect that the issues is that you are trapping an exception in :-
private void _createDatabase() {
if(_checkDatabase()){
return;
}
getReadableDatabase();
try {
_copyDatabase();
}catch (Exception e){
}
}
So processing continues and an empty database is created and hence no table.
The root cause might be that the databases directory might not exist. You need to look at the exception that has been trapped to determine the exact error. e.g. e.printStackTrace();
The following is how you could create the databases directory (to resolve the ENOENT (No such file or directory) exception that may be the issue) :-
e.g.
private void _copyDatabase() throws IOException {
File dir = new File(mPath); //<<<<<<<<<< ADDED
if(!dir.exists()) { //<<<<<<<<<< ADDED
dir.mkdirs(); //<<<<<<<<<< ADDED
} //<<<<<<<<<< ADDED
InputStream inputStream = mContext.getAssets().open(mDatabaseName);
FileOutputStream fileOutputStream = new FileOutputStream(mPath+mDatabaseName);
byte[] bytes = new byte[1024];
do{
int n;
if((n=inputStream.read(bytes)) <= 0){
fileOutputStream.flush();
fileOutputStream.close();
return;
}
fileOutputStream.write(bytes,0,n);
}while (true);
}
It is also inadvisable to hard code paths e.g. using :-
databaseAdapter = new DatabaseAdapter(activity.getApplicationContext(),dbName,"/data/data/"+activity.getApplicationInfo().packageName+"/databases/");
It's better to get the path using the Context's getDatabasePath method.
Note the code is in-principle code, it has not been tested or run and may therefore contain errors.
Note on the devices on which you have issues you will need to delete the database (Clear the App's data or uninstall the App) before running any amended code.
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.
.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.