Android: Populating a GridtView from the SQLite Database - sqlite

Gridview is not populating any data from Sqlite database while saving the data in to database. Logcat is not generating any error also.
My DB is.
public Cursor getAllRows() {
SQLiteDatabase db = this.getReadableDatabase();
//String where = null;
Cursor c = db.rawQuery("SELECT * FROM " + DATAALL_TABLE, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
Mainactivity.
public void populateListView() {
Cursor cursor = db.getAllRows();
String[] fromFieldNames = new String[] {
DBHelper.COURSES_KEY_FIELD_ID1, DBHelper.FIELD_MATERIALDESC, DBHelper.FIELD_MATERIALNUM
};
int[] toViewIDs = new int[] {
R.id.textView1, R.id.textView3, R.id.textView2
};
SimpleCursorAdapter myCursorAdapter;
myCursorAdapter = new SimpleCursorAdapter(getBaseContext(), android.R.layout.activity_list_item, cursor, fromFieldNames, toViewIDs, 0);
GridView myList = (GridView) findViewById(R.id.gridView1);
myList.setAdapter(myCursorAdapter);
}
Post to the honorable member #MikeT advise its works fine but need alignment ,
as is
expected format

Your issue, assuming that there is data in the table, is likely that R.id.textView1 .... 3 are nothing to do with the layout passed to the SimpleCursorAdapter. i.e. Your issue is likely to do with the combination of the layout passed to the SimpleCursorAdapter and the Id's of the views passed as the to id's.
If you were to use :-
gridview = this.findViewById(R.id.gridView1);
csr = DBHelper.getAllRows();
myCursorAdapter = new SimpleCursorAdapter(
getBaseContext(),
//android.R.layout.simple_list_item_2,
android.R.layout.activity_list_item,
csr,
new String[]{
SO50674769DBHelper.COURSES_KEY_FIELD_ID1
//SO50674769DBHelper.FIELD_MATERIALDESC,
//SO50674769DBHelper.FIELD_MATERIALNUM
},
new int[]{android.R.id.text1}, //<<<< ID of the available view
0
);
gridview.setAdapter(myCursorAdapter);
Then result would be along the lines of :-
Changing to use a different stock layout and 2 fields as per :-
gridview = this.findViewById(R.id.gridView1);
csr = DBHelper.getAllRows();
myCursorAdapter = new SimpleCursorAdapter(
getBaseContext(),
android.R.layout.simple_list_item_2,
//android.R.layout.activity_list_item, //<<<< Changed Layout
csr,
new String[]{
SO50674769DBHelper.COURSES_KEY_FIELD_ID1,
SO50674769DBHelper.FIELD_MATERIALDESC,
//SO50674769DBHelper.FIELD_MATERIALNUM
},
new int[]{android.R.id.text1, android.R.id.text2}, //<<<< ID's of the 2 views
0
);
gridview.setAdapter(myCursorAdapter);
Note The DatabaseHelper class is so named for my convenience.
Would result in :-
As such I suspect that you need to change the layout to a one of your own.
Additionally, as hinted at your getAllRows method is not at all ideal.
Checking for a null Cursor is useless as a Cursor returned from rawQuery will not be null. It may be empty in which case the Cursor getCount method would return 0 ().
moveToFirst is also a waste.
Simply have :-
public Cursor getAllRows() {
SQLiteDatabase db = this.getReadableDatabase();
return db.rawQuery("SELECT * FROM " + DATAALL_TABLE, null);
}

Related

Return list of Integers with SQLiteDatabase.rawQuery

I'm trying to write a function that returns a list of Integers using SQLiteDatabase.rawQuery.
This is how i'm imagining it but doesn't work..
public List<Integer> queryInt(String sql, String[] whereArgs){
//fetch string array
List<Integer> r = new ArrayList<Integer> ();
SQLiteDatabase db = getReadableDatabase();
Cursor c = db.rawQuery(
sql,
whereArgs
);
return c.toInt(); //something that does this
}
If someone has a clue, thanks for the help !
You need to move within the Cursor before you can access any of the data (initially a Cursor will be positioned at before the first row (position -1)).
So your queryInt method could be :-
public List<Integer> queryInt(String sql, String[] whereArgs){
//fetch string array
List<Integer> r = new ArrayList<>();
SQLiteDatabase db = getReadableDatabase();
Cursor c = db.rawQuery(
sql,
whereArgs
);
// Loop through the Cursor
while(c.moveToNext()) {
r.add(c.getInt(0)); //<<<< see note
}
c.close(); //<<<< Should always close a Cursor when done with it.
return r;
}
Note 0 assumes that the data is to be extracted from the first column. However it is considered better practice to not hard code the column offset but to get the column offset based upon the column name so r.add(c.getInt(c.getColumnIndex(your_column_name_as_a_string))); would be recommended.
If there are no rows then the above would return an empty List, so you may need to check the returned List's size.

Cursor inside another cursor in sqlite db

I have the below code where I am using nested cursors. Both of them are not null but I am getting error
"android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0" on the inner cursor.
Cursor cursor3 = null;
Cursor cursor2 = db.getAllFriendsChat();
cursor2.moveToFirst();
while (!cursor2.isAfterLast()) {
String number = cursor2.getString(cursor2.getColumnIndexOrThrow(ChatModel.COLUMN_CHAT_SENT_TO));
cursor3 = db.getName(number);
String name = cursor3.getString(cursor3.getColumnIndexOrThrow(db.KEY_NAME));
db.insertList(name, number);
cursor3.close();
cursor2.moveToNext();
}
cursor2.close();
getName() Method:
public Cursor getName(String phone) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor c = db.rawQuery("select * from " + TABLE_STUDENTS + " where phone_number = " + phone, null);
if (c != null) {
c.moveToFirst(); //***I see that this statement is executed.***
}
return c;
}
I am unable to understand where I am doing mistake. Is there a different way to handle nested cursors in sqlite db. Pls help.
Thanks !
rawQuery() never returns null.
To test whether a cursor is empty, you have to check whether moveToFirst() succeeds, or call isAfterLast().

how can i bind an object to a gridview

My code is
public Emp GetEmpByEmpno(int empno)
{
using (con)
{
if (con.State == ConnectionState.Closed)
{
con.ConnectionString = constr;
con.Open();
}
cmd.CommandText = "sp_emp_GetempByEmpno";
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#eno",empno);
dr=cmd.ExecuteReader();
Emp obj=null;
while(dr.Read())
{
obj=new Emp();
obj.Empno=int.Parse(dr["Empno"].ToString());
obj.Ename=dr["Ename"].ToString();
obj.Sal=dr["Sal"].ToString();
obj.Deptno=int.Parse(dr["Deptno"].ToString());
}
return obj;
}
}
Here I fetch the record based on employee number, whenever i pass empno in textbox search button onClick, the respective employee should display in grid view. How can i bind the object to grid view?
Employee obj=EmpDeptBus.GetEmployeeByEmpno(int.Parse(txtEmpno.Text));
gvemp.DataSource = c;
gvemp.DataBind();
You should be able to just say
gvemp.DataSource = obj;
That's really all you need to do to bind the object.
Also, change your
while(dr.Read())
to
if(dr.Read())
You're only expecting one record so only fetch one. Also put your return obj outside your using to make sure everything is properly disposed before you return to the calling function.
Try making sure that txtEmpno.Text holds an int value before you attempt to pass it to this method or it will blow up. Never, ever trust user input. You could do something like:
int empNo = 0;
if(int.TryParse(txtEmpNo.Text.Trim(), out empNo)
{
// then call the function and bind your grid using the empNo as the
// variable holding the employee number.
}
else
{
// otherwise handle the fact that the user entered a non-numeric.
}

javaFX table view couldn't update table crash when adding new rows

I have TableView with number of columns, I have set onEditCommit method on the first column to get the value inserted and then retrieve data from database based on that value and set the retrieved data in other columns. the table couldn't update it's content.
accountNoCol.setOnEditCommit(new EventHandler<CellEditEvent<Bond, String>>() {
#Override
public void handle(CellEditEvent<Bond, String> event) {
String newValue = event.getNewValue();
Bond bond = event.getRowValue();
int selectedRow = event.getTablePosition().getRow();
if (isInteger(newValue)) {
((Bond) event.getTableView().getItems().get(
event.getTablePosition().getRow())).setAccountNo(newValue);
if (isDebtAccount(newValue)) {
String accountName = getDebtAccountName(newValue);
String coinName = getCoinName(newValue);
float coinExchange = getCoinExchange(newValue);
bond.setAccountName(accountName);
bond.setCoinName(coinName);
bond.setCoinExchange(coinExchange);
bondTable.getSelectionModel().select(selectedRow, statementCol);
} else if (isNonDebtAccount(newValue)) {
String accountName = getNonDebtAccountName(newValue);
bond.setAccountName(accountName);
bond.setCoinName(getDefaultCoinName());
bond.setCoinExchange(1);
bondTable.getSelectionModel().select(selectedRow, statementCol);
}
else {
System.out.println("wrong acount name");
// show accounts table - i guess
}
} else {
if (newValue.length() == 0) {
System.out.println("length : " + newValue.length());
((Bond) event.getTableView().getItems().get(
event.getTablePosition().getRow())).setAccountNo(newValue);
}
}
}
});
I tried to use this next line but the table get crashed after adding new rows
bondData.set(selectedRow,Bond);
Solved. The problem was the table get crashed when am trying to open new stage from a listener on a tablecolumn. so on listener and before fire my action which is opening new stage i set the tablecolumn uneditable.

Not able to return JsonResult

The following query is working successfully.
var tabs = (
from r in db.TabMasters
orderby r.colID
select new { r.colID, r.FirstName, r.LastName })
.Skip(rows * (page - 1)).Take(rows);
Now I want to return JsonResult as like
var jsonData = new
{
total = (int)Math.Ceiling((float)totalRecords / (float)rows),
page = page,
records = totalRecords,
rows = (from r in tabs
select new { id = r.colID, cell = new string[] { r.FirstName, r.LastName } }).ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
But it will gives me an error like:
The array type 'System.String[]' cannot be initialized in a query result. Consider using 'System.Collections.Generic.List`1[System.String]' instead.
What should I do to get expected result?
I suspect that it's as simple as pushing the last part into an in-process query using AsEnumerable():
var jsonData = new
{
total = (int)Math.Ceiling((float)totalRecords / (float)rows),
page = page,
records = totalRecords,
rows = (from r in tabs.AsEnumerable()
select new { id = r.colID,
cell = new[] { r.FirstName, r.LastName } }
).ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
You may want to pull that query out of the anonymous type initializer, for clarity:
var rows = tabs.AsEnumerable()
.Select(r => new { id = r.colID,
cell = new[] { r.FirstName, r.LastName })
.ToArray();
var jsonData = new {
total = (int)Math.Ceiling((float)totalRecords / (float)rows),
page,
records = totalRecords,
rows
};
It's because it's adding to the LINQ query that is your tabs IQueryable. That is then trying to turn the LINQ expression into a SQL query and the provider doesn't support projecting arrays.
You can either change the assignment of the tabs variable's LINQ expression to use ToList to materialize the DB results right then and there, or you can add .AsEnumerable() to the LINQ expression assigned to the rows field of the anonymous type that is your JsonResult. AsEnumerable will demote the IQueryable to an IEnumerable which will prevent your second LINQ query from trying to be added to the DB query and just make it a LINQ-to-objects call like it needs to be.

Resources