Retrieve specific column of data and store it in string array - android

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();

Related

Set all returned data to textview from sqlite

I want to set the random data from my table to a single textview.I am able to fetch random data from sqlite but I can not set it to my textview.Probably I should not use setText to put it there.
"Generate" function should bring each time random data from that table.
- main class -
I am having my problem down here (Part of the above class)
private void generatecompliment() {
Cursor cursor = mydb.generatecompliments();
cursor.moveToFirst();
String[] compliments1 = new String[cursor.getCount()];
//cursor.moveToNext();
shwtxt.setText(cursor.getString(1));
}}
- databasehelper class-
public Cursor generatecompliments () {
SQLiteDatabase sqLiteDatabase2 = getReadableDatabase();
String sql ="SELECT * FROM " + TABLE_NAME2 + "ORDER BY RANDOM() LIMIT 1";
return sqLiteDatabase2.rawQuery(sql, null);
}
}
Note:I have a third class which uses another table but I did not put it here since its working fine.
Thanks for help.
You have two options
I believe that you would want something like :-
private void generatecompliment() {
boolean done_first_column = false;
StringBuilder sb = new StringBuilder();
Cursor cursor = mydb.generatecompliments();
if (cursor.moveToFirst()) {
for (String column_name; cursor.getColumnNames) {
if (done_first_column) {
sb.append(" "); //<<<<<<<<<< separator between column data
}
sb.append(cursor.getString(csr.getColumnIndex(column_name));
done_first_column = true;
}
}
cursor.close();
shwtxt.setText(sb.toString());
}
or alternatively
private void generatecompliment() {
StringBuilder sb = new StringBuilder();
Cursor cursor = mydb.generatecompliments();
if (cursor.moveToFirst()) {
for (int i =0; i < cursor.getColumnCount(); i++) {
if (i > 0) {
sb.append(" "); //<<<<<<<<<< separator between column data
}
sb.append(cursor.getString(i);
}
}
cursor.close();
shwtxt.setText(sb.toString());
}
The difference being that the first gets a String array of the column names using the Cursor getColumnNames method, whilst the second retrieves the number of columns retrieved from the Cursor getColumnCount method.
This assumes that by saying all returned data that you want data from all columns concatenated.
This also assumes that you want a space separating the data from each column.
There is also the assumption that shwtxt has been appropriately instantiated.
The above code is in-principle code, it has not been tested or run so it may caontain some small errors.

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);
}

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.

How to retrieve single sqlite column and store rows into array

Im new to android, and i use Sqlite to store an array of type double into a column called "KEY_VALUE"
public long createEntry(Double rates) {
ContentValues cv = new ContentValues();
cv.put(KEY_VALUE, rates);
return ourDatabase.insert(TABLE, null, cv);
}
I put the data into the columns here via another class
for(i=0;i<37;i++){
entry.createEntry((theRSSHandler.rates()[i]));
}
Now i would like to retrieve the column i saved and get each row as an array element, ive seen and tried other similar solutions but they have not worked.
Here is the method i use to try and get the column data But it has failed.
public Double[] getData() {
String[] col = {KEY_VALUE};
Cursor c = ourDatabase.query(TABLE, col, KEY_VALUE , null, null, null, null);
Double[] result = null;
if(c != null){
c.moveToFirst();
}
int iVal = c.getColumnIndex(KEY_VALUE);
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result[c.getPosition()] = c.getDouble(iVal);
}
return result;
}
you are trying to put values in an array that has not been initialized.
Double[] result = null;
needs to be followed up with something like...
result = new Double[100];
i think you probably want to initialize it with the number of records pointed to by the cursor
result = new Double[c.count()];

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

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();
}

Categories

Resources