problems with cursor and getting data? - android

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();
}
}

Related

How to know when SQLite query is finished

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

How to put this cursor data in ArrayLists - AndroidStudio

I have a cursorLoader which returns a cursor with this data:
0 {
email=bogdan#gmail.com
about=Party
}
1 {
email=bogdan1#gmail.com
about=Paaarty
}
2 {
email=bogdan2#gmail.com
about=activity 2
}
3 {
email=bogdan3#gmail.com
about=activity 3
}
4 {
email=bogdan4#gmail.com
about=activity 5
}
How can I save the emails in an ArrayList called emails and the about in an ArrayList called about. I've been trying different things with the cursor but most of the time I just get outOfBounds.
Edit: This is the line that prints it like that:
Log.v("Cursor Object", DatabaseUtils.dumpCursorToString(cursor));
If you want to do it your way maybe this method would help (provided that you supply two empty ArrayList) ?
private void populateLists(Cursor cursor, List<String> emails,
List<String> about) throws IllegalArgumentException {
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToFirst();
do {
emails.add(cursor.getString(cursor
.getColumnIndexOrThrow("email")));
about.add(cursor.getString(cursor
.getColumnIndexOrThrow("about")));
} while (cursor.moveToNext());
}
}

If statement with cursor?

So what I am trying to do is display some information from my sqlite database into a listview. I got the basics down for that but how I display the information needs to be conditional from what the cursor gets back. Currently my cursor comes back liek this.
{
id_number=1234
text=testing
type=1
datetime=null
}
What I need to do is get the type and display according. Example:
if (type == 1){ do code } else if (type == 2) { do a different code }
How exactly would I parse it to do this?
Use this code to go through each of the cursor's rows:
Cursor c = dataBase.rawQuery("SELECT id_number, text, type, datetime FROM [data base name]", null);
if(c.moveToFirst()) {
do {
int type = c.getInt(2);
if(type == 1) {
//do something
} else if (type == 2) {
//do something else
}
} while (c.moveToNext());
}
c.close();

Sqlite android update query not working

Here My update database table methods
public void insertionchallanval(ArrayList<String> itemcode,ArrayList<String> item,ArrayList<String> quantity,
ArrayList<String> date,ArrayList<String> status,ArrayList<String> id)
{
ContentValues insertValues = new ContentValues();
for(int i=0;i<status.size();i++)
{
if(!retriveidstatus(id.get(i)))
{
insertValues.put("id", id.get(i));
insertValues.put("itemcode", itemcode.get(i));
insertValues.put("item", item.get(i));
insertValues.put("status", status.get(i));
insertValues.put("date", date.get(i));
insertValues.put("quantity", quantity.get(i));
//insertValues.put("category", category.get(i));
myDataBase.insert("create_challan", null, insertValues);
}
else
{
insertValues.put("id", id.get(i));
insertValues.put("itemcode", itemcode.get(i));
insertValues.put("item", item.get(i));
insertValues.put("quantity", quantity.get(i));
insertValues.put("status", status.get(i));
insertValues.put("date", date.get(i));
//insertValues.put("category", category.get(i));
myDataBase.update("create_challan", insertValues, "id="+"'"+id.get(i)+"'",null );
}
}
}
Here my check Id Methods
public boolean retriveidstatus(String id)
{
Cursor curCalllog = myDataBase.rawQuery("SELECT id FROM create_challan", null);
if(curCalllog.moveToNext() && curCalllog != null) {
while(!curCalllog.isAfterLast())
{
if(id.contains(curCalllog.getString(0)))
{
return true;
}
curCalllog.moveToNext();
}
}
return false;
}
Table Structure
id String
status String
date String
challanno String
itemcode String
item String
quantity String
When i call methods for insertion new value then its working fine but when i call again with new updated value then update methods return 0 means no row effected
Please Help me how i can fix this problem
Thanks IN Advance
Instead of checking wether the _IDs exist or not you can use replace() method of the class SQLiteDatabase like this :
myDataBase.replace("create_challan", null, insertValues);
hope it helps Cheers :)

Collect data from sqlite and display it in TextView

I was able to be extracted the data that interest me in this way:
Cursor stipcursor = dataBase.rawQuery("SELECT (riepilogo) AS stip FROM "+DbHelper.RIEPILOGO+" WHERE MESI = 'Gennaio' and ANNI = "+anno+"", null);
int colIndexstip = stipcursor.getColumnIndex("stip");
if (colIndexstip == -1)
return;
else
stipcursor.moveToFirst();
double stip = stipcursor.getDouble(colIndexstip);
System.out.println("Riepilogo"+stip);
the problem is that if the database has data, everything works, but if the database is empty, the application crashes.
As given in this post, try this
if ( cursor.moveToFirst() ) {
// start activity a
} else {
// start activity b
}
cursor.moveToFirst() will return false if the cursor is empty. It works for me always.
You can try the first method given on that post also.

Categories

Resources