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
Related
I have an android application that display data from my external Database so from several tables. Everything work fine while internet connection is available (all data come from URL link and they are been parsed with volley). But how can I save and load lastest data when internet is not available.
What is the best way to do that. Im new in android....
Please help.
Normally Volley and also HttpStack it uses allows you to seamlessly cache responses. This however depends on your responses and requests. Those cache strategies obeys http cache definition. If You want to have different behavior for Volley you can just override this part. basically when you create a request you can override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
and instead of
return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
you do
long now = System.currentTimeMillis();
Cache.Entry entry = HttpHeaderParser.parseCacheHeaders(response);
entry.ttl = now + 30l * 24 * 60 * 60 * 1000; //kepps cache for 30 days
//entry.softTtl = now + 30l * 24 * 60 * 60 * 1000; //will not refresh for 30 days
return Response.success(parsed, entry);
Which basically will refresh the cache every time the server specifies so but will always return the cache for 30 days unless changes .
Note that here you may receive 2 callbacks in response or in one response and 1 error(in case of no network). the first one will be the cache.
UPDATE:
if you add (which is commented in the example above):
entry.softTtl = now + 30l * 24 * 60 * 60 * 1000; //will not refresh for 30 days
this will affect the refresh of the cache. in this case it wont event try to refresh the cache for 30 days. In that case you will return 1 response.
Note that I never would recommend solution like this because cache needs to be updated, especially if you want to fake cache on POST requests as in your case.
Receiving 2 callbacks is not really an issue as you can handle this seamlesly for the user and update UI when needed. also if you want to have more control you can know which one is from the cache and which one form the network by implementing your
ResponseDelivery
or extend
ExecutorDelivery
and then check for the param
mResponse.intermediate
and decide what to do then. ResponseDelivery is the one which calls the callbacks.
Update
similar question and examples here
if you have to store only small chunk of data then use SharedPreferences
If you have large data then use SQLite
Use below code to create and update SQLite DB
public class SqlMangaeMenu
{
SQLiteDatabase db1 = null;
private static String DBNAME = "YourLocal.db";
Context gcntxt;
public SqlMangaeMenu(Context cntxt)
{
// TODO Auto-generated constructor stub
gcntxt=cntxt;
db1 = cntxt.openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
db1.execSQL("CREATE TABLE IF NOT EXISTS mytbl(appid varchar PRIMARY KEY,appname varchar,iconcode varchar,msgidentfier varchar,scode varchar,image blob,imagehdr blobhdr); ");
}//EOF Constructor
public void insertContent(String appid,String appname,String iconcode,String msgidentifier,String scode,Bitmap bmp,Bitmap bmphdr)
{
ContentValues contentValues = new ContentValues();
contentValues.put("appid", appid);
contentValues.put("appname", appname);
contentValues.put("iconcode", iconcode);
contentValues.put("msgidentfier", msgidentifier);
contentValues.put("scode", scode);
byte[] blob = null,blobhdr=null;
if(bmp!=null)
{
ByteArrayOutputStream outStr = new ByteArrayOutputStream();
bmp.compress(CompressFormat.PNG, 100, outStr);
blob = outStr.toByteArray();
}
contentValues.put("image", blob);
if(bmphdr!=null)
{
ByteArrayOutputStream outStr1 = new ByteArrayOutputStream();
bmphdr.compress(CompressFormat.PNG, 100, outStr1);
blobhdr = outStr1.toByteArray();
}
contentValues.put("imagehdr", blobhdr);
Log.d("db", "SQL Writing"+appid+appname+iconcode+msgidentifier+scode);
try {
// db1.insert("mytbl",null,contentValues);
db1.insertWithOnConflict("mytbl", null, contentValues,SQLiteDatabase.CONFLICT_IGNORE);
} catch (Exception e)
{
// TODO: handle exception
}
db1.close();
}//EOF insertContent
// Deleting single contact
public void Delete_appid(String id)
{
db1.delete("mytbl", "appid" + "=" + id, null);
db1.close();
}//EOF Delete_appid
public void readAppId()
{
MyApplication.dbappid=new ArrayList<String>();
String appid;
try
{
Cursor c = db1.rawQuery("SELECT * FROM mytbl", null);
//Cursor c = db1.rawQuery("SELECT MAX(ID) FROM mytbl", null);
if(c!= null)
{
if (c.moveToFirst())
{
do {
appid=c.getString(c.getColumnIndex("appid"));
MyApplication.dbappid.add(appid);
}while(c.moveToNext());
}
}
Log.d("db", "SQL Reading");
db1.close();
}
catch(Exception e)
{
System.out.println(e);
}
}//EOF readAppId
public void readDataandImage()
{
Bitmap image=null,imagehdr = null;
//Bitmap images
MyApplication.dbimg=new ArrayList<Bitmap>();
MyApplication.dbhdrimage=new ArrayList<Bitmap>();
//String
MyApplication.dbappname=new ArrayList<String>();
MyApplication.dbappid=new ArrayList<String>();
MyApplication.dbiconcode=new ArrayList<String>();
String appname,appid,iconcode;
try
{
Cursor c = db1.rawQuery("SELECT * FROM mytbl", null);
if(c!= null)
{
if (c.moveToFirst())
{
do {
image=null;imagehdr=null;
byte[] blob = c.getBlob(c.getColumnIndex("image"));
byte[] blobhdr = c.getBlob(c.getColumnIndex("imagehdr"));
appid=c.getString(c.getColumnIndex("appid"));
appname=c.getString(c.getColumnIndex("appname"));
iconcode=c.getString(c.getColumnIndex("iconcode"));
if(blob!=null)
{
image = BitmapFactory.decodeByteArray(blob, 0, blob.length);
}
if(blobhdr!=null)
{
imagehdr = BitmapFactory.decodeByteArray(blobhdr, 0, blobhdr.length);
}
//Images
MyApplication.dbimg.add(image);
MyApplication.dbappid.add(appid);
//String
MyApplication.dbappname.add(appname);
MyApplication.dbiconcode.add(iconcode);
MyApplication.dbhdrimage.add(imagehdr);
}while(c.moveToNext());
}
}
Log.d("db", "SQL Reading");
db1.close();
}
catch(Exception e)
{
System.out.println(e);
}
}//EOF readDataandImage
public int dbRowCount()
{
int rowcnt=0;
String countQuery = "SELECT * FROM mytbl";
//SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db1.rawQuery(countQuery, null);
rowcnt = cursor.getCount();
cursor.close();
db1.close();
Log.d("db", "Numrecs"+rowcnt);
return rowcnt;
}//EOFdbRowCount
}
where MyApplication is a static class to hold the read values.
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 compare a ContentValues Object with values from a Database, but I can't figure out why the following wont work:
ContentValues werte = new ContentValues();
try{
JSONObject ClickedItem = new JSONObject();
ClickedItem = resultArray.getJSONObject(position);
werte.put("name", ClickedItem.getString("name"));
werte.put("hersteller", ClickedItem.getString("hersteller"));
}
catch (Exception e) {
System.out.println("Whoops - something went wrong!3");
e.printStackTrace();
}
Boolean allreadyAdded = false;
Cursor devicesCursor = mDatenbank.query("addedDevices", new String[] {"name", "hersteller"}, null, null, null, null, null);
startManagingCursor(devicesCursor);
devicesCursor.moveToFirst();
for (int i=0;i<devicesCursor.getCount();i++){
if(devicesCursor.getString(0) == werte.getAsString("name")){
allreadyAdded = true;
}
devicesCursor.moveToNext();
}
if(allreadyAdded==false){
mDatenbank.insert("addedDevices", null, werte);
}
The if(devicesCursor.getString(0) == werte.getAsString("name")) just wont work and I can't figure out why. System.out.println shows me that devicesCursor and were both have the same value but already Added won't be set to true...
Because you can not compare two string using == operator, Your if condition never be gone true.
To compare two strings just use .equals() or .equalsIgnoreCases() from Java String Class..
if(devicesCursor.getString(0).equals(werte.getAsString("name")))
i am looking to make game of questions and answers.i had taken a textview and 4 radio group buttons.and i am fetching data from the external data file from the assets folder.when i installs the app into the emulater it works fine.when i reopens the app in the emulater it is just showing question not showing any text in the radio buttons.here is my code in the data base file
public String makeatext(String My_database_table,int i) {
SQLiteDatabase myDB = getDatabase();
String results = new String();
try {
String firstColumn = "questions";
// final String KEY_ROWID = "id";
// Cursor c = myDB.rawQuery("SELECT questions FROM " +
// My_database_table+ ";",null);
Cursor c = myDB.query(true, My_database_table,
new String[] { firstColumn },null, null, null, null, null,
null);
int iquestion = c.getColumnIndex(firstColumn);
if(c.moveToPosition(i)){
results = c.getString(iquestion)+"\n";
}
//while (c.moveToPosition(1)) {
//String firstName = c.getString(iquestion);
//results =(" "+ firstName + " ");
//}
return results;
} catch (Exception e) {
Log.e("ERROR","ERROR in Make test file :"+e.toString());
e.printStackTrace();
// TODO: handle exception
}
return results;
}
and in the Activity file i am just calling it as
String shoow = myDb.makeatext("question", Qno);
showQuestion.setText(shoow);
and on the top of the oncreate methode i initilized the data base asprivate final DataBaseHelper myDb = new DataBaseHelper(this);
can any one say me why this is happenig.do i need to write the for loop in the activity file also or shall i take a cursor in the activity class .
plz help me out
thanks in advance
for radio buttons the code in the database file is as follows as i have 4 buttons the code for 4 buttons will be as same as this
public String makeExtra1(String My_database_table ,int positions) {
String results = new String();
try {
String secondColumn = "Extra1";
Cursor c = myDataBase.query(true, My_database_table,
new String[] { secondColumn }, null, null, null, null, null,
null);
int iExtra1 = c.getColumnIndex(secondColumn);
if(c.moveToPosition(positions)){
results = results+c.getString(iExtra1)+"\n";
}
return results;
} catch (Exception e) {
Log.e("ERROR","ERROR in Make test file :"+e.toString());
e.printStackTrace();
// TODO: handle exception
}
return results;}
and in the Activity file
String showextra1 = myDb.makeExtra1("question", Qno);
r0.setText(showextra1);
i repeted this thing for 4 times as changing the makeExtra2,3,4 and in the assinged to r1,r2,r3 as above.
You should call Cursor.close() after reading data from it. Better to do it finally{} block.
If you want to raise only one answer per query - fill where param of myDataBase.query().
The unreachable code error is because you are writing finally{} block after return results;
Move this line after the finally{} block, eclipse will not give you any error.
Also do use myDB.close(); in this finally block.
I have created complied statement given below. Now my question is how to get resultset of the query.
Here is my code:
DataBaseHelper dbHelper=new DataBaseHelper(context);
dbHelper.createDataBase();
dbHelper.openDataBase();
SQLiteDatabase db = dbHelper.getWritableDatabase();
SQLiteStatement st=db.compileStatement("select taskid from task where taskdate=?");
st.bindString(1,"2011/09/05");
st.execute();
This works without any error. But I want the result set of the given query. Please help..
The result set isn't available, at least for now, in sqlite. It all depends on exactly what information you want from the ResultSet or ResultSetMetaData, etc, but there are other means of obtaining almost the same information.
You can get detailed information about the columns in a table with the following, used as if it were a SELECT, and the information about the columns will be presented:
pragma table_info(myTable) ;
See http://www.sqlite.org/pragma.html#pragma_table_info for more information.
If you want the information concerning a specific SELECT, you can get information from the resulting Cursor. See http://developer.android.com/reference/android/database/Cursor.html
For example, if you want the type of data for a column, you can use the getType() method in the newer versions of Android, or use a series of "get" functions to determine at least what type is readable, with this horrible code:
Cursor curs = db.rawQuery(sqlStr, null);
int numberOfColumns = curs.getColumnCount();
String []colNames = new String[numberOfColumns];
String []colTypes = new String[numberOfColumns];
for(int iCol=1; iCol<=numberOfColumns; iCol++) {
colNames[iCol-1] = curs.getColumnName(iCol-1);
colTypes[iCol-1] = null; //curs.getType(iCol);
}
while(curs.moveToNext()) {
// this code assumes that the first row has the same data types
// as the rest of the rows
for(int iCol=1; iCol<=numberOfColumns; iCol++) {
String colName = colNames[iCol-1];
String colType = colTypes[iCol-1];
if(colType==null) {
// determine column type
try {
curs.getString(iCol-1);
colType = colTypes[iCol-1] = "text";
} catch (Exception ignore) {
try {
curs.getLong(iCol-1);
colType = colTypes[iCol-1] = "integer";
} catch (Exception ignore1) {
try {
curs.getFloat(iCol-1);
colType = colTypes[iCol-1] = "real";
} catch (Exception ignore2) {
try {
curs.getBlob(iCol-1);
colType = colTypes[iCol-1] = "blob";
} catch (Exception ignore3) {
colType = colTypes[iCol-1] = "other";
}
}
}
}
}
if("text".equals(colType)) {
... curs.getString(iCol-1);
} else
if("real".equals(colType)) {
... curs.getDouble(iCol-1);
} else
if("integer".equals(colType)) {
... curs.getInt(iCol-1);
} else { // unknown type
... colType+"-"+curs.getString(iCol-1);
}
}
}
Other information is available in a similar manner, depending on your need.