Initialized foreign key in dynamic table - java

.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.

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

Is that possible to save String arraylist inside class through internal storage?

I am writing an note app and trying to save String arraylist in internalstorage and it doesn't seems to work
The user is creating and editing a table and i'm trying to save the content in arraylist, which just doesn't work.
Someone know
I created an class which i save as a ".bin" file
the function that suppose to store the arraylists:
ArrayList<String> tableLayoutBcontent=new ArrayList<>();
ArrayList<String> tableLayoutCcontent=new ArrayList<>();
ArrayList<String> tableLayoutDcontent=new ArrayList<>();
TableRow tableRow1=(TableRow)tableLayoutB.getChildAt(0);
EditText editText, editText1;
int tableCellsCountD=0;
for(int i=0;i<tableColumnCountB;i++){
editText1= (EditText) tableRow1.getChildAt(i).getTag();
tableLayoutBcontent.add(editText1.getText().toString());
for(int j=0;j<tableRowCountC;j++) {
tableRow= (TableRow)tableLayoutD.getChildAt(j);
Log.d("In create table", "number of rows and columns"+tableColumnCountB + i + j);
Log.d("In create table", "number of child counts"+tableRow.getChildCount()+tableRow1.getChildCount());
editText=(EditText)tableRow.getChildAt(i).getTag();
Log.d("In create table", "Content"+editText.getText().toString());
tableLayoutDcontent.add(editText.getText().toString());
tableCellsCountD++;
}
}
for(int i=0;i<tableRowCountC;i++){
tableRow=(TableRow)tableLayoutC.getChildAt(i);
editText=(EditText)tableRow.getChildAt(0).getTag();
tableLayoutCcontent.add(editText.getText().toString());
}
Table table= new Table(TableTitle, tableLayoutAcontent, tableLayoutBcontent, tableLayoutCcontent, tableLayoutDcontent, tableRowCountC, tableColumnCountB);
Log.d("In get table layout", "Check");
return table;
}
the function that supposed to restore the arraylists:
public void setTableLayoutData(Table table){
Title.setText(TableTitle);
TableLayoutBcontent= table.getTableLayoutBcontent();
TableLayoutCcontent= table.getTableLayoutCcontent();
TableLayoutDcontent= table.getTableLayoutDcontent();
InitialColumnsNumber = table.getColumnsNumber();
InitialRowsNumber = table.getRowsNumber();
for(int i = 0; i< InitialColumnsNumber; i++){
addColumnsToTableB(TableLayoutBcontent.get(i),i);
Log.d("Check content", "TablelayoutB content:" + TableLayoutBcontent.get(i));
}
for(int i = 0; i< InitialRowsNumber; i++){
initializeRowForTableD(i);
addRowToTableC(TableLayoutCcontent.get(i));
Log.d("Check content", "TablelayoutC content:" + TableLayoutCcontent.get(i));
for (int j = 0; j< InitialColumnsNumber; j++){
addColumnToTableD(i, TableLayoutDcontent.get(i));
}
}
}```
and the function that save the table:
public void SaveTable(){
Table table=getTableLayoutData();
Idea idea=Utilities.getIdea(IdeaTitle);
if(table!=null) {
Log.d("Idea'S title", IdeaTitle);
idea.AddTable(table);
}
if(Utilities.SaveIdea(this, idea)){
Toast.makeText(this, "Your table is saved in your idea", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(this, "your table couldn't be saved for some reason", Toast.LENGTH_SHORT).show();
}
}
I expect it store the content and it just doesn't work,
anybody can try to help me with it?
edit:
Idea class code:
public class Idea implements Serializable{
private long Date;
private String Title;
private String Content;
private ArrayList<Table> Tables;
public Idea(long date, String title, String content) {
Date = date;
Title = title;
Content = content;
Tables=new ArrayList<>();
}
public Idea(long date, String title, String content, ArrayList<Table> tables) {
Date = date;
Title = title;
Content = content;
Tables = tables;
}
public long getDate() {
return Date;
}
public String getTitle() {
return Title;
}
public String getContent() {
return Content;
}
public void setDate(long date) {
Date = date;
}
public void setTitle(String title) {
Title = title;
}
public void setContent(String content) {
Content = content;
}
public ArrayList<Table> getTables() {
return Tables;
}
public void setTables(ArrayList<Table> tables) {
Tables = tables;
}
public void AddTable(Table table){
Tables.add(table);
Log.d("TablesCount", "tables count is "+Tables.size());
}
public Table getTable(String title){
for (int i=0;i<Tables.size();i++){
Log.d("Table name", Tables.get(i).getTitle());
if(title.equals(Tables.get(i).getTitle())){
return Tables.get(i);
}
}
return null;
}
public String getTableTitle(int i){
if(Tables.size()>i){
return Tables.get(i).getTitle();
}
return null;
}
public boolean hasTable(){
Log.d("hasTables", "TablesCount is "+Tables.size());
return Tables.size() != 0;
}
public int getTablesCount(){
return Tables.size();
}
}
Utillities.saveIdea code:
public static boolean SaveIdea(final Context context, final Idea idea){
final String FileName=String.valueOf(idea.getTitle()+".bin");
FileOutputStream fos;
ObjectOutputStream oos;
try {
fos = context.openFileOutput(FileName, Context.MODE_PRIVATE);
oos = new ObjectOutputStream(fos);
oos.writeObject(idea);
Log.d("in save idea", "in try");
oos.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
Log.d("in save idea", "in catch");
Toast.makeText(context, "file wasn't saved, please check if you have enough storage space left on your device", Toast.LENGTH_SHORT).show();
return false;
}
return true;
}

data inserted into external sqlite database but not saving in android studio

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.

compare a string with a database column's values

I am developing an app in which i have a profiles list which is stored in a database containing too many profiles,the problem is that when i save a new profile, the app must have to check the profile is already exist or not....how to do that
mSaveProfile.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
CProfileDataSource m_profileDataSource = new CProfileDataSource(CAddNewProfileActivity.this);
_profile = mProfileName.getText().toString();
if (_profile.matches(""))
{
Toast.makeText(CAddNewProfileActivity.this, "You did not enter a profileName", Toast.LENGTH_SHORT).show();
return;
} else if(_profile.equalsIgnoreCase(getProfileName(CAddNewProfileActivity.this)))
{
Toast.makeText(CAddNewProfileActivity.this, "Profile already exists", Toast.LENGTH_SHORT).show();
return;
}
else
{
userProfile.setProfileName(_profile);
m_profileDataSource.addProfile(new CUserProfile(CAddNewProfileActivity.this, userProfile.getProfileName(), userProfile.getBrightness(), userProfile.getSleepTime(), m_n8SensorState, userProfile.getOptimization()));
Toast.makeText(CAddNewProfileActivity.this, "Saved", Toast.LENGTH_SHORT).show();
}
finish();
}
});
and the following function is only checking the last entered profile not the whole list ..
public String getProfileName(CAddNewProfileActivity cAddNewProfileActivity){
String profile=null;
CProfileDataSource profileDataSource =new CProfileDataSource(cAddNewProfileActivity);
List<CUserProfile> profileName=profileDataSource.getAllProfiles();
for(CUserProfile cp:profileName){
profile=cp.getProfileName();
}
return profile;
}
Below sample method explains how to check whether the profile already exists or not. This is sample one you had to change the values, table name and where conditions according to your.
public void saveOrUpdateProfile(String profileId, String name, String emailId) {
boolean UPDATE_FLAG = false;
SQLiteDatabase sdb = this.getWritableDatabase();
String selectQuery = "SELECT * FROM tableName WHERE profileId = '" + profileId + "';";
Cursor cursor = sdb.rawQuery(selectQuery, null);
try {
if (cursor != null && cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
UPDATE_FLAG = true;
}
}
ContentValues values = new ContentValues();
values. ("name", name);
values. ("email_id", emailId);
if (UPDATE_FLAG) {
sdb.update(tableName, values, "profileId = ?", new String[]{profileId});
} else {
sdb.insert(tableName, null, values);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
}
}
public long getProfilesRecordCount(String profileName)
{
SQLiteDatabase db=this.openReadable();
long rawNum=DatabaseUtils.queryNumEntries(db,TABLE_NAME,"Profile_Name=?", new String[]{profileName});
return rawNum;
}
rawNum should not greater than 0 ...if it is then String already exists.

Get data from two columns in the database and add to ArrayList

I do not know how to get the data of two columns. I only know how to do it when it deals with one column only.
here is the code where the issue is:
public ArrayList<String> getData() {
ArrayList<String> List = new ArrayList<String>();
Cursor c = db.rawQuery("SELECT Column1, Column2 FROM Table where id = 1", null);
try {
if (c != null) {
if (c.moveToFirst()) {
do {
String levelData = c.getString(c.getColumnIndex("Column1"));
List.add("" + levelData);
}
while (c.moveToNext());
}
}
} catch (SQLiteException e) {
Log.e("Retrieve Data", "Unable to get Data " + e);
}
return List;
}
I know that the problem is at the c.getColumnIndex("Column1")); because that will be the place where to type the column of the table you want to get data from. But what will I do if I will try to do it using two columns?
the answer is simple. it was the first time i tried this and i didn't expect it to work so
this is what i did:
try {
if (c != null) {
if (c.moveToFirst()) {
do {
String levelData = c.getString(c.getColumnIndex("Column1"));
List.add("" + levelData);
}
while (c.moveToNext());
}
}
if (c != null) {
if (c.moveToFirst()) {
do {
String levelData = c.getString(c.getColumnIndex("Column2"));
List.add("" + levelData);
}
while (c.moveToNext());
}
}
} catch (SQLiteException e) {
Log.e("Retrieve Data", "Unable to get Data " + e);
}
I simply added another exact code but this time, it reads Column2 and worked as expected. :D
Make a java bean class with 2 variable and their getters & Setters like
public class Data {
String coloumn1;
String coloumn2;
public String getColoumn1() {
return coloumn1;
}
public void setColoumn1(String coloumn1) {
this.coloumn1 = coloumn1;
}
public String getColoumn2() {
return coloumn2;
}
public void setColoumn2(String coloumn2) {
this.coloumn2 = coloumn2;
}
}
Use
ArrayList dataList = new ArrayList();
dataList.setsetColoumn1(Your Data);
same for coloumn2 and for getters.

Categories

Resources