i'm populating a list view to view my record, i've the following code...
super.onCreate(savedInstanceState);
setContentView(R.layout.total);
ArrayList<Object> results = new ArrayList<Object>();
// -- SQLiteOpenHelper dbHelper = new DatabaseHelper(this, SAMPLE_DB_NAME, null, 1);
SQLiteDatabase myDB = this.openOrCreateDatabase(SAMPLE_DB_NAME, SQLiteDatabase.OPEN_READONLY, null);
try {
/* Create the Database (no Errors if it already exists) */
myDB.execSQL("PRAGMA foreign_keys = ON;");
// -- openOrCreateDatabase(name, mode, factory)
// myDB = dbHelper.getReadableDatabase();
Cursor c = myDB.query(DatabaseHelper.SAMPLE_TABLE_NAME, null, null, null, null, null, null);
Cursor d = myDB.query(DatabaseHelper.SAMPLE_TABLE_NAMES, null, null, null, null, null, null);
/* Check if our result was valid. */
if (c != null && d != null) {
c.moveToFirst(); // it's very important to do this action otherwise your Cursor object did not get work
d.moveToFirst();
char cust_name = (char) c.getColumnIndex("cust_name");
char pro_name = (char) d.getColumnIndex("pro_name");
int pro_price = (int) d.getColumnIndex("pro_price");
/* Check if at least one Result was returned. */
if (c.isFirst() && d.isFirst()) {
int i = 0;
/* Loop through all Results */
do {
i++;
String cust_nameColumnIndex = c.getString(cust_name);
String pro_nameColumnIndex = c.getString(pro_name);
int pro_priceColumnIndex = c.getInt(pro_price);
/* Add current Entry to results. */
results.add("" + i + ": " + cust_name + " (" + pro_name + ": " + pro_price + ")");
} while (c.moveToNext()&& d.moveToNext());
}
}
} catch (SQLiteException e) {
} finally {
if (myDB != null)
myDB.close();
}
// -- android.R.layout.simple_list_item_1 is object which belong to ListActivity itself
// -- you only need to add list object in your main layout file
this.setListAdapter(new ArrayAdapter<Object>(this, android.R.layout.simple_list_item_1, results));
}
total.xml
<ListView
android:id="#id/android:list"
android:layout_width="fill_parent"
android:layout_height="380dp"
android:cacheColorHint="#00000000" >
</ListView>
the data is successfully inserted to sqlite (confirmed from adb shell)...it gives me garbage value...can any one please figure out the issue....Thanks in advance
That is not garbage values references(memory) addresses, use below code it will work.
do {
i++;
String cust_nameColumnIndex = c.getString(cust_name);
String pro_nameColumnIndex = c.getString(pro_name);
int pro_priceColumnIndex = c.getInt(pro_price);
/* Add current Entry to results. */
results.add("" + i + ": " + cust_nameColumnIndex + " (" + pro_nameColumnIndex + ": " + pro_priceColumnIndex + ")");
} while (c.moveToNext()&& d.moveToNext());
this.setListAdapter(new ArrayAdapter<Object>(this, android.R.layout.simple_list_item_1, (String[]) results.toArray(new String[0])));
Try changing the way you read your cursors. Something like that might be better:
//Get the indexes
int cust_name = cursor.getColumnIndex("cust_name");
int pro_name = cursor.getColumnIndex("pro_name");
int pro_price = cursor.getColumnIndex("pro_price");
try {
if(cursor.moveToFirst()){
while (!cursor.isAfterLast()) {
//Get the data
String cust_nameColumnIndex = cursor.getString(cust_name);
String pro_nameColumnIndex = cursor.getString(pro_name);
int pro_priceColumnIndex = cursor.getInt(pro_price);
//Move to next cursor item
cursor.moveToNext();
}
}
else {
Log.i(TAG, "Empty cursor");
//Do whatever
}
} catch (Exception e) {
Log.i(TAG, "Exception while reading cursor: " + e.getMessage());
//Do whatever
}
finally {
cursor.close();
}
Related
i have retrieved some values from DB using the query which is given below.
public Cursor getcredittranscation(String date)
{
String sql="SELECT A.Acc_No,A.Cust_Name, T.Trans_Amnt FROM TransactionTable "
+ "T LEFT JOIN AccMaster A on A.Acc_ID = T.Acc_ID "
+ "WHERE T.Trans_Date =? AND T.Trans_Type=? ORDER BY T.Entry_Time asc";
Cursor cursor = db.rawQuery(sql, new String[]{date, "credit"});
return cursor;
}
And in main activity i want to show these results as a report. Activity code is as given below.
try{
db.open();
Cursor c = db.getdebittranscation(temp);
if (c.moveToFirst()) {
do {
DisplayDebitDetails(c);
debittotal(c);
} while (c.moveToNext());
}
db.close();
}catch (Exception e) {
// TODO: handle exception
Log.e("Retrive Debit Error ", " "+e.getMessage());
}
private void DisplayDebitDetails(Cursor c) {
String tempdebit = debitView.getText().toString() + " ";
tempdebit= " \t"+tempdebit+ "\n\t" +c.getString(0) + "\t\t\t"
+ c.getString(1) + "\t\t\t" + c.getString(2);
debitView.setText(tempdebit);
Log.e("debit", "Acc No :"+c.getString(0) +"Name :"+c.getString(1)+ "Trans Amnt :"+c.getString(2));
}
}
private void debittotal(Cursor c){
int tmp = Integer.parseInt(debiTotalView.getText().toString()+" ");
tmp = +tmp+Integer.parseInt(c.getString(2));
debiTotalView.setText(tmp);
Retrieving and viewing all values is ok... But i need the sum of all values in String(2) . which is given in method debittotal(Cursor c). what is the error in that part ?? I am not getting total
you can use getCount() method
int number_of_records = cursor.getCount();
try this and make sure that debitTotalView.getText().toString() is not blank or null
initially that field value must be 0 otherwise it will give you NumberFormatException for invalid int value
replace
int tmp = Integer.parseInt(debiTotalView.getText().toString()+" ");
tmp = +tmp+Integer.parseInt(c.getString(2));
debiTotalView.setText(tmp);
with
int tmp = Integer.parseInt(debiTotalView.getText().toString().trim());
tmp = +tmp+Integer.parseInt(c.getString(2));
debiTotalView.setText(tmp+"");
I am working on a code snippet where i am storing my json encoded data into a txt file,and using following method to separate all parts and adding them into database.
public boolean addAnswersFromJSONArray() {
boolean flag = false;
Answer answer = new Answer();
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard, "user_live.txt");
FileReader fr;
JsonReader reader;
try {
fr = new FileReader(file);
reader = new JsonReader(fr);
reader.beginArray();
reader.setLenient(true);
while (reader.hasNext()) {
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals("product_name")) {
answer.setProductName(reader.nextString());
} else if (name.equals("subject")) {
answer.setSubject(reader.nextString());
} else if (name.equals("month")) {
answer.setMonth(reader.nextString());
} else if (name.equals("year")) {
answer.setYear(reader.nextString());
} else if (name.equals("question")) {
answer.setQuestion(reader.nextString());
} else if (name.equals("answer")) {
answer.setAnswer(reader.nextString());
} else if (name.equals("question_no")) {
answer.setQuestion_no(reader.nextString());
} else if (name.equals("marks")) {
answer.setMarks(reader.nextString());
} else {
reader.skipValue();
}
}
answer.save(db);
reader.endObject();
flag = true;
}
reader.endArray();
reader.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
file.delete();
db.close();
}
return flag;
}
and then i am retrieving each fields departments,subjects,month and year,questions,answers,question_no, but while retrieving marks i am getting only unique entries that is 10 and 5....Ideally the size of one set is 18 so i m getting ArrayIndexoutOfBounds Exception.
//database calling part
marks = db.getMarksList(department, subject, month_year);
database method is,
public String[] getMarksList(String department, String subject,
String month_year) {
String month = month_year.split("-")[0];
String year = month_year.split("-")[1];
String whereClause = DEPARTMENT + " = '" + department + "'" + " AND "
+ SUBJECT + " = '" + subject + "' AND " + MONTH + " = '"
+ month + "' AND " + YEAR + " = '" + year + "'";
System.out.println("questions: " + whereClause);
Cursor cursor = db.query(true, "ANSWERS", new String[] { "MARKS" },
whereClause, null, null, null, "DEPARTMENT", null);
String list[] = new String[cursor.getCount()];
int i = 0;
if (cursor != null && cursor.getCount() > 0) {
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor
.moveToNext()) {
list[i] = new String(cursor.getString(0));
i++;
}
}
return list;
}
Can anyone help me to resolve this issue?? Why getting only unique value,I have checked my json result also each row contains marks.
i got the solution for this,
Changed database query and method as following,
public List<Answer> getMarksList(String department, String subject,
String month_year) {
List<Answer> list = new ArrayList<Answer>();
String month = month_year.split("-")[0];
String year = month_year.split("-")[1];
try {
String sql1 = "select all marks from " + TABLE_NAME
+ " where department = '" + department
+ "' AND subject = '" + subject + "' AND month = '" + month
+ "' AND year = '" + year + "';";
SQLiteDatabase db1 = this.getWritableDatabase();
Cursor cursor = db1.rawQuery(sql1, null);
if (cursor.moveToFirst()) {
do {
Answer a = new Answer();
a.setMarks(cursor.getString(0));
list.add(a);
} while (cursor.moveToNext());
}
} catch (Exception e) {
}
return list;
}
using "all" in query is retrieving all records.
I am trying to do Order by to fetch the records from higher to lower values , but the sorting is not happening, i am getting the records randomly.
Here is my code , please let me know , where i am going wrong:
public void fetchTopRecords() {
int i = 0;
String where = "SELECT * FROM " + DATABASE_TABLE_2 + " ORDER BY "
+ COL_C + " ASC LIMIT 6";
Cursor c = db.rawQuery(where, null);
if (c != null) {
if (c.moveToFirst()) {
do {
String pckname = c.getString(COL_A);
array_pck.add(pckname);
int marks = c.getInt(COL_C);
i++;
} while (c.moveToNext());
}
}
use the below code it will work :
public void fetchTopRecords() {
String where = "SELECT * FROM " + DATABASE_TABLE_2 + " ORDER BY "
+ COL_C + " DESC LIMIT 6";
Cursor c = db.rawQuery(where, null);
if (c != null) {
if (c.moveToFirst()) {
do {
String pckname = c.getString(COL_A);
array_pck.add(pckname);
int marks = c.getInt(COL_C);
} while (c.moveToNext());
}
}
I'm trying to populate a list view from a SQLite db I can create the db and add items to it and display them in a TextView but for some reason not on a ListView
Is it that sData is the wrong type of object?
Can anyone help, please?
public void DBTest() {
SQLiteDatabase myDB = null;
String TableName = "myTable";
/* Create a Database. */
try {
myDB = this.openOrCreateDatabase(DATABASE_NAME, MODE_PRIVATE, null);
/* Create a Table in the Database. */
myDB.execSQL("CREATE TABLE IF NOT EXISTS "
+ TableName
+ " (_id integer primary key autoincrement, name text, script text, su short);");
/* Insert data to a Table*/
myDB.execSQL("INSERT INTO "
+ TableName
+ " (name, script, su)"
+ " VALUES ('hello', 'reboot', 1);");
/*retrieve data from database */
Cursor c = myDB.rawQuery("SELECT * FROM " + TableName, null);
int Column1 = c.getColumnIndex("name");
int Column2 = c.getColumnIndex("script");
int Column3 = c.getColumnIndex("su");
// Check if our result was valid.
c.moveToFirst();
String sData="";
if (c != null) {
// Loop through all Results
do {
String Name = c.getString(Column1);
String Script = c.getString(Column2);
int su = c.getInt(Column3);
sData = sData + Name + " " + Script + " " + su + "\n";
} while (c.moveToNext());
}
ListView lv = (ListView) findViewById(R.id.mainListView);
lv.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice, sData));
} catch (Exception e) {
Log.e("Error", "Error", e);
} finally {
if (myDB != null)
myDB.close();
}
}
You will end up with a ListView with just one single item, the value of sData. You need to create a list such as:
c.moveToFirst();
ArrayList<String> sData = new ArrayList<String>();
if (c != null) {
do {
String Name = c.getString(Column1);
String Script = c.getString(Column2);
int su = c.getInt(Column3);
sData.add(Name + " " + Script + " " + su);
} while (c.moveToNext());
}
ListView lv = (ListView) findViewById(R.id.mainListView);
lv.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice, sData));
I also recommend you change your cursor looping to be similar to this:
// cursor left as it came from the database because it starts at the row before the first row
ArrayList<String> sData = new ArrayList<String>();
while (c.moveToNext()) {
String Name = c.getString(Column1);
String Script = c.getString(Column2);
int su = c.getInt(Column3);
sData.add(Name + " " + Script + " " + su);
}
because at the moment you are not checking the return value of moveToFirst, and it may return false (meaning there are no rows), however your do-while loop means the cursor will be read at least once whether or not it has 0 rows, and if there are 0 rows, you app will crash.
String sData="";
try to make sData a String array. feed that into the adapter.
sData is no array try something like
ArrayList<String> sData = new ArrayList<String>();
if (c != null) {
// Loop through all Results
do {
String Name = c.getString(Column1);
String Script = c.getString(Column2);
int su = c.getInt(Column3);
String newData = Name + " " + Script + " " + su;
sData.add(newData);
} while (c.moveToNext());
}
I have a variable of type Bitmap and I would like to assign it to a Contact from my contact list as the CalledID picture, how would I do that?
You have to creat your own mime type for those.
Here is an example that saves a boolean as my custom mime type to the contacts. It uses the latest SDK 2.1
Important
This example uses DATA1 for data, DATA1 is indexed but it's not recomended for binary data.
In your case to store binary data such as Picture you have to use DATA15.
By convention, DATA15 is used for storing BLOBs (binary data).
public static final String MIMETYPE_FORMALITY = "vnd.android.cursor.item/useformality";
public clsMyClass saveFormality() {
try {
ContentValues values = new ContentValues();
values.put(Data.DATA1, this.getFormality() ? "1" : "0");
int mod = ctx.getContentResolver().update(
Data.CONTENT_URI,
values,
Data.CONTACT_ID + "=" + this.getId() + " AND "
+ Data.MIMETYPE + "= '"
+ clsContacts.FORMALITY_MIMETYPE + "'", null);
if (mod == 0) {
values.put(Data.CONTACT_ID, this.getId());
values.put(Data.MIMETYPE, clsContacts.FORMALITY_MIMETYPE);
ctx.getContentResolver().insert(Data.CONTENT_URI, values);
}
} catch (Exception e) {
Log.v(TAG(), "saveFormality failed");
}
return this;
}
public boolean getFormality() {
if (data.containsKey(FORMALITY)) {
return data.getAsBoolean(FORMALITY);
} else {
// read formality
Cursor c = readDataWithMimeType(clsContacts.MIMETYPE_FORMALITY, this.getId());
if (c != null) {
try {
if (c.moveToFirst()) {
this.setFormality(c.getInt(0) == 1);
return (c.getInt(0) == 1);
}
} finally {
c.close();
}
}
return false;
}
}
public clsMyClass setFormality(Boolean value) {
data.remove(FORMALITY);
data.put(FORMALITY, value);
return this;
}
/**
* Utility method to read data with mime type
*
* #param mimetype String representation of the mimetype used for this type
* of data
* #param contactid String representation of the contact id
* #return
*/
private Cursor readDataWithMimeType(String mimetype, String contactid) {
return ctx.getContentResolver().query(
Data.CONTENT_URI,
new String[] {
Data.DATA1
},
Data.RAW_CONTACT_ID + "=" + contactid + " AND " + Data.MIMETYPE + "= '" + mimetype
+ "'", null, null);
}
Usage is
objContact.setFormality(true).saveFormality();