I am getting a problem in android textview.
I am simply setting text on the android textview like below
pAmount.setText("Rs." + receiptAmount + "/-");
but is showing null in the text
System.out.println("receiptAmount ====>"+ receiptAmount );
I had tried to print the value of receiptAmount to check whether, the value is null or not.
But, It is showing the right value in the log.
What is the issue does any body have any idea.
similarly , other texview are showing the null value in the same activity.
TextView pAmount= (TextView) findViewById(R.id.amount);
1.Call the set text After Declaring the above line in Oncreate.
2.get the Proper data in receiptAmount. Your Problem Solved
pAmount.setText("Rs." + receiptAmount + "/-");
public void FeeGetFeeTypes(String studentId, String fee_slotid) {
// TODO Auto-generated method stub
ArrayList<String> arrayList_FeeType=new ArrayList<String>();
ArrayList<String> arrayList_FeeTypeAmount=new ArrayList<String>();
try{
SQLiteDatabase db = this.getReadableDatabase();
final String MY_QUERY = "select * from feetype where student_id=? and slot_id=?";
Cursor res = db.rawQuery(MY_QUERY, new String[]{ studentId, fee_slotid });
res.moveToFirst();
while (res.isAfterLast() == false){
arrayList_FeeType.add(res.getString(res
.getColumnIndex(FEE_TYPE_COLUMN_FEETYPE)));
arrayList_FeeTypeAmount.add(res.getString(res
.getColumnIndex(FEE_TYPE_COLUMN_FEETYPEAMOUNT)));
}
if(arrayList_FeeType.size()>0){
PrintActivity.sendFeeType(arrayList_FeeType, arrayList_FeeTypeAmount);
}
}
catch(Exception e){
e.printStackTrace();
}
}
This is the code that is resulting the null values. When the data is large, I get out of memory exception
I have created a table with id and tag as column.
id is set as primary key. And in tag column, I have entered more than one value.
So now i want to get the count of how many times the tag value is repeated.
So my table is like this.
Id Tag
---------------------
1 Friend, Family
2 Family, Enemy
and my output should be like this:
friend (1)
family(2)
Enemy(1)
I have written a code but not getting the result I want.
This is MyDatabase.java code:
public Details calculateCount()
{
Details detail = null;
try
{
SQLiteDatabase db=this.getWritableDatabase();
String selectQuery=("select count(*),Tags from photodetails group by Tags" );
Cursor cursor = db.rawQuery(selectQuery, null);
if(cursor.moveToLast())
{
do
{
detail=new Details(Integer.parseInt(cursor.getString(0)),(cursor.getString(1)));
}while( cursor.moveToNext());
}
}
catch(Exception e)
{
e.printStackTrace();
}
return detail;
}
And this is MAinActivity.java code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity2);
getActionBar().setDisplayHomeAsUpEnabled(true);
MyDataBase MyDB = new MyDataBase(this);
Log.d(LOGCAT,"Entered MAinActivity2");
Details c= MyDB.calculateCount();
if(c == null)
{
Log.d(LOGCAT,"C is null");
}
else
{
Log.d(LOGCAT,c.getTag()); // Here iam only retrieving tag dont know how to get that count.
}
}
Pls help me out on this
If you want to get a count, you're going to want to create a method such as a int getCount() method that will return the int value of the count. Currently, you have Details calculateCount() which will return a Details object.
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 have ORMLite database with some fields. I want to select titles from the table where id == id which I get from webservice. I do like that:
try {
Dao<ProcessStatus,Integer> dao = db.getStatusDao();
Log.i("status",dao.queryForAll().toString());
QueryBuilder<ProcessStatus,Integer> query = dao.queryBuilder();
Where where = query.where();
String a = null;
for(Order r:LoginActivity.orders) {
//LoginActivity.orders - array of my objects which I get from webservice
Log.i("database",query.selectRaw("select title from process_status").
where().rawComparison(ProcessStatus.STATUS_ID, "=",
r.getProcess_status().getProccessStatusId()).toString());
}
Log.i("sr",a);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I tried like this but I get only sets of my id, not titles. I tried like this:
Log.i("database", query.selectColumns(ProcessStatus.STATUS_TITLE).where().
eq(ProcessStatus.STATUS_ID, r.getProcess_status().getProccessStatusId())
.toString());
but I have the same result. How should I get data from database?
For selecting an specific field from the table, you could do something like this:
String result = "";
try {
GenericRawResults<String[]> rawResults = yourDAO.queryRaw("select " +
ProcessStatus.STATUS_TITLE +" from YourTable where "+
ProcessStatus.STATUS_ID + " = " +
r.getProcess_status().getProccessStatusId());
List<String[]> results = rawResults.getResults();
// This will select the first result (the first and maybe only row returned)
String[] resultArray = results.get(0);
//This will select the first field in the result which should be the ID
result = resultArray[0];
} catch (Exception e) {
e.printStackTrace();
}
Hope this helps.
It's hard to properly answer this question without seeing all of the classes of the processStatusId field and others. However I think you are doing too much raw method and may not be properly escaping your values and the like.
I would recommend that you use the IN SQL statement instead of what you are doing in the loop. Something like:
List<String> ids = new ArrayList<String>();
for(Order r : LoginActivity.orders) {
ids.add(r.getProcess_status().getProccessStatusId());
}
QueryBuilder<ProcessStatus, Integer> qb = dao.queryBuilder();
Where where = qb.where();
where.in(ProcessStatus.STATUS_ID, ids);
qb.selectColumns(ProcessStatus.STATUS_TITLE);
Now that you have built your query, either you can retrieve your ProcessStatus objects or you can get the titles themselves using dao.queryForRaw(...):
List<ProcessStatus> results = qb.query();
// or use the prepareStatementString method to get raw results
GenericRawResults<String[]> results = dao.queryRaw(qb.prepareStatementString());
// each raw result would have a String[] with 1 element for the title
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.