I have problem with my database row number. My table has 3 columns(ROWID,WORD,DEFINITION) and 3 row. I delete second row and then I try to query same row, my app fails. is this an autoincrement problem? what should I do?
Here is my code;
//Get that function
public String getThat(int id) {
String result= "";
String[] columns = new String[]{KEY_ROWID,KEY_WORD,KEY_DEFINITION};
Cursor c = ourDatabase.query(DB_TABLE, columns, KEY_ROWID +
"=" + id, null, null, null, null,null);
if(c!=null){
c.moveToFirst();
}
result = c.getString(c.getColumnIndex(KEY_DEFINITION));
return result;
}
//delete function
public boolean deleteRecords(long rowId){
return ourDatabase.delete(DB_TABLE, KEY_ROWID +"="+rowId,null)>0;
}
When the query doesn't match anything, a non-null Cursor is returned anyway but it doesn't contain any rows. When you try to access data from a non-existing row an exception is thrown.
Change this
if(c!=null){
c.moveToFirst();
}
result = c.getString(c.getColumnIndex(KEY_DEFINITION));
to something like
if(c.moveToFirst()){
result = c.getString(c.getColumnIndex(KEY_DEFINITION));
}
i.e. check the return value of moveTo..() and only access cursor data if the move succeeded and the cursor points to a valid row.
Related
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);
}
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.
I have a list of users in my list view which is populated by retrieving data from documentum . If I click on any row of this least (each row represent one user) I should be able to see all of their information listed down .(This is my problem )
public void selectedItemFromListView(){
selected = lwAllUserGrp.getSelectionModel().getSelectedItem();
System.out.println(selected);
String query =" select * from dm_user where user_name = '#aclName'" ;
String test = query.replace("#aclname", selected);
GetDataWithDqlProfile(_session , query , "user_login_name" , "user_address" , "user_state" );
System.out.println(user.getAddress());
System.out.println(user.getState());
System.out.println(user.getUsername());
}
if I click on a row of list view I can successfully see who is selected and I need to retrieve all the other attributes of that username (same person) from documentum via DQL .
private void GetDataWithDqlProfile(IDfSession session, String Query, String username , String address , String state ) {
try {
IDfQuery UpdateQuery = new DfQuery();
UpdateQuery.setDQL(Query);
IDfCollection col = UpdateQuery.execute(_session, IDfQuery.DF_QUERY);
user.setAddress(col.getString(username));
user.setUsername(col.getString(address));
user.setState(col.getString(state));
col.close();
} catch (Exception e) {
Alert alert = new Alert(Alert.AlertType.ERROR, e.getMessage());
alert.showAndWait();
Logs.WriteLog(LoginController.Repository + ",User:" + LoginController.Username, "DQL Query", e.toString());
e.getStackTrace();
}
and my output is :
User's name
null
null
null
I've tried the DQL query in DQL tester and it works well
In order to fetch rows from IDfCollection you have to call next() on the collection object. This method both advances to the next row and returns a boolean if successful. Use a boolean test (e.g., while or if) to iterate, like this:
IDfCollection col = UpdateQuery.execute(_session, IDfQuery.DF_QUERY);
if (col.next()) {
user.setAddress(col.getString(username));
user.setUsername(col.getString(address));
user.setState(col.getString(state));
}
col.close();
The iteration is necessary even if the collection contains only one row. In other words, you need to manually advance to the first row.
1) As #eiviamu already mentioned, you have to call IDfCollection.next() to get the next row.
2) Your code, among other problems, has one documentum-related: closing of collection must happen always in finally block.
Otherwise you can get unclosed collection which might lead to memory leaks and weird application behavior (e.g. if I'm not mistaken there are 9 simultaneous open collections are allowed for one DCTM session by default, and if you exceed this limit an exception will be thrown)
For those of you referring to this question later here is how I solved the problem :
public ArrayList<User> GetDataWithDqlpro(IDfSession session, String Query, String username , String state , String address) {
try {
IDfQuery UpdateQuery = new DfQuery();
UpdateQuery.setDQL(Query);
IDfCollection col = UpdateQuery.execute(_session, IDfQuery.DF_QUERY);
while (col.next()) {
list.add( new User(col.getString(username),col.getString(address) , col.getString(state)));
}
col.close();
}catch (Exception e) {
Alert alert = new Alert(Alert.AlertType.ERROR, e.getMessage());
alert.showAndWait();
Logs.WriteLog(LoginController.Repository + ",User:" + LoginController.Username, "DQL Query", e.toString());
e.getStackTrace();
}
return (ArrayList<User>) list;
}
public void selectedItemFromListView(){
selected = lwAllUserGrp.getSelectionModel().getSelectedItem();
System.out.println(selected);
String Query = "select user_login_name , user_state , user_address from dm_user where user_login_name ='#aclname'";
Query = Query.replace("#aclname",selected );
ArrayList<User> allUserNames = GetDataWithDqlpro(_session, Query, "user_login_name","user_address","user_state");
for (int i = 0 ; i <= allUserNames.size()-1 ; i++ ){
if (selected.compareToIgnoreCase(allUserNames.get(i).getUsername() ) == 0){
System.out.println(allUserNames.get(i).getState() );
System.out.println(allUserNames.get(i).getAddress() );
System.out.println(allUserNames.get(i).getUsername() );
}
}
}
Worth mentioning that I have a class called User with constructor and get and set methods
I hope it will help some one :)
when I call select in other function, there is problem in line number 3.
Is it wrong?
public String[] select(int n){
db = helper.getReadableDatabase();
Cursor c = db.rawQuery("SELECT * FROM info WHERE number='" + n + "'", null);
}
The rawQuery() looks good, though usually you wouldn't quote integers as 'string literal'.
However, a non-void method must return a value and your method doesn't return anything. Add return null; to make it compile; implement a loop that builds a string array to return a non-null value.
I am getting an error like "No Such Column while compiling DELETE FROM table".
please help
public String getData() {
String[] columns = new String []{KEY_ROWID, KEY_HEADER, KEY_QUOTE_VALUE};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
String result = "";
int iRow = c.getColumnIndex(KEY_ROWID);
int iHeader = c.getColumnIndex(KEY_HEADER);
int iQuote_value = c.getColumnIndex(KEY_QUOTE_VALUE);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = result + c.getString(iRow)+ "#" +c.getString(iHeader)+ ":" +c.getString(iQuote_value)+ ":";
}
return result;
}
public void deleteEntry(String Deldata1) throws SQLException {
ourDatabase.delete(DATABASE_TABLE, KEY_HEADER + "=" + Deldata1 , null);
}
}
please help me
The Deldata1 variable is probably not initialized to a quoted string.
Print the value of KEY_HEADER and Deldata1 in the deleteEntry function before the delete call.
Atleast one should be the name of a table in the database. The other can be a table name or a quoted string.