Ok, I've got this Retrofit Call that receives a list of objects and insert the into a local SQLite database. I want to display a message saying that the operation was successful with a Ok button that when pressed opens a new activity.
How do I check if my Query has finished so I can show the message?
final ContactApi contactApi = retrofit.create(ContactApi.class);
Call<List<Contact>> callContact = contactApi.getContact(token);
callContact.enqueue(new Callback<List<Contact>>() {
#Override
public void onResponse(Response<List<Contact>> response, Retrofit retrofit) {
List<Contact> contactList = response.body();
if (contactList != null) {
try {
DBHelper dbHelper = new DBHelper(TokenActivity.this, token);
SQLiteDatabase conn = dbHelper.getWritableDatabase();
RepoContact repocontact = new RepoContact(conn);
// Inserts each contact into the database
for (Contatc c : contactList) {
repositorioCadastro.inserirCadastro(c);
Log.i("ACTTOKEN", "Contact insert ID: " + c.getId());
}
} catch (SQLiteException e) {
Log.i("ACTTOKEN", "Faillure on insert: " + e.getMessage());
}
}
wrap your code in try{...}finally{...} blocks with a listener ( beginTransactionWithListener(SQLiteTransactionListener transactionListener)), and use the transactionListner to check whether everything went well within the transaction, in addition to everything within the try/finally.
what you have is good, just try adding finally block..
something like this..
db.beginTransaction();
try {
...
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
You can try a different loop, something like this:
for(int i = 0; i < contactList.size(); i++) {
Contact c = contactList.get(i);
repositorioCadastro.inserirCadastro(c);
Log.i("ACTTOKEN", "Contact insert ID: " + c.getId());
if(i == (contactList.size() - 1)) {
// DO SOMETHING HERE
}
}
You may check insert statement return a long when query successfully executed then long value.
db.insert()
returns the row ID of the newly inserted row, or -1 if an error occurred
I'm trying to add data from a csv file to an sqlite database on Android.
My data in csv file looks like this
SID,Attended,Serial,Time,Title,Forenames,Last name,Parking,How many people will be in your party (including yourself)?,Any access requirements?,Access requirements,Timetable
9290,,0000000092906,2014-04-07 18:44:59,Miss,foo1,foo1,,2,No,,fooo
9291,,0000000092907,2014-04-08 18:44:59,Miss,foo2,foo2,,2,No,,fooo
9292,,0000000092908,2014-04-07 18:44:59,Miss,foo3,foo3,,2,No,,fooo
I created a DatabaseHelper to import it :
public void importFromCSV(String filename)
{
//deleteTable();
SQLiteDatabase db = this.getReadableDatabase();
String next[] = {};
try {
db.beginTransaction();
CSVReader reader = new CSVReader(new FileReader(filename));
reader.readNext();
for(;;) {
next = reader.readNext();
if(next != null) {
this.addPerson(new Person(Long.parseLong(next[0]),
next[1],
Long.parseLong(next[2]),
next[3],
next[4],
next[5],
next[6],
next[7],
Integer.parseInt(next[8]),
next[9],
next[10],
next[11]));
} else {
break;
}
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
finally {
db.endTransaction();
}
}
But when I try to do a SELECT on my database, I got an error : CursorIndexOutOfBoundsException : Index 0 requested, with a size of 0.
I did some research and found that this error was because of an empty cursor.
Here is my getPerson function :
public Person getPerson(long sid){
// 1. get reference to readable DB
SQLiteDatabase db = this.getReadableDatabase();
// 2. build query
Cursor cursor =
db.query(TABLE_PERSONS, // a. table
COLUMNS, // b. column names
" sid = ?", // c. selections
new String[] { String.valueOf(sid) }, // d. selections args
null, // e. group by
null, // f. having
null, // g. order by
null); // h. limit
// 3. if we got results get the first one
if (cursor != null) {
cursor.moveToFirst();
}
// 4. build pers object
Person pers = new Person();
pers.setSid(Long.parseLong(cursor.getString(0)));
pers.setAttended(cursor.getString(1));
pers.setSerial(Long.parseLong(cursor.getString(2)));
pers.setTime(cursor.getString(3));
pers.setTitle(cursor.getString(4));
pers.setForename(cursor.getString(5));
pers.setLastname(cursor.getString(6));
pers.setParking(cursor.getString(7));
pers.setNumberpeople(Integer.parseInt(cursor.getString(8)));
pers.setAccessreqornot(cursor.getString(9));
pers.setAccessreq(cursor.getString(10));
pers.setTimetable(cursor.getString(11));
Log.d("getPerson()", pers.toString());
// 5. return pers
return pers;
}
I think the issue is due to my addPerson function called in importFromCsv().
My log at the beginning of the addPerson function returns me the right thing, but I think the db.insert is not going well. But I don't have any error on this.
My addPerson function :
public void addPerson(Person pers){
Log.d("addPerson", pers.toString());
// 1. get reference to writable DB
SQLiteDatabase db = this.getWritableDatabase();
// 2. create ContentValues to add key "column"/value
ContentValues values = new ContentValues();
values.put(SID, pers.getSid());
values.put(ATTENDED, pers.getAttended());
values.put(SERIAL, pers.getSerial());
values.put(TIME, pers.getTime());
values.put(TITLE, pers.getTitle());
values.put(FORENAME, pers.getForename());
values.put(LASTNAME, pers.getLastname());
values.put(PARKING, pers.getParking());
values.put(NUMBERPEOPLE, pers.getNumberpeople());
values.put(ACCESSREQORNOT, pers.getAccessreqornot());
values.put(ACCESSREQ, pers.getAccessreq());
values.put(TIMETABLE, pers.getTimetable());
// 3. insert
db.insert(TABLE_PERSONS, // table
null, //nullColumnHack
values); // key/value -> keys = column names/ values = column values
}
Thanks for your reading time, I would be really grateful if someone had any idea.
EDIT : Stacktrace :
07-08 12:01:57.755: D/addPerson(10828): Person [sid=9290, attended=, serial=92906, time=2014-04-07 18:44:59, title=Miss, forename=Ladina, lastname=Clement, parking=, numberpeople=2, accessreqornot=No, accessreq=, timetable=Fine]
07-08 12:01:57.755: D/addPerson(10828): Person [sid=9291, attended=, serial=92907, time=2014-04-08 18:44:59, title=Miss, forename=Ladina2, lastname=Clement2, parking=, numberpeople=2, accessreqornot=No, accessreq=, timetable=Fine]
07-08 12:01:57.763: D/addPerson(10828): Person [sid=9292, attended=, serial=92908, time=2014-04-07 18:44:59, title=Miss, forename=Ladina3, lastname=Clement3, parking=, numberpeople=2, accessreqornot=No, accessreq=, timetable=Fine]
07-08 12:01:59.193: D/ViewRootImpl(10828): ViewRoot TouchDown(Absolute) DOWN (357 , 189)
07-08 12:01:59.247: D/getAllPersons()(10828): []
Change this line:
if (cursor != null) {
cursor.moveToFirst();
}
to
if (!cursor.moveToFirst()) {
// do something when there are no results
}
The null check on the cursor is redundant. You can check if the cursor is empty by doing cursor.moveToFirst(). If it returns false you should prevent executing further commands on the cursor like you are doing later e.g. cursor.getString(0).
My data is like this:
25-07-14 12:00,15,52,16,50,42,58,63,62,52
22-06-14 14:00,15,52,16,50,42,58,63,62,52
12-09-14 19:00,45,51,16,50,42,58,13,34,52
02-02-14 16:00,15,52,16,50,42,58,63,62,52
01-05-14 12:00,15,52,16,50,42,58,63,62,52
i have read that data like this you can find once. In the file path i am checking is that csv file are not.
FilePath = data.getData().getPath();
if(FilePath.substring(FilePath.length()-4).endsWith(".csv"))
And the code is here
private void readcsvfile() {
if(FilePath.length()>4)
{
dataGridTable = new DgaDataGridTable(context);
equipmentTable = new EquipmentTable(context);
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(FilePath)));
String line;
while ((line=reader.readLine())!=null)
{
info = new DgaDataGridInfo();
String[] rowData = line.split(",");
if(rowData[0].length()!=0&&rowData[1].length()!=0&&rowData[2].length()!=0&&rowData[3].length()!=0&&rowData[4].length()!=0&&rowData[5].length()!=0&&rowData[6].length()!=0&&rowData[7].length()!=0&&rowData[8].length()!=0&&rowData[9].length()!=0)
{
info.setDateadded(rowData[0]);
info.setH2(Integer.parseInt(rowData[1]));
info.setCh4(Integer.parseInt(rowData[2]));
info.setC2h2(Integer.parseInt(rowData[3]));
info.setC2h4(Integer.parseInt(rowData[4]));
info.setC2h6(Integer.parseInt(rowData[5]));
info.setCo(Integer.parseInt(rowData[6]));
info.setCo2(Integer.parseInt(rowData[7]));
info.setO2(Integer.parseInt(rowData[8]));
info.setN2(Integer.parseInt(rowData[9]));
info.setTdcg(Integer.parseInt(rowData[1])+Integer.parseInt(rowData[2])+Integer.parseInt(rowData[5])+Integer.parseInt(rowData[4])+Integer.parseInt(rowData[3])+Integer.parseInt(rowData[6]));
equipmentname = equipment_spinner.getSelectedItem().toString();
info.setEquipid(equipmentTable.getEquipmentId(equipmentname));
dataGridTable.insertRecord(info);
Toast.makeText(this, "Dga Records Succesfully Added", Toast.LENGTH_LONG).show();
loadAllDgaRecords();
}
else
{
showAlertDialog();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
else
Toast.makeText(this, "Please choose csv file", Toast.LENGTH_LONG).show();
}
Thanks
I'm getting this error.
09-05 16:17:27.460: E/CursorWindow(29553): Failed to read row 0, column -1 from a CursorWindow which has 1 rows, 8 columns.
09-05 16:17:27.465: E/AndroidRuntime(29553): FATAL EXCEPTION: main
09-05 16:17:27.465: E/AndroidRuntime(29553): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.nesv.landstar/com.nesv.landstar.LandstarPage}: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
I don't know what I'm doing wrong with my code. Here it is:
Cursor c = null;
try
{
c = landstarDB.rawQuery("SELECT * FROM DriverShipment", null);
}catch (Exception e) {
Log.w("Error selecting table", "Error selecting table");
}
if (c != null && c.moveToFirst()) {
c.moveToFirst();
do {
Log.i("cctid:", c.getString(c.getColumnIndex("cctid")));
if(c.getString(c.getColumnIndex("cctid")) == cctid)
{
isRecorded = true;
shipmentId = c.getString(c.getColumnIndex("cctid"));
origin = c.getString(c.getColumnIndex("origin"));
destination = c.getString(c.getColumnIndex("destination"));
protectTime = c.getString(c.getColumnIndex("protect_time"));
readyTime = c.getString(c.getColumnIndex("ready_time"));
etat = c.getString(c.getColumnIndex("eta"));
if(c.getString(c.getColumnIndex("isAccepted")) == "1")
{
isAccepted = true;
}
}
}while(c.moveToNext());
}
c.close();
Any ideas? Thanks!
column -1 tells you that there is no column cctid, and getColumnIndex returns -1.
Also
c.getString(c.getColumnIndex("cctid")) == cctid
Will not work. Strings are compared using the equals method.
I suggest you post your table creation Query so we can see why the column is not there.
You have call c.moveToFirst(); two times
if (c != null && c.moveToFirst()) {
c.moveToFirst(); // Remove this one
Change your loop as below:
if (c.getCount > 0) {
c.moveToFirst();
do {
Log.i("cctid:", c.getString(c.getColumnIndex("cctid")));
if(c.getString(c.getColumnIndex("cctid")) == cctid)
{
isRecorded = true;
shipmentId = c.getString(c.getColumnIndex("cctid"));
origin = c.getString(c.getColumnIndex("origin"));
destination = c.getString(c.getColumnIndex("destination"));
protectTime = c.getString(c.getColumnIndex("protect_time"));
readyTime = c.getString(c.getColumnIndex("ready_time"));
etat = c.getString(c.getColumnIndex("eta"));
if(c.getString(c.getColumnIndex("isAccepted")) == "1")
{
isAccepted = true;
}
}
}while(c.moveToNext());
}
I have created a table and trying to fetch data from it using a cursor as follow:
public Cursor getcontent() {
Cursor d = database.query(DatabaseHandler.Table_Name2,allColumns,selection, null, null,null,null);
return d;
}
Cursor r = X.getcontent();
if (r.getCount() > 0) {
r.moveToFirst();
do {
String id = r.getString(r.getColumnIndex("content_id"));
al.add(id);
MainActivity.tt1.append("\n");
MainActivity.tt1.append(id);
} while (r.moveToNext()==true);
r.close();
} else {
Log.i("TAG"," No value found");
}
}
I am showing the result in the TextView to see what data it is fetched. My problem is when I run this code sometimes it shows the data in the TextView, whatever it has fetched and sometimes it doesn't. Its a 50:50 ratio, according to me it should show fetched values every time as data is fetched every time I don't know what is wrong here, can someone tell me what's the issue here?
Check Whether Cursor you are getting is Null or not . and if yes then What is the Count of Cursor. you can Do it by Below Way.
Cursor r = X.getcontent();
if ((r != null) && (r.getCount() > 0)) {
r.moveToFirst();
do {
String id = r.getString(r.getColumnIndex("content_id"));
al.add(id);
MainActivity.tt1.append("\n");
MainActivity.tt1.append(id);
} while (r.moveToNext());
r.close();
} else {
Log.i("TAG"," No value found inside Cursor");
}
try like this
Cursor r = X.getcontent();
try {
if (r.moveToFirst()) {
do {
String id = r.getString(r.getColumnIndex("content_id"));
al.add(id);
MainActivity.tt1.append("\n");
MainActivity.tt1.append(id);
} while (r.moveToNext());
}
} finally {
if(r!=null) {
r.close();
}
}
I have written a simple code for Database updatation, but it is sometime updating and sometimes not... i have written LOG for conformation but the log is giving correct output. Here is what i am trying :=
public void updateDownloadedAssetNumberOfStartingBytesEncrypted(int id, int startingBytesEncrypted)
{
SQLiteDatabase database = null;
int numOfRowsUpdated = 0;
try
{
database = getWritableDatabase();
ContentValues values = new ContentValues();
values.put("StartingBytesEncrypted", startingBytesEncrypted);
if(database.isOpen())
{
Log.v("updating in db","doc id - "+id + " encrypted bytes - "+startingBytesEncrypted);
numOfRowsUpdated = database.update("_assets", values, "Id = "+id, null);
}
else
{
Log.v("Database","the database is not open thus starting encrypted bytes were not updated");
}
Log.v("muber of rows updated - ",""+numOfRowsUpdated);
}
catch(Exception ex)
{
}
finally
{
if(database != null)
{
database.close();
}
}
}
What is the problem?? Any help would be Appreciable.
Ya i got ur code...
Finally i resolved the issue.... actually it is beacuse of threading....
the thread creating the row was executed later and that updating the row was executed first
i have resolved it.Have fun :)
This happened due to connection of database is not open. Pls keep ex.printstacktrace(); in catch statement.