How to get all single column values then pass it to String[]? - android

I got a big problem here. I create databasehelper class to handle all of my query function.
Now I try to make a function that will load all values of a column from my database but I dont know how to do it. FYI I got 3 columns inside my database table. Here is my code so far:
(UPDATED, it works and gives me values now)
public List<Content> getSearchKeys() {
List<Content> contentList = new ArrayList<Content>();
// The query
String selectQuery = "SELECT * FROM " + TABLE_SEARCH;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// I use do.. while here and it works now, should I better use for loop?
if (cursor.moveToFirst()) {
do {
Content content = new Content();
content.setID(Integer.parseInt(cursor.getString(0)));
content.setsKeys(cursor.getString(1));
content.setAct(cursor.getString(2));
// Adding content to list
contentList.add(content);
} while (cursor.moveToNext());
}
// return content list
return contentList;
}
The problem now is how to pass the result of above function into String[] ? In my Activity I try to use it like this and it's not working:
(Updated)
...
setContentView(R.layout.page_search);
DatabaseHandler db = new DatabaseHandler(this);
List<Content> contents = db.getAllContacts();
final String[] searchQ = new String[contents.size()];
int i =0;
for (Content cn : contents) {
searchQ[i] = cn.getsKeys().toString();
}
final String[] SearchQueries = searchQ;
If I comment the code above and change it to string array like this, then it works:
static final String[] SearchQueries = new String[] { "iPhone", "Mac", "Apple",};
My aim is to replace array above into Array I retrieve from my database. So what's wrong and what's the correct method to handle this? Many thanks for your help.

Problem 1: if cursor is empty but not null, your do while loop fails (change it to a while loop)
Problem 2: to convert to string, you'll need a toString method in your Content class. Then you will write a loop:
String[] queryAsStrings = new String[query.size()];
int i = 0;
for (Content c : query) {
queryAsStrings[i] = c.toString();
}

Related

retrieve data from database what next?

ok I just followed an instruction that I should do this to retrieve sql data from database but it just cuts to there so far I have this inside my databasehelper class.
public void getIconResource(String tblName)
{
SQLiteDatabase db = this.getReadableDatabase();
String getresource = "Select * from " + tblName;
Cursor cursor = db.rawQuery(getresource,null); //null for conditions
if(cursor.moveToFirst())
{
do
{
int resource = cursor.getInt(3);
}
while (cursor.moveToNext());
}
db.close();
}
So somehow this does is it get all the values of my tables 4th column which contains an int... how do I retrieve the value in my MainActivity and save it in an array of integers?
just add everything in a ArrayList and return the arraylist
simply call the method in your main activty
public ArrayList<Integer> getIconResource(String tblName)
{
SQLiteDatabase db = this.getReadableDatabase();
String getresource = "Select * from " + tblName;
Cursor cursor = db.rawQuery(getresource,null); //null for conditions
ArrayList data= new ArrayList<>();
if(cursor.moveToFirst())
{
do
{
int resource = cursor.getInt(3);
data.add(resource);
}
while (cursor.moveToNext());
}
db.close();
}
return data;
}
Well, as you have it, the variable resource is scoped only to the while loop. Even if it wasn't it would constantly get overwritten on each loop iteration.
Instead, you should declare a collection higher up and Add each value to it during your while loop. You could also redefine your function to return the collection if integers.
public List<int> getIconResource(String tblName)
{
SQLiteDatabase db = this.getReadableDatabase();
List<int> myVals = new List<int>();
String getresource = "Select * from " + tblName;
Cursor cursor = db.rawQuery(getresource, null); //null for conditions
if (cursor.moveToFirst())
{
do
{
myVals.Add(cursor.getInt(3));
}
while (cursor.moveToNext());
}
db.close();
return myVals;
}
Also, as a note... string concatenation of a SQL query is a recipe for disaster. Look up SQL Injection and best practices to avoid it before continuing further. It is worth the time to get into good habits early on.
EDIT / ADDENDUM
Unless you also limit your result set returned from your table query, you will be getting every record. The function you have here really has no practical use and would likely cause more problems than any benefits it may have. I would suggest, as an example of a more usable function that returns a specific IconResource based on the IconId:
public int getIconResource(int iconId)
{
SQLiteDatabase db = this.getReadableDatabase();
String getresource = "select IconResource from IconTable where IconId = ?";
PreparedStatement pstmnt = db.prepareStatement(getresource);
pstrmnt.setString(1, iconId);
ResultSet rset = db.executeQuery();
int iconResource;
if (rset.next())
iconResource = rset.getInt("IconResource");
db.close();
return iconResource;
}
Of course, the above is making assumptions of your table structure.
Using the above, in your code elsewhere, you would simply call this function with the IconId and use the output however needed:
int iconResource = getIconResource(5); // returns the IconResource for IconId = 5
The above prevents any possible SQL Injection attacks by using a parameterized query and avoiding the use of dynamic concatenated strings sent to your SQL server.
You may try out the following code:
public List<Integer> getIconResource(String tblName)
{
List<Integer> list = new ArrayList<Integer>();
list.clear();
SQLiteDatabase db = this.getReadableDatabase();
String getresource = "Select * from " + tblName;
Cursor cursor = db.rawQuery(getresource,null); //null for conditions
if(cursor.moveToFirst())
{
do
{
int resource = cursor.getInt(3);
list.add(resource);
}
while (cursor.moveToNext());
}
db.close();
return list;
}
Then call this method in MainActivity and store the List in another Integer type list.
databasehelper dbhelper;
List<Integer> newList = dbhelper.getIconResource("Your tablename");
fot(int i = 0 ; i< newList.size() ; i++){
int yourValue = newList(i);
}

How to access the last word from word within a list of query

I have a list of items queried from my database. This list has two words in each item, the two words are separated by a space. I now want to get access to only the last word after the space.
This the query from my database
public List<String> getList(){
List<String> array = new ArrayList<String>();
String selectQuery = "SELECT * FROM " + TABLE_LIST;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
ArrayList<ArrayList<String>> row = new ArrayList<ArrayList<String>>();
if (cursor .moveToFirst()) {
;
do {
String listName = cursor.getString(cursor.getColumnIndex(ITEM_A));
array.add(listName);
}while(cursor.moveToNext());
}
cursor.close();
return array;
}
Accessing the items from the query
List<String> m = new ArrayList<String>();
m = dbHelper.getList();
System.out.println(m);
This gives the below output
[itemOA AITEME,itemOD BITEMD,itemOC CITEMS, itemOB DTEM]
I however wants to get the last words of the list,
[AITEME, BITEMD, CITEMS ,DTEM]
Thanks for helping.
I think you could restructure your code to save from having to do this, but:
String substr = myString.substring(startIndex);
Will work as long as you always have a known starting point (if it's always going to start with "itemOA" or 6 characters + a single whitespace)

Alternate way to access multiple columns independently from a database?

My application stores three items: "name", "email", "mobile" in its database under the same table. I want to access each of them independently so that I could display their value under their respective TEXTVIEWs. I access them independently because if I access them all through one single function I won't be able to display the values
Currently, I have to write a function for each column so as to get information from it.
Example to get "email"
public String getUserEmail(String mobile) {
String[] columns = new String[] {USER_EMAIL};
Cursor c = MainDataBase.query(REG_INFO_TABLE, columns, USER_MOBILE_NUMBER + "=" + mobile, null, null, null, null);
String result = "";
int email = c.getColumnIndex(USER_EMAIL);
while(c.moveToNext()) {
result = result + c.getString(email);
}
return result;
}
So, if I need the the "name", I'll have to write another function similar to above to get it.
Now, if I need to access 50 such columns, I'll have to make 50 such functions which does not sound good. Is there any other way I can do this? Can arrays be used here?
You should consider creating a User class that holds the data for each User. Then you change getAllRegInfo() to return a User object. This has the advantage that the rest of your app only accesses Users and has no idea where the data comes from. It is also much more expressive to write
User user = getAllRegInfo();
String name = user.getName();
rather than
String[] user = getAllRegInfo();
String name = user[0];
In addition, a User class can have fields of any type rather than being forced to convert all data to String.
Okay, so I found an alternative. It is using arrays only.
Here is the code:
public String[] getAllRegInfo() {
String[] columns = new String[] {USER_NAME, USER_EMAIL, USER_MOBILE_NUMBER};
Cursor c = MainDataBase.query(REG_INFO_TABLE, columns, null, null, null, null, null);
String[] result = new String[3];
for(int j=0; j<3; j++) {
result[j] = "";
}
int[] column = new int[3];
column[0] = c.getColumnIndex(USER_NAME);
column[1] = c.getColumnIndex(USER_EMAIL);
column[2] = c.getColumnIndex(USER_MOBILE_NUMBER);
while(c.moveToNext()) {
for(int i = 0; i<3; ++i) {
result[i] = c.getString(column[i]);
}
}
return result;
}
Of course, one will have to manually asign the array indexes to the columns. Like this:
column[0] = c.getColumnIndex(USER_NAME);
column[1] = c.getColumnIndex(USER_EMAIL);
column[2] = c.getColumnIndex(USER_MOBILE_NUMBER);
The solution seems to be working fine but I'm not sure how scalable it is.

Retrieve specific column of data and store it in string array

I got a sqlite database and i wanted to retrieve a specific column of data and store it into a string array. Inside the database there are two columns. There will be multiple row of data with the same username and I wanted to retrieve the user's "ContentPath" and store it into a string array. But I don't know how to retrieve that specific column data...
public String[] get_contentByEmailID(String emailid){
String[] returnMsg = null;
helper = this.getReadableDatabase();
Cursor c = helper.rawQuery("SELECT tableid, emailid, contentpath" +
" from w_content where emailid='"+emailid"' ", null);
int contentpathColumn = c.getColumnIndex("contentpath");
if (c.moveToFirst()) {
do {
returnMsg = new String[2];
String contentpath = c.getString(contentpathColumn);
returnMsg[0] = emailid_sync;
returnMsg[1] = contentpath;
} while (c.moveToNext());
}
if (c != null && !c.isClosed()) {
c.close();
}
if (helper!=null){
helper.close();
};
return returnMsg;
}
When I called this function to retrieve the data. It comes up with emailid and contentpath.
String values[] = helper.get_contentByEmailID(SettingConstant.EMAIL);
Any comments will be appreciated.
The reason you got array filled with emailid and contentpath is, because you always reset the returnMsg on each row and fill it with such value. Since there will be varying row count, it is generally suggested that you use ArrayList, instead of building static length array.
To fix it, change:
String[] returnMsg = null;
to:
ArrayList<String> returnMsg = new ArrayList<String>();
And then, in your do{}, do something like this:
do {
String contentpath = c.getString(contentpathColumn);
returnMsg.add(contentpath);
} while (c.moveToNext());
Finally, change your return statement to:
return returnMsg.toArray();

Save result from SQL query to ArrayList Android

I'm trying to understand how to save result from SQL queries in android to an arraylist. Actually I find a few questions but none of them can answer why my code is wrong. So here is what I'm trying to do :
String query = null;
query = "SELECT * FROM users WHERE objectId = "+objectId+" AND serverName "+serverName;
SQLiteDatabase db;
// Insert results from query in database.
ArrayList <String[]> result = new ArrayList<String[]>();
ResultSet rs = db.execSQL(query);
int columnCount = rs.getMetaData().getColumnCount();
while(rs.next())
{
String[] row = new String[columnCount];
for (int i=0; i <columnCount ; i++)
{
row[i] = rs.getString(i + 1);
}
result.add(row);
}
And the error is saying that I cannot convert void to ResultSet.
Any suggestions how to fix that or which is the right way to do this.
Thanks in advance
Once your database is open for reading use db.query or db.rawQuery to get a cursor that can be used to create your ArrayList
cursor = db.rawQuery(<query>, null);
if(cursor.getCount() > 0)
{
cursor.moveToFirst();
//add to list here
}

Categories

Resources