I am new to the android world and have a problem with an id. What i need is that when the user clicks on new match it will insert a new row into the db. This is working and i get the lastId but now i need this id in the next activities. How can i store that id so i can use it elsewhere?
This is how i insert the new match:
public void newMatch(WedstrijdenGeschiedenis wedstrijd){
// 1.
SQLiteDatabase db = this.getWritableDatabase();
// 2.
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Date date = new Date();
ContentValues values = new ContentValues();
values.put(KEY_DATUM, dateFormat.format(date)); // get datum
// 3.
long lastId = db.insert(TABLE_WEDSTRIJD, // table
null, //nullColumnHack
values); // key/value -> keys = column names/ values = column values
Log.d("New Match","ID ="+lastId);
// 4. close
db.close();
}
so i see the lastId in LogCat but i don't know how to store it for further use. I tried void but offcourse that is not possible on void. Sorry for the dummy question
change void to long and add a return statement that returns the lastId
public long newMatch(WedstrijdenGeschiedenis wedstrijd){
// Your other code
return lastId;
}
Access it with:
long lastId= db.newMatch(new WedstrijdenGeschiedenis());
Related
In a view of my application I can re-sort the position of the rows of a ListView by drag & drop and I save the new order of the rows in the database. The ListView Shows the the contents of an ArrayList defined this way:
ArrayList<ContentValues> lstBat;
and it is populated from a SQLite database. After populate the list I add some values to the "ContentValues" that I use in the Array adapter.
The problem comes in the re_sort method after execute "dbTools.updateBat(cv)".
public void re_sort() {
int lines= lstBat.size();
ContentValues cv=null;
for (int i = 0; i < lines; i++) {
cv = lstBat.get(i); //get row's cv
cv.put("order", i); //Assign new order
dbTools.updateBat(cv); //Store new order in the list
lstBat.set(i, cv);
}
}
The values "state", "icon" and "date" are no longer in the local variable "cv" (ContentValues), they were removed too !!!!!
updateBat method is defined in DBTools class
public int updateBat (ContentValues cv){
SQLiteDatabase database = this.getWritableDatabase();
cv.remove("state"); //Not a column of the table
cv.remove("icon"); //Not a column of the table
cv.remove("date"); //Not a column of the table
return database.update(TABLE_bat, cv, "batId"+"=?", new String[]{cv.getAsString("batId")});
}
And this is the workaround:
public void re_sort() {
int lines= lstBat.size();
long date=0;
String state="";
int icon=0;
ContentValues cv=null;
for (int i = 0; i < lines; i++) {
cv = lstBat.get(i);
date=cv.getAsLong("date");
icon=cv.getAsInteger("icon");
state=cv.getAsString("state");
cv.put("order", i);
dbTools.updateBat(cv);
cv.put("state",state);
cv.put("icon",icon);
cv.put("date",date);
lstBat.set(i, cv);
}
}
If I comment out dbTools.updateBat(cv) the values are preserved, and of course the database won't be updated.
Why were they removed if they are out of scope?
If I correctly understand your code, its behavior seems quite normal.
From your re_sort method you pass the cv object to the updateBat method. All object parameters in Java are passed by reference, therefore cv is NOT a copy of your original object. If you wish to pass a copy of your ContentValues object, you should create a clone. Something like this:
public void re_sort() {
int lines= lstBat.size();
ContentValues cv=null;
for (int i = 0; i < lines; i++) {
cv = lstBat.get(i); //get row's cv
cv.put("order", i); //Assign new order
dbTools.updateBat(new ContentValues(cv)); //Store new order in the list, by passing a new ContentValues object
lstBat.set(i, cv);
}
}
I have a sqlite database prepopulated with some data and I would like to have method/function that enables the user to "save" the info in his favorites and display it. The only problem is i have problems with the queries to work properly. I don't understand how to get the position from the current displayed data (from the db) in the activity and save it to the database. I have a column called "Favorites" in db with the default value set to "no" and when the user click a button the value should change to "yes".
The user click a row in listview populated from the DB and it starts a new activity with intent.putExtra(data from db). The new activity displays the data in a single textview. In this new activity i've made a navigation drawer/listview(shows by sliding or "hamburger meny"). In this nav drawer I have a "button" that i would like to get the id from the db according to the current displayed data and change the value of the column "Favorite". In a another class i used
Cursor c = dbHelper.showBook(Integer.toString(position + 1));
Got this help from another recent thread of mine and it worked fine but my new problem is that i have if statements as below. The start of intent works fine. But I want to call a method from my dbHelper to update rows in db. And the code above dont work(but no errors) when i try to use it. The toast shows but nothing is happening in the DB.
myDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position == 0){
Intent iHome = new Intent(DisplayBook.this, MyAccont.class);
startActivity(iHome);
else if (position == 3){
dbHelper.addFavorites(Integer.toString(position+ 1));
Toast.makeText(getApplicationContext(), "Added to favorites", Toast.LENGTH_SHORT).show();
the dbHelper.addFavorites: (the addFavs param is supposed to be the id/pos of the db row as in the working code above)
public void addFavorites(String addFavs){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COL_FAV, "yes");
String whereClause = COL_ID + " = ?" ;
String[] whereArgs = new String[] { addFavs};
db.update(
TABLE_NAME,
values,
whereClause,
whereArgs);
}
I've tried a fair amount of versions och different codes and stuff but nothing works and now I'm asking for som advice on this. How can i do it in a good an efficient way? Thank you so much for any help at all!
EDIT: Solved it by using arrays instead of stringbuilder. I save the id from the database in [0] and used it in dbHelper.addFavorites(myStringArray[0]);
and in
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Cursor c = dbHelper.aClass(Integer.toString(position + 1));
StringBuilder sb = new StringBuilder();
while (c.moveToNext()) {
myStringArray[0] = c.getString(0);
myStringArray[1] = c.getString(4);
Intent i = new Intent(classA.this, classB.class);
i.putExtra(null, myStringArray);
startActivity(i);
I'm not shure, but your problem may be this line
ContentValues values = new ContentValues();
try to change it to:
ContentValues values = new ContentValues(1);
From my experience u should write amount of variables u want to send to your db.
I am having a problem updating my records when I edit it. I think it's on the DatabaseHandler because I don't know the right codes on how to update the database. Can someone help me fix this?
btn_Update.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
String ReportCode = tv_Code.getText().toString();
//Casting and conversion for district code
String District = spn_District.getSelectedItem().toString();
Cursor rDistrict = databaseHandler.getReport_DistrictCode(District);
String DistrictCode = rDistrict.getString(rDistrict.getColumnIndex(Constants.DISTRICT_CODE));
//Casting and conversion for province id
String Province = spn_Province.getSelectedItem().toString();
Cursor rProvince = databaseHandler.getReport_ProvinceId(Province);
String ProvinceCode = rProvince.getString(rProvince.getColumnIndex(Constants.PROVINCE_ID));
//Casting and conversion for InfoType id
String InfoType = spn_InfoType.getSelectedItem().toString();
Cursor rInfoType = databaseHandler.getReport_InfoTypeCode(InfoType);
String InfoTypeCode = rInfoType.getString(rInfoType.getColumnIndex(Constants.INFORMATIONTYPE_CODE));
int IsCompetitor = chkString;
String DateObserved = txt_Date.getText().toString();
String Remarks = txt_Remarks.getText().toString();
//UPDATE IREPORT
databaseHandler.UpdateReport(new Cons_iReport (ReportCode, InfoTypeCode, DistrictCode, ProvinceCode, DateObserved, IsCompetitor, Remarks));
Toast.makeText(getApplicationContext(), "UPDATE!", Toast.LENGTH_SHORT).show();
}
});
DatabaseHandler.java
public void UpdateReport(Cons_iReport save){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(Constants.REPORT_CODE, save.getReportCode()); // Save Report Code
values.put(Constants.REPORT_DISTRICTCODE, save.getDistrict()); // Save District
values.put(Constants.REPORT_PROVINCECODE, save.getProvince()); // Save Province
values.put(Constants.REPORT_ISCOMPETITOR, save.getCompetitor()); // Save isCompetitor
values.put(Constants.REPORT_INFOTYPECODE, save.getInfoType()); // Save infoType
values.put(Constants.REPORT_DATEOBSERVED, save.getDateObserved()); // Save Date Observed
values.put(Constants.REPORT_REMARKS, save.getRemarks()); // Save Remarks
db.update(Constants.TABLE_REPORT, values, Constants.REPORT_CODE+" = ?", null);
db.close();
}
Your whereArgs are null
db.update(Constants.TABLE_REPORT, values, Constants.REPORT_CODE+" = ?", null);
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#update(java.lang.String, android.content.ContentValues, java.lang.String, java.lang.String[])
You need to supply them or it will not find any records to update.
It's the equivalent of saying "update the records where Constants.REPORT_CODE equals ... nothing". You need to tell it what REPORT_CODE to update.
I currently have a CSV file that I parse and am trying to insert the data into the android database. The problem I am having is that it is taking way too long to insert all of the data. It's a good amount of data but I feel like it shouldn't take 20min or so to complete.
Basically, I create my database, then begin the parsing. While parsing through each individual CSV row, I grab the required data and insert it into the database. In total there are around 40000 rows.
Is there any way I can speed up this process? I have tried batch inserts but it never really helped (unless I did it wrong).
Code down below.
Thanks.
DatabaseHelper (i have two insert commands based on the amount of data in each csv row):
// add zipcode
public void add9Zipcode(String zip, String city, String state, String lat,
String longi, String decom) {
// get db and content values
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
db.beginTransaction();
try{
// add the values
values.put(KEY_ZIP, zip);
values.put(KEY_STATE, state);
values.put(KEY_CITY, city);
values.put(KEY_LAT, lat);
values.put(KEY_LONG, longi);
values.put(KEY_DECOM, decom);
// execute the statement
db.insert(TABLE_NAME, null, values);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
db.close();
}
public void add12Zipcode(String zip, String city, String state, String lat,
String longi, String decom, String tax, String pop, String wages) {
// get db and content values
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
db.beginTransaction();
try{
// add the values
values.put(KEY_ZIP, zip);
values.put(KEY_STATE, state);
values.put(KEY_CITY, city);
values.put(KEY_LAT, lat);
values.put(KEY_LONG, longi);
values.put(KEY_DECOM, decom);
values.put(KEY_TAX, tax);
values.put(KEY_POP, pop);
values.put(KEY_WAGES, wages);
// execute the statement
db.insert(TABLE_NAME, null, values);
db.setTransactionSuccessful();
} finally{
db.endTransaction();
}
db.close();
}
Parse File:
public void parse(ArrayList<String> theArray, DatabaseHandler db) {
String[] data = null;
// while loop to get split the data into new lines
// for loop to split each string in the array list of zipcodes
for (int x = 0; x < theArray.size(); x++) {
if(x == 10000 || x == 20000 || x == 30000 || x == 40000){
Log.d(TAG, "x is 10k, 20k, 30k, 40k");
}
// split string first into an array
data = theArray.get(x).split(",");
// separate based on the size of the array: 9 or 12
if (data.length == 9) {
db.add9Zipcode(data[0], data[2], data[3], data[5], data[6],
data[8]);
} else if (data.length == 12) {
db.add12Zipcode(data[0], data[2], data[3], data[5], data[6],
data[8], data[9], data[10], data[11]);
/*
* theZip.zip = data[0]; theZip.city = data[2]; theZip.state =
* data[3]; theZip.lat = data[5]; theZip.longi = data[6];
* theZip.decom = data[8]; theZip. = data[9]; theZip.population
* = data[10]; theZip.wages = data[11];
*/
}
}
Refer to this answer I made previously: Inserting 1000000 rows in sqlite3 database
In short, use an InsertHelper and do more than one insert per transaction - unless you did something wonky, the speed increase should be noticeable.
Edit:
In short:
Your SQLiteOpenHelper should be a singleton used across your entire application.
Don't go around calling close() on your SQLiteDatabase instance - it's cached in the SQLiteOpenHelper and every time you close you force the helper to reopen it.
Batch your inserts, start a transaction outside the call to the addZipCode methods and mark it as successful after you've done all the inserts - then commit the transaction.
Use an InsertHelper - it will format the insert properly as a prepared statement and is nice and reusable.
Be mindful of synchronizing access to the database - unless you intend to do all your database work on the UI-thread (which is not recommended) - you either need to enable locking or guard access to the database to avoid concurrent access.
I want to save weekdays in database, so i thought to store it by assigning int value to each day. i.e
1 -> Selected, 0 -> Not Selected.
Monday = 0/1
Tuesday = 0/1
.
.
.
.
.
Sunday = 0/1.
But this will make 7 columns in DB. So I was thinking if anyone can help me with this if I should store it in a single array and retrieve the values for further use. I was reading some examples over internet but didn't get it in a easy way.
To insert 7 values in one column you can use comma separator like this
where Total_Score_P1 is an string array
//string array
String[] Total_Score = new String[] { p1e1,p1e2,p1e3,p1e4,p1e5,p1e6 };
// Convderting it into a single string
String result_ScoreP1 = ("" + Arrays.asList(Total_Score_P1)).
replaceAll("(^.|.$)", " ").replace(", ", " , " );
result_ScoreP1 will be
// output of this
result_ScoreP1 = "p1e1,p1e2,p1e3,p1e4,p1e5,p1e6";
insert it as a single string in database and
when retrieve it in again break in parts like
// a string array list
// query fired
public ArrayList<String> rulTable(String id) {
// TODO Auto-generated method stub
ArrayList<String> Ruleob = new ArrayList<String>();
Cursor c_rule;
try
{
c_rule = db.query(NameTable, new String[]{
columns1
},
Rule_COurseID + "=" + id ,
null, null,
null, null, null);
c_rule.moveToFirst();
// if there is data available after the cursor's pointer, add
// it to the ArrayList that will be returned by the method.
if (!c_rule.isAfterLast())
{
do
{
Ruleob.add(c_rule.getString(0));
}
while (c_rule.moveToNext());
}
// let java know that you are through with the cursor.
c_rule.close();
}
catch(Exception e)
{
}
return Ruleob;
}
//list to get elements
ArrayList<String> ListOne = new ArrayList<String>();
ArrayList<String> row ;
try{
// received values
row = db.TheTable(id);
String r1 = row .get(0);
}
catch(Exception e)
{
}
StringTokenizer st2 = new StringTokenizer(r1, "||");
while(st2.hasMoreTokens()) {
String Desc = st2.nextToken();
System.out.println(Desc+ "\t" );
ListOne.add(Desc);
//
}
You can use a binary integer 1= selected 0 =Not Selected (1111111) (0000000)
total seven days so index 0=mon, 1=tues, 2=wed, 3=thurs, 4=friday, 5=sat, 6=sunday..and so on..
here 1111111 means all day selected, 0000000 all day not selected, 0001000 only thursday is selected.
I have also discovered a way i.e. convert your so called values to a JSON Array and then store the complete JSON String to an entity/field in Database.
It helps in serving the values easily and effectivly.
Create another table with a column for each day, boolean value. Make an association to this table by integer id (use a foreign key) This is the relational way of solving the problem.