I have an android sqlite database in Farsi (Persian) language, and I use the data in that for fill the ListView, but my problem is that I use item name in ListView in my query. For example, I get a name of ListView's text and use it in my query, but some of them does not show me correct answer from DB. I use the Farsi class for queries.
Here is my code:
List<String> getSubjects(String db_name, String name) {
List<String> collection = new ArrayList<String>();
Cursor cursor;
SQLiteDatabase db;
MyDataBaseHelper myDbHelper;
myDbHelper = new MyDataBaseHelper(this, db_name);
try {
cursor = null;
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
myDbHelper.openDataBase();
db = myDbHelper.getReadableDatabase();
cursor = db.rawQuery(
"select distinct type from mydata where group like '%"
+ farsi.ConvertBackToRealFarsi(name) + "%'", null);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
String uname = cursor.getString(cursor
.getColumnIndex("type"));
collection.add(DariGlyphUtils.reshapeText(uname));
} while (cursor.moveToNext());
}
}
} catch (SQLException sqle) {
throw sqle;
}
db.close();
return collection;
}
Related
I am trying to populate a RecyclerView with the data in each column.
I want to retrieve all of the values under a column and return it as a List dynamically.
What is the best way to go about this?
Attached is a sample image of the data:
There is a list of tables I am showing in the app, then the user should be able to click on a table name and see a RecyclerView of all of the values under each column with swipeable tabs.
For the image above, the user should see a recyclerview of CreateDate, then swipe over and see a recyclerview of CreatedByTablet, etc.
The problem I am encountering is how to return all of the values in a column, dynamically. I am not that familiar with SQL so how would I go about accomplishing this? And how would the method know to return a List<String> or a List<Integer>?
Here is some code I wrote to attempt this:
// Get all table names
public List<String> getAllTableNames() {
List<String> tableNames = new ArrayList<>();
try {
String query = "SELECT name FROM sqlite_master WHERE type='table'";
SQLiteDatabase db = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READWRITE);
Cursor cursor = db.rawQuery(query, null);
// Iterate
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast()) {
tableNames.add(cursor.getString(cursor.getColumnIndex("name")));
cursor.moveToNext();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return tableNames;
}
// Get all names of columns inside a table
public List<String> getAllColumnNames(String tableName) {
List<String> names = new ArrayList<>();
try {
String query = "SELECT * FROM " + tableName;
SQLiteDatabase db = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READWRITE);
Cursor cursor = db.rawQuery(query, null, null);
String[] columnNames = cursor.getColumnNames();
names = Arrays.asList(columnNames);
} catch (Exception e) {
e.printStackTrace();
}
return names;
}
public int getColumnType(String tableName, String columnName) {
String[] args = { columnName };
try {
int type;
String query = "SELECT * FROM " + tableName;
SQLiteDatabase db = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READWRITE);
Cursor cursor = db.rawQuery(query, args);
Log.d(TAG, "Column Index: " + String.valueOf(cursor.getColumnIndex(columnName)));
type = cursor.getType(cursor.getColumnIndex(columnName));
return type;
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
public List getAllRows(String tableName, String columnName, int type) {
Log.d(TAG, "Getting all rows");
switch (type) {
case 1:
List<Integer> integerList = createIntegerList(tableName, columnName);
return integerList;
case 3:
List<String> stringList = createStringList(tableName, columnName);
return stringList;
}
return null;
}
private List<Integer> createIntegerList(String tableName, String columnName) {
List<Integer> integerList = new ArrayList<>();
try {
String query = "SELECT * FROM " + tableName;
SQLiteDatabase db = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READWRITE);
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast()) {
int number = cursor.getInt(cursor.getColumnIndex(columnName));
integerList.add(number);
cursor.moveToNext();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return integerList;
}
private List<String> createStringList(String tableName, String columnName) {
List<String> integerList = new ArrayList<>();
try {
String query = "SELECT * FROM " + tableName;
SQLiteDatabase db = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READWRITE);
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast()) {
String name = cursor.getString(cursor.getColumnIndex(columnName));
integerList.add(name);
cursor.moveToNext();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return integerList;
}
How can I return a list of integer or string (depending of column data type) of all the values in a column inside a table in Sqlite android?
I'm trying to do a query with in a query
id = mCursor.getInt(mCursor.getColumnIndex(DatabaseHelper.COLUMN_SUBJECT_ID));
S = new Subject(id, getSubjectDescById(id));
Subjects.add(S);
the getSubjectDescById() function opens up another cursor on its own.
mCursor is opened before the code and closed after it.
Is it risky to have nested Cursors? If so what would be a better alternative to my code
I have not tested this though but i think,Yes you can use Nested cursors
Scenario:
Step-1> Open CURSOR-1
Step-2> Open CURSOR-2 and Use that cursor as a pointer for the new Cursor you care going to create
Step-3> Close CURSOR-2
Step-4> Close Cursor-1
Try this Sample::
private void DemoFunction() throws Exception {
DatabaseHandler mHelper;
SQLiteDatabase db = null;
Cursor mCursor1 = null;
Cursor mCursor2 = null;
try {
mHelper = new DatabaseHandler(getActivity());
db = mHelper.getReadableDatabase();
//make query for buffet-type
mCursor1 = db.rawQuery("<------My First Query ------>", null);
if(mCursor1.moveToFirst()){
do{
mCursor2 = db.rawQuery("<------My Second Query ------>", null);
if(mCursor2.moveToFirst()){
do{
}while(mCursor2.moveToNext());
Log.d("", "");
}
}while(mCursor1.moveToNext());
Log.d("", "");
}
} catch (Exception e) {
if(isErr==false){
errMsg=e.getLocalizedMessage();
isErr=true;
}
throw e;
}finally{
if(db!=null){
if(db.isOpen()) db.close();
}
if(mCursor1!=null||mCursor2!=null){
if(!mCursor2.isClosed())mCursor2.close();
if(!mCursor1.isClosed())mCursor1.close();
}
}
}
Note:- Make sure you close all the cursors
I'm trying to load an sqlite table as an arraylist so that i can use the data in it. I'm not too sure about the sqlite queries but i already have a class built to manipulate the strings as is, which is what i'm more comfortable with. I can load an individual row but i'm not sure how to get the whole table as an arraylist.
I have the following method in my main method
public void ShowCNData()
{
TestAdapter mDbHelper = new TestAdapter(this);
mDbHelper.createDatabase();
mDbHelper.open();
String allData = mDbHelper.getCYData().get(1)[1];
thing.setText(allData);
mDbHelper.close();
}
and the following method in my dbAdapter/Helper class
public ArrayList<String[]> getCYData()
{
ArrayList<String[]> CYData = new ArrayList<String[]>();
try
{
String sql ="SELECT * FROM cnYears ";
Cursor mCur = null;
do
{
mCur = mDb.rawQuery(sql, null);
CYData.add(new String[] {mCur.getString(0),mCur.getString(1),mCur.getString(2),mCur.getString(3),mCur.getString(4)});
}
while (mCur.moveToNext());
return CYData;
}
catch (SQLException mSQLException)
{
Log.e(TAG, "getTestData >>"+ mSQLException.toString());
throw mSQLException;
}
}
How do i load the data into my ArrayList?
Without actual log information, I'd guess your NullPointerException occurs when you get an empty cursor. Try it this way:
//initialize arraylist, execute query etc.
if (cursor.moveToFirst()) {
do {
String[] entry = new String[dataSize];
//pull your data here
data[0] = cursor.getInt(0);
data[1] = cursor.getString(1);
//...
list.add(entry);
} while (cursor.moveToNext());
}
// return arraylist
I have a SQLite table of this tipe
Table Vehicles:
CATEGORY COUNTRY ID NAME EMAIL
A GE 1 BMW sample1#salple.it
A GE 2 Lamborghini sample2#salple.it
B GE 3 BMW sample3#salple.it
I want to select all the entries that have a specified name or a specified category and pass all the parameters how each row in a constructor
Vehicle(String category, String country, int id, String name, String email)
I have implemented this adapter using some tutorials:
public class TestAdapter
{
protected static final String TAG = "DataAdapter";
private final Context mContext;
private SQLiteDatabase mDb;
private DataBaseHelper mDbHelper;
public TestAdapter(Context context)
{
this.mContext = context;
mDbHelper = new DataBaseHelper(mContext);
}
public TestAdapter createDatabase() throws SQLException
{
try
{
mDbHelper.createDataBase();
}
catch (IOException mIOException)
{
Log.e(TAG, mIOException.toString() + " UnableToCreateDatabase");
throw new Error("UnableToCreateDatabase");
}
return this;
}
public TestAdapter open() throws SQLException
{
try
{
mDbHelper.openDataBase();
mDbHelper.close();
mDb = mDbHelper.getReadableDatabase();
}
catch (SQLException mSQLException)
{
Log.e(TAG, "open >>"+ mSQLException.toString());
throw mSQLException;
}
return this;
}
public void close()
{
mDbHelper.close();
}
public boolean SaveVehicles(String category , String country, String id, String name, String email)
{
try
{
ContentValues cv = new ContentValues();
cv.put("Category", category);
cv.put("Country", country);
cv.put("id", id);
cv.put("Name", name);
cv.put("Email", email);
mDb.insert("Vehicles", null, cv);
Log.d("SaveVehicles", "informationsaved");
return true;
}
catch(Exception ex)
{
Log.d("SaveVehicles", ex.toString());
return false;
}
}
}
But I don't know how I could implement the various get methods that I need, to meet a solution to my problem.
Creating an object from a SQL query would look something like this
/**
* #return Returns a list of all objects.
*/
public ArrayList<Object> getAllObjects()
{
// Select All Query
String selectQuery = "SELECT * FROM SOME_TABLE";
// Get the isntance of the database
SQLiteDatabase db = this.getWritableDatabase();
//get the cursor you're going to use
Cursor cursor = db.rawQuery(selectQuery, null);
//this is optional - if you want to return one object
//you don't need a list
ArrayList<Object> objectList = new ArrayList<Object>();
//you should always use the try catch statement incase
//something goes wrong when trying to read the data
try
{
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
//the .getString(int x) method of the cursor returns the column
//of the table your query returned
Object object= new Object(Integer.parseInt(cursor.getString(0)),
Integer.parseInt(cursor.getString(1)),
Integer.parseInt(cursor.getString(2)),
cursor.getString(3),
cursor.getString(4),
cursor.getString(5),
Boolean.parseBoolean(cursor.getString(6))
);
// Adding contact to list
objectList.add(object);
} while (cursor.moveToNext());
}
}
catch (SQLiteException e)
{
Log.d("SQL Error", e.getMessage());
return null;
}
finally
{
//release all your resources
cursor.close();
db.close();
}
return objectList;
}
The code above assumes you have some table in your database named "SOME_TABLE" and that you have an object that takes 7 parameters but you should be able to alter the snippet to make it work for you.
You need to query your database for the data, and then iterate through the returned cursor to pull out the data you need and put it into strings to feed into your constructor.
The query would look something like this (using the info you provided and the query method):
public Cursor fetchList(String category) {
return mDb.query("Vehicles", new String[] { "CATEGORY", "COUNTRY", "ID", "NAME", "EMAIL" }, "Category =" + category,
null, null, null, null);
}
Note that this is a basic query and subject to SQL injection attacks, It should be parameterized to make it less vulnerable, unless you are not going to allow the user to type in the category and rather have them pick from a list you provide.
Anyway, that would return your data in a cursor, with one row for each record that matched the search parameters. From there, you would need to iterate through the returned cursor and pull the data out of it and into strings you can use.
I am new to android . I have an application working with SQLite DB.
I need to push values from database to an arraylist of type object.
The code i used is given here.
private ArrayList<objectname> objectList = new ArrayList<objectname>();
//function used to get values from database
public ArrayList<objectname> getResults() {
MyDb db = new MyDb(this); //my database helper file
db.open();
Cursor c = db.getAllValues(); //function to retrieve all values from a table- written in MyDb.java file
if (c.moveToFirst())
{
do {
String date = c.getString(c.getColumnIndex("date"));
try
{
ob = new objectname();
ob.setDate(c.getString(c.getColumnIndex("date")));// setDate function is written in Class file
objectList.add(ob);
}
catch (Exception e) {
Log.e(MY_DEBUG_TAG, "Error " + e.toString());
}
} while (c.moveToNext());
}
db.close();
return objectList;
}
This is not working correctly. Not shown any errors but i didn't get values in to the arraylist objectList
Please help me..Thanks in advance..
try this:
private ArrayList<objectname> objectList = getResults();
private ArrayList<objectname> getResults() {
MyDb db = new MyDb(this); //my database helper file
db.open();
ArrayList<objectname> resultList = new ArrayList<objectname>();
Cursor c = db.getAllValues(); //function to retrieve all values from a table- written in MyDb.java file
while (c.moveToNext())
{
String date = c.getString(c.getColumnIndex("date"));
try
{
ob = new objectname();
ob.setDate(date);// setDate function is written in Class file
resultList.add(ob);
}
catch (Exception e) {
Log.e(MY_DEBUG_TAG, "Error " + e.toString());
}
}
c.close();
db.close();
return resultList;
}
I had a similar issue with retrieving values from the db using cursors and displaying on screen.. The below solution works for me..
Cursor cur = db.getAllValues();
int index = c.getColumnIndex("date");
cur.moveToFirst();
while (cur.isAfterLast() == false) {
System.out.println(cur.getString(index)); // For debug purposes
String date = cur.getString(index);
try {
ob = new objectname();
ob.setDate(date);
resultList.add(ob);
} catch (Exception e) {
Log.e(MY_DEBUG_TAG, "Error " + e.toString());
}
cur.moveToNext();
}
cur.close();
Probably your query is drawing a blank and moveToFirst is returning false.
What about logging the value of c.getCount() before your if statement?