Retrieve records from sqllite using Array list - android

I am retrieving all records from database and saving all records in array list.when i show array list records ,repeated data displayed,i don't know what's the prolblem??
Calling this function in view_record class:
public ArrayList<tuple> getdata() { // TODO Auto-generated method stub
tuple obj=new tuple();
Cursor c = ourDatabase.query(DATABASE_TABLE, PROJECTION_ALL, null, null, null, null, null);
if(c == null) {
return null;
}
ArrayList <tuple> data = new ArrayList<tuple>();
// String result = " ";
int i=0;
for(c.moveToFirst();!c.isAfterLast();c.moveToNext()){
obj.ROWID= c.getString(c.getColumnIndexOrThrow(KEY_ROWID));
obj.CNAME= c.getString(c.getColumnIndexOrThrow(KEY_CNAME));
obj.SNAME= c.getString(c.getColumnIndexOrThrow(KEY_SNAME));
obj.FAMILY= c.getString(c.getColumnIndexOrThrow(KEY_FAMILY));
obj.LOCATION= c.getString(c.getColumnIndexOrThrow(KEY_LOCATION));
obj.IMAGE1= c.getBlob(c.getColumnIndexOrThrow(KEY_IMAGE1));
obj.IMAGE2= c.getBlob(c.getColumnIndexOrThrow(KEY_IMAGE2));
obj.IMAGE3= c.getBlob(c.getColumnIndexOrThrow(KEY_IMAGE3));
data.add(i, obj);
i++;
}
c.close();
return data; }
My view_record class
public class view_record extends Activity {
#Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.db_view);
TextView tv=(TextView) findViewById(R.id.tvSqlinfo);
ImageView img=(ImageView) findViewById(R.id.img_view);
db_handler info=new db_handler(this);
info.open();
// Log.d("abc", "adb");
ArrayList <tuple> data=info.getdata();
Log.d("abc", "adb");
String result="";
for(int i=0;i<data.size();i++){
result +=" " + data.get(i).ROWID + " " + data.get(i).CNAME + " " + data.get(i).SNAME + " " + data.get(i).FAMILY + " " + data.get(i).LOCATION + "\n";
tv.setText(result);
img.setImageBitmap(Utilities.getImage(data.get(0).IMAGE2));
}
info.close(); } }
I want to view as follows :
" 1 cname sname family location "
" 2 cname sname family location "
But i am getting
" 2 cname sname family location "
" 2 cname sname family location "
Means last record displayed two times.
and one more thing ,i want to get all records where cname=something,getting error while doing it so

you are not making a new project in your for loop. That is whay you are getting same results. just do...
on start of for loop add this line obj=new tuple();
Answer to your Second Question
for(int i=0;i<data.size();i++){
result +=" " + data.get(i).ROWID + " " + data.get(i).CNAME + " " + data.get(i).SNAME + " " + data.get(i).FAMILY + " " + data.get(i).LOCATION + "\n";
img.setImageBitmap(Utilities.getImage(data.get(0).IMAGE2));
}
tv.setText(Html.fromHtml(result));

Related

Query on ContactsContract.data for RAW_CONTACT_ID returns 0 rows

I'm trying to get get data from from DATA table for specific RAW_CONTACT_IDs, but all I get are empty query outputs.
The logic seems quite simple but I just can't figure out why this happens. Googled it but couldn't find anything similar.
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
String where = RawContacts.DELETED + "<> 0 and " + RawContacts.ACCOUNT_TYPE + "=?";
Cursor c = getContentResolver().query(ContactsContract.RawContacts.CONTENT_URI,
new String[] {RawContacts._ID,
RawContacts.ACCOUNT_NAME,
RawContacts.ACCOUNT_TYPE,
RawContacts.DISPLAY_NAME_PRIMARY
},
where,
new String[] {"Local Phone Account"},
null);
int i = 0;
if (c.getCount() > 0) {
while (c.moveToNext() && i < 10) {
i = i + 1;
// get the id from RawContacts cursor
String rawID = c.getString(c.getColumnIndex(RawContacts._ID));
tv.append("searching RawID " + rawID + "\n" +
"account name: " + c.getString((c.getColumnIndex(RawContacts.ACCOUNT_NAME))) + "\n" +
"account type: " + c.getString(c.getColumnIndex(RawContacts.ACCOUNT_TYPE)) + "\n" +
"display name: " + c.getString(c.getColumnIndex(RawContacts.DISPLAY_NAME_PRIMARY)) + "\n"
);
// create a cursor from Data table for the RawContacts ID
Cursor cur = getContentResolver().query(Data.CONTENT_URI,
new String[] {Data._ID},
Data.RAW_CONTACT_ID + "=?",
new String[] {String.valueOf(rawID)},
null
);
tv.append("found " + cur.getCount() + " matches for id " + String.valueOf(rawID) + "\n");
cur.close();
}
}
setContentView(tv);
}

retrieve all data from all columns from an inner join result

How do I retrieve the data on all columns from an INNER JOIN result? I use this query:
SELECT course.course_title,
course.course_body,
course. course_image,
instructor.instructor_title,
instructor.instructor_body,
instructor.instructor_photo
FROM course
INNER JOIN instructor
ON course.course_instructor1=instructor.instructor_nid
WHERE course_id=4
and this is the equivalent variable COURSE_OUTLINE that i'll be using to execute
String COURSE_OUTLINE =
"SELECT " + Qualified.COURSE_TITLE + ", "
+ Qualified.COURSE_BODY + ", "
+ Qualified.COURSE_IMAGE + ", "
+ Qualified.INSTRUCTOR_TITLE + ", "
+ Qualified.INSTRUCTOR_BODY + ", "
+ Qualified.INSTRUCTOR_IMAGE + ", " +
"FROM " + Tables.COURSE_JOIN_INSTRUCTOR +
"WHERE " + CourseColumns.COURSE_ID +
"=?";
In my code,
Cursor cur = mSqliteDb.rawQuery(SubQuery.COURSE_OUTLINE, new String[] {position});
This gives 1 record. I know how to retrieve data from a specific column but I'm not sure how to retrieve it from all columns.
this is the code I use to retrieve data from a specific column
public String getCourseImage(int position) {
String image = "";
String pos = Integer.toString(position);
Cursor cur = mSqliteDb.rawQuery(SelectQuery.ALL_COURSES, new String[] {pos});
if (cur != null) {
if (cur.moveToFirst()) {
do {
image = cur.getString(cur.getColumnIndex(CourseColumns.COURSE_IMAGE));
} while (cur.moveToNext());
}
cur.close();
}
return image;
}
My intention is mapping each data in a column to a View
getColumnNames gives you an array with all columns... if that's what you're asking. It's kind of hard to tell.

Database update on id deleted

Can someone tell me what is wrong with coding below. Why I can not update next positions?
public static void deleteItemsFromProduct(long nomer) {
cursor_child = DataSourceChild.queryAllinChild();
if (cursor_child != null) {
par = new String[]{String.valueOf(nomer)};
db_child.delete(DBHelperChild.TABLE_ITEMS_AND_PRICES, DBHelperChild.COLUMN_NOMER + "=?", par);
Prod.setProdId(nomer);
cv_child = new ContentValues();
cv_child.put(DBHelperChild.COLUMN_NOMER, Prod.getProdId());
par = new String[]{String.valueOf(nomer+1)};
int updCount = db_child.update(DBHelperChild.TABLE_ITEMS_AND_PRICES, cv_child, DBHelperChild.COLUMN_NOMER + "=?", par);
Log.d(LOG_TAG, "updated rows count = " + updCount);
if (cursor_child.moveToFirst()) {
Log.d(LOG_TAG, "--- Left in the table for items and prices: ---");
do {
Log.d(LOG_TAG,
"item id = " + cursor_child.getInt(item_and_price_idColIndex)
+ ", item name = " + cursor_child.getString(item_ColIndex)
+ ", item price = " + cursor_child.getInt(price_ColIndex)
+ ", product nomer = " + cursor_child.getInt(nomer_ColIndex));
} while (cursor_child.moveToNext());
} else {
}
} else {
Log.d(LOG_TAG, "Cursor is null");
// закрываем курсор
cursor_child.close();
}
}
The idea is to delete set of items in the list while getting id (nomer) from another list. This code updates only the next id nomer after deleted but not others down the list.
Thank you.

Updating UI from AsyncTask after exiting and re-entering app

I am currently working on an app that runs an AsyncTask in the background and updates the UI with a progressbar. The progress bar works fine when the app is running, however, when the user exits the app and re-enters, the AsyncTask is still running in the background, but the progress bar won't update. It's as if the AsyncTask has detached itself from the activity. Does anyone have any ideas what might be causing this such as general rules involved with AsyncTasks. I can provide code if needed, but it is rather lengthy, so just let me know what parts you would need to see. I should also note that the AsyncTask does complete, I can tell this because it uploads a database to the server when it finishes.
Here is the code:
public class BackgroundAsyncTask extends AsyncTask {
int myProgress;
#Override
protected void onPostExecute(Void result) {
((TextView) findViewById(R.id.tv1)).setText("");
Cursor cur = sql3.query("videohashes", null, null, null, null,
null, null);
cur.moveToFirst();
while (!cur.isAfterLast()) {
Cursor curFrame = sql3.query("table_" + cur.getString(2), null,
null, null, null, null, null);
curFrame.moveToFirst();
((TextView) findViewById(R.id.tv1)).append("\nPath: "
+ cur.getString(1) + "\nHash: " + cur.getString(2)
+ "\nDate:" + cur.getString(3) + "\nSize: "
+ cur.getString(4) + " bytes\nResolution"
+ cur.getString(5) + "\nFormat: " + cur.getString(6)
+ "\nCodec: " + cur.getString(7) + "\nFPS: "
+ cur.getString(8) + "\n\nFirst Frame Info:\nType: "
+ curFrame.getString(1) + "\ncp_num: "
+ curFrame.getString(2) + "\ndp_num: "
+ curFrame.getString(3) + "\npts: "
+ curFrame.getString(4) + "\nqstride: "
+ curFrame.getString(5) + "\nsize: "
+ curFrame.getString(6) + "\nqp_stddev: "
+ curFrame.getString(7) + "\ncount: "
+ curFrame.getString(8) + "\nqp_avg: "
+ curFrame.getString(9) + "\n\n");
cur.moveToNext();
}
cur.close();
((Button) findViewById(R.id.btnSend)).setEnabled(true);
((Button) findViewById(R.id.btnStart)).setEnabled(true);
sql3.close();
sharedPreferences.edit().putString("lastVideoInfo", ((TextView) findViewById(R.id.tv1)).getText().toString()).commit();
sharedPreferences.edit().putBoolean("asyncTaskRunning", false).commit();
dateNow = new Date();
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
totProgress = 0;
currVid = 0;
curProgress = 0;
}
#Override
protected void onProgressUpdate(Integer... values) {
progress.setProgress(values[0]);
}
#Override
protected Void doInBackground(Void... arg0) {
// Calculate total size of all files
for (String path : myFiles) {
totProgress += getFileSize(path);
}
progress.setMax(totProgress);
String strDB3File = getFilesDir().getPath() + "/VideoHashes.db3";
sql3 = SQLiteDatabase.openDatabase(strDB3File, null,
SQLiteDatabase.CREATE_IF_NECESSARY);
try {
String mysql = "CREATE TABLE IF NOT EXISTS videohashes (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, path TEXT NOT NULL, hash TEXT NOT NULL, date TEXT NOT NULL, size INTEGER, resolution TEXT NOT NULL, codec TEXT NOT NULL, format TEXT NOT NULL, fps TEXT NOT NULL)";
sql3.execSQL(mysql);
} catch (SQLiteException e) {
// TODO: handle exception
}
for (String path : myFiles) {
try {
String hash = getMD5Checksum(path);
Cursor curFrame = sql3.query("videohashes",
new String[] { "hash" }, "hash=?",
new String[] { hash }, null, null, null);
if (!curFrame.moveToFirst()) {
ContentValues myInsertData = new ContentValues();
myInsertData.put("path", path);
myInsertData.put("hash", hash);
Date date = new Date();
myInsertData.put("date", dateFormat.format(date));
myInsertData.put("size", getFileSize(path));
naInit(path);
Log.i("VPMA", "After naInit");
int[] prVideoRes = naGetVideoResolution();
myInsertData.put("resolution", prVideoRes[0] + "x"
+ prVideoRes[1]);
String prVideoCodecName = naGetVideoCodecName();
myInsertData.put("codec", prVideoCodecName);
String prVideoFormatName = naGetVideoFormatName();
myInsertData.put("format", prVideoFormatName);
double prFps = naGetVideoFPS();
Log.i("VPMA", "fps: " + prFps);
myInsertData.put("fps", prFps);
Object[] prObjArray = naGetArray();
Log.i("VPMA", (String) prObjArray[0]);
String[] prStrArray = Arrays.copyOf(prObjArray,
prObjArray.length, String[].class);
Log.i("VPMA", "before frames");
try {
String mysql = "CREATE TABLE table_"
+ hash
+ " (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, type TEXT NOT NULL, cp_num TEXT NOT NULL, dp_num TEXT NOT NULL, pts TEXT NOT NULL, qstride TEXT NOT NULL, size TEXT NOT NULL, qp_stddev TEXT NOT NULL, count TEXT NOT NULL, qp_avg TEXT NOT NULL)";
sql3.execSQL(mysql);
} catch (SQLiteException e) {
// TODO: handle exception
}
for (String str : prStrArray) {
ContentValues myFrameInsertData = new ContentValues();
String[] strArr = str.split(",");
if (strArr.length == 9) {
String stddev = "", strCount = "", strQp_avg = "";
double sd, qp_avg, count = 0, sum = 0, sqrSum = 0;
try {
count = Integer.parseInt(strArr[6].trim());
sum = Integer.parseInt(strArr[7].trim());
sqrSum = Integer.parseInt(strArr[8].trim());
//sd = (sum * sum / count);
sd = (sqrSum - (sum*sum/count))/(count-1);//(sqrSum - sd) / (count - 1);
stddev = String.valueOf(sd);
qp_avg = sum / count;
strCount = String.valueOf(count);
strQp_avg = String.valueOf(qp_avg);
} catch (Exception e) {
Log.i("Error: ", "error converting values");
}
//Log.i("Java Code: ", "Sum: " + sum + " SqrSum: " + sqrSum + " Count: " + count);
//Log.i("Java Code: ", "StdDev: " + stddev + " qp_avg: " + strQp_avg);
myFrameInsertData.put("type", strArr[0]);
myFrameInsertData.put("cp_num", strArr[1]);
myFrameInsertData.put("dp_num", strArr[2]);
myFrameInsertData.put("pts", strArr[3]);
myFrameInsertData.put("qstride", strArr[4]);
myFrameInsertData.put("size", strArr[5]);
myFrameInsertData.put("qp_stddev", stddev);
myFrameInsertData.put("count", strCount);
myFrameInsertData.put("qp_avg", strQp_avg);
sql3.insert("table_" + hash, null,
myFrameInsertData);
}
}
sql3.insert("videohashes", null, myInsertData);
naClose();
}
curFrame.close();
currVid++;
curProgress += getFileSize(path);
publishProgress(curProgress);
Log.i("Progress", "CurrVid:" + currVid + " Max:"
+ progress.getMax());
} catch (Exception e) {
Log.i("File", "File not Found");
}
}
return null;
}
}
}
if (sharedPreferences.getBoolean("asyncTaskRunning", false) == false)
{
((Button) findViewById(R.id.btnStart)).setEnabled(false);
progress = (ProgressBar) findViewById(R.id.progressBar1);
text = (TextView) findViewById(R.id.tv1);
if (sharedPreferences.contains("lastVideoInfo"))
{
text.setText("Last Video Information Parsed " + "(" + dateFormat.format(dateNow) + "):\n\n" + sharedPreferences.getString("lastVideoInfo", ""));
((Button) findViewById(R.id.btnSend)).setEnabled(true);
}
else
{
text.setText("");
((Button) findViewById(R.id.btnSend)).setEnabled(false);
}
progress.setProgress(0);
myFiles = new ArrayList<String>();
new StartAsyncTask().execute();
}
}
When the Activity is destroyed, it loses its reference to the AsyncTask, as when the AsyncTask is created it is passed in a reference to the instance of the Activity that creates it. When the instance dies, the reference to the Activity becomes useless.
A better approach would be put the AsyncTask into a Service, set up the Service and set the AsyncTask running in the Service and bind your Activity to the Service.
Then when a new instance of the Activity is created (ie when the user re-enters the app), it can bind to the same Service instance that's already running and pass in a reference to its self to receive progress info.
Another advantage of this approach is that your Service can put a notification icon in the notification bar, which greatly reduces it chances of being killed by the system, the user could view progress at a glance, and even be notified of when the process is complete.
Allowing an AsyncTask to be cut loose from its owner (is the Activity) and trusting that it will complete what its doing is a pretty bad idea, and will probably have some unexpected results, lead to potential memory leaks etc.

How should I do this query in Sqlite?

I have a database with the columns: id, pdate, pvalue1, pvalue2. First I make a query with a cursor:
Cursor c = ourDatabase.query(DATABASE_TABLE, new String[] { "_id","pdate","pvalue1","pvalue2"},
"pdate >= ? AND pdate <= ?", new String[] { datefrom, dateto }, null, null, null);
This gives me some rows, for example if pdate = 20120318, then pvalue1 = 58, pvalue2=29. These are strings so I can give a value of "XX" to pvalue2. I would like to sum the pvalue1 between the given datefrom and dateto and group them by pdate where pvalue2 = XX. My problem is that I cannot put this condition into the query (with that its working, like "pvalue2 = XX"..), because I need the other datas too.
if (c.moveToFirst())
{
do{
if (c.getString(3).equals("XX")){
Log.i("XX", c.getString(1) + " " + c.getString(2)) + " " + c.getString(3));
}
else {
Log.i("NotXX", c.getString(1) + " " + c.getString(2)) + " " + c.getString(3));
}
while (c.moveToNext());
}
}
It is okay so far, so I can log the datas with this where pvalue2 = XX and NotXX and get something like this:
(pdate,pvalue1,pvalue2) 20120317,48,29;------;20120317,21,54;-------20120317,11,XX;-----20120318,79,71;-------20120318,21,XX;
What I would like to do?
First: Grouping the sums (pvalue1) by pdate and indicate it if pvalue2 is XX or notXX, so somethnig like this:
20120317,NotXX,69 (since 48+21=69) -------- 20120317,XX,11 -------- 20120318,NotXX,79 -------- 20120318,XX,21
After this I would like to substract the XX sum from the NotXX sum for every day. I would like to get:
20120317,58 (since 69-11) ------- 20120318,58 (since 79-21)
How sould I do this?
Thank you very much in advance!
My problem is that I cannot put this condition into the query
You are probably wrong. You can add something like (syntax may contain errors)
"select sum(select pdate from DATABASE_TABLE where pdata > x and pdate < y) as sum"
to the projection argument and you get that result as a column named sum. The only problem is that there is no support for ? in projection (at least I have not tried it but I guess it would not work)
If that's not what you want then there is very likely a different way. SQLite is very powerful.
Edit:
Would that be what you want? It's not done in SQL but it would print the sum you want for each day.
Cursor c = ourDatabase.query(DATABASE_TABLE, new String[] { "_id","pdate","pvalue1","pvalue2"},
"pdate >= ? AND pdate <= ?", new String[] { datefrom, dateto }, null, null, "pdate");
boolean first = true;
if (c != null) {
String currentDate = null;
int sum = 0;
while (c.moveToNext()) {
String date = c.getString(1);
int value1 = c.getInt(2);
String value2 = c.getString(3);
if (!date.equals(currentDate)) {
if (!first) {
Log.d("TAG", "The result for " + currentDate + " is: " + sum);
} else {
Log.d("TAG", "Date has changed, but we don't have data yet.");
}
first = false;
currentDate = date;
sum = 0;
}
if ("XX".equals(value2)) {
Log.d("TAG", "new line: " + date + ", " + value1 + ", " + value2 + " -");
sum -= value1;
} else {
Log.d("TAG", "new line: " + date + ", " + value1 + ", " + value2 + " +");
sum += value1;
}
}
if (!first) {
Log.d("TAG", "The last result: " + currentDate + " is: " + sum);
}
c.close();
}
Edit2: This might work when you want it done by the database.
Cursor c = ourDatabase.rawQuery(
"SELECT pdate, sum(sum2) AS sum1 FROM " +
"(" +
" SELECT pdate, pvalue1, pvalue2, -sum(pvalue1) AS sum2 " +
" FROM " + DATABASE_TABLE +
" WHERE pvalue2='XX' GROUP BY pdate" +
" UNION " +
" SELECT pdate, pvalue1, pvalue2, sum(pvalue1) AS sum2 " +
" FROM " + DATABASE_TABLE +
" WHERE pvalue2!='XX' GROUP BY pdate" +
") " +
" WHERE pdate>=? AND pdate<=? " +
" GROUP BY pdate",
new String[] { datefrom, dateto });
if (c != null) {
while (c.moveToNext()) {
String date = c.getString(0);
int value1 = c.getInt(1);
Log.d("TAG", "The result for " + date + " is: " + value1);
}
c.close();
}

Categories

Resources