I have saved product name in one column in Sqllite database .Lot of product name are already saved there now, I need to get all product name sent it to web service.For example egg, briyani, idly.
I have used it this code in Sqllite but String is not append.I have mention below this code:
public String fetchMyRowid(String column_name)
{
String query = "select "+column_name+" From " + TABLErestaurant;
mCursor =db.rawQuery(query, null);
StringBuffer buf = new StringBuffer();
if (mCursor.moveToFirst()) {
buf.append(mCursor.getString(0)+",");
}
return buf.toString();
}
if (mCursor.moveToFirst()) {
buf.append(mCursor.getString(0)+",");
}
The problem is you're not iterating through your results. Do this instead:
while(mCursor.moveToNext()) {
buf.append(mCursor.getString(mCursor.getColumnIndex(column_name))+",");
}
your code is fine but you forgate: db.getWritableDatabase(); or getreadableDatabase()
i have modify your code here DBController is my class public class DBController extends SQLiteOpenHelper
so your code ll be..
public String fetchMyRowid(String column_name, DBController db) {
String query = "SELECT " + column_name + " FROM " + TABLErestaurant;
SQLiteDatabase dd = db.getWritableDatabase();
cursor = dd.rawQuery(query, null);
StringBuffer buf = new StringBuffer();
if(cursor.getCount() > 0 || cursor != null){
do {
Log.e("name--->", "" + cursor.getString(0));
buf.append(cursor.getString(0) + ",");
} while (cursor.moveToNext());
Log.e("name---> buffeer-->", "" + buf);
}
return buf.toString();
}
Just make a small change here,
instead of this line ,
String query = "select "+column_name+" From " + TABLErestaurant;
try this line
String query = "select * From " + TABLErestaurant;
Related
I am using the following method to query my SQLite database with LIKE statement.
public List<Bean> getWords(String englishWord) {
if(englishWord.equals(""))
return new ArrayList<Bean>();
String sql = "SELECT * FROM " + TABLE_NAME +
" WHERE " + ENGLISH + " LIKE ? ORDER BY LENGTH(" + ENGLISH + ") LIMIT 100";
SQLiteDatabase db = initializer.getReadableDatabase();
Cursor cursor = null;
try {
cursor = db.rawQuery(sql, new String[]{"%" + englishWord.trim() + "%"});
List<Bean> wordList = new ArrayList<Bean>();
while(cursor.moveToNext()) {
String english = cursor.getString(1);
String mal = cursor.getString(2);
wordList.add(new Bean(english, bangla));
}
return wordList;
} catch (SQLiteException exception) {
exception.printStackTrace();
return null;
} finally {
if (cursor != null)
cursor.close();
}
}
I would like to change the above code for that it will query for exact match. I tried to modify the code as below but I do not how to get the mal string.
public void getoneWords(String englishWord) {
String sql = "SELECT * FROM " + TABLE_NAME +
" WHERE " + ENGLISH + " =?";
SQLiteDatabase db = initializer.getReadableDatabase();
Cursor cursor = null;
try {
cursor = db.rawQuery(sql, new String[]{englishWord});
while(cursor.moveToNext()) {
String english = cursor.getString(1);
String mal = cursor.getString(2);
}
} finally {
if (cursor != null)
cursor.close();
}
}
Method getoneWords for what. You should return mal and english in this function.
return new Bean(english, mal);
If you need first word, just cursor.moveToFirst and delete while loop:
String english = cursor.getString(1);
String mal = cursor.getString(2);
return new Bean(english, mal);
I finally solved this problem myself.
public String getoneWords(String englishWord) {
String sql = "SELECT * FROM " + TABLE_NAME +
" WHERE " + ENGLISH + " =?";
SQLiteDatabase db = initializer.getReadableDatabase();
Cursor cursor = null;
String meaning = "";
try {
cursor = db.rawQuery(sql, new String[] {englishWord});
if(cursor.getCount() > 0) {
cursor.moveToFirst();
meaning = cursor.getString(2);
}
return meaning;
}finally {
cursor.close();
}
}
In your getoneWords() you are not returning the queried values.
As you have two return values you would either need to wrap them in a Pair or create a "holder" Object (e.g. class Words(String english, String mal)) for the return values.
If your Query returns multiple matches you would need to return a list of those Objects. Otherwise, your above Code would just return the last match.
So you need to alter your function to return the queried
public Pair<String,String> getoneWords(String englishWord) {
Pair<String,String> result = null;
...
if(cursor.moveToNext()) {
String english = cursor.getString(1);
String mal = cursor.getString(2);
result = new Pair<String,String>(english, mal);
}
...
return result;
}
I'm getting a null pointer exception on the following line of code
attendanceList = dbHelper.getAttendance(surName, name);
both surName and name are not null, have size() > 0 and attendanceList is of type ArrayList and here is the getAttendance function:
public ArrayList<Attendance> getAttendance(String surName, String name)
{
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<Attendance> attendanceList = new ArrayList<>();
Cursor cursor = db.rawQuery("SELECT * FROM " + ATTENDANCE_TABLE + " WHERE " + COLUMN_SURNAME + " =? AND "
+ COLUMN_NAME + " =?", new String[] {surName, name});
if(cursor .moveToFirst())
{
while(!cursor.isAfterLast())
{
Attendance attendance = new Attendance();
attendance.setDate(cursor.getString(cursor.getColumnIndex(COLUMN_DATE)));
attendance.setName(cursor.getString(cursor.getColumnIndex(COLUMN_NAME)));
attendance.setSurName(cursor.getString(cursor.getColumnIndex(COLUMN_SURNAME)));
attendance.setState(cursor.getString(cursor.getColumnIndex(COLUMN_STATE)));
attendance.setTerm(cursor.getInt(cursor.getColumnIndex(COLUMN_TERM)));
attendance.setSubject(cursor.getString(cursor.getColumnIndex(COLUMN_SUBJECT_NAME)));
attendanceList.add(attendance);
cursor.moveToNext();
}
cursor.close();
db.close();
return attendanceList;
}
else
{
cursor.close();
db.close();
return null;
}
}
There is no syntax error in the above function, and I know it shouldn't return null because I see the content of the ATTENDANCE_TABLE using DB Browser for SQLite. Can someone point what is wrong with my code? I feel like I wrote 1 + 1 = 2 and getting an error..
Try this... SQLiteDbHelper is my DataBase Class where my table is defined. Table_Name is string in which my table name is stored
cursor = db.rawQuery("SELECT * FROM "+SQLiteDBHelper.TABLE_NAME+" WHERE "+SQLiteDBHelper.COLUMN_SURNAME+"=? AND "+SQLiteDBHelper.COLUMN_NAME+"=?",new String[] {surName,name});
if (cursor != null) {
if(cursor.getCount() > 0) {
cursor.moveToFirst();
//Retrieving User SurName and Name
String s_name = cursor.getString(cursor.getColumnIndex(SQLiteDBHelper.COLUMN_SURNAME));
String _name= cursor.getString(cursor.getColumnIndex(SQLiteDBHelper.COLUMN_NAME));
Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_SHORT).show();
I am pretty sure that it not surName or name that causes NullpointerException, but dbHelper is.
So please check if you are initialising your dbHelper after this line
attendanceList = dbHelper.getAttendance(surName, name);
If so, then move it above and your crash will be fixed.
Hope it helps.
I created a table with three columns id, name and discipline.
I want to find the student name given the discipline.
Following is my method:
String findstudent(String disc){
SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
String find = "SELECT * FROM "+ TABLE_STUDENTS + " WHERE "+KEY_DISCIPLINE +" = " +disc ;
Cursor cursor = sqLiteDatabase.rawQuery(find,null);
cursor.moveToFirst();
String found =cursor.getString(1);
return found;
}
When I use it, the application stops working.
I am not sure. But, you can try this way
Cursor.moveToFirst();
do{
//get the data
String found =cursor.getString(cursor.getColumnIndexOrThrow("COLUMN NAME"));
}while(Cursor.moveNext);
Try the following code:
String find = "SELECT *<enter code here>
FROM "+ TABLE_STUDENTS + "
WHERE "+KEY_DISCIPLINE +" = '" + disc + "'" ;
Try this:
String findstudent(String disc){
Cursor cursor;
cursor = this.db.query(TABLE_STUDENTS,null, KEY_DISCIPLINE +" = "+ disc, null, null, null, null,null );
cursor.moveToFirst();
String found =cursor.getString(0);
return found;
}
Hope it Helps!!
public Cursor findstudent(String disc){
SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
String[] find = new String[]{ col1,col2,col3};//all fields in db in need
String order=col1;
Cursor c=db.query(TABLE_STUDENTS, find, KEY_DISCIPLINE +" = " +disc, null, null, null, order);
c.moveToFirst();
db.close();
return c;
}
In the activity include this:
DataBaseHandler db = new DataBaseHandler(this);
try {
Cursor c = db.displayName(your_disc);
startManagingCursor(c);
if (!c.moveToFirst()) {
System.out.println("!Move " + posnumber);
} else {
String idname = c.getString(c
.getColumnIndex(DataBaseHandler.KEY_NAME));
System.out.println("null:");
System.out.println("Move " + idname);
return true;
}
c.close();
stopManagingCursor(c);
} catch (Exception ex) {
}
Please let me know why my where clause isn't working. I tried using the query instead of rawquery but no luck.
try {
String categoryex = "NAME";
DBHelper dbHelper = new DBHelper(this.getApplicationContext());
MyData = dbHelper.getWritableDatabase();
Cursor c = MyData.rawQuery("SELECT * FROM " + tableName + where Category = '+categoryex'" , null);
if (c != null ) {
if (c.moveToFirst()) {
do {
String firstName = c.getString(c.getColumnIndex("Category"));
String age = c.getString(c.getColumnIndex("Text_Data"));
results.add( firstName + " Directions: " + age);
}while (c.moveToNext());
}
}
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
} finally {
if (MyData != null)
MyData.execSQL("DELETE FROM " + tableName);
MyData.close();
}
try... (you left out a double-quote before where.
Cursor c = MyData.rawQuery("SELECT * FROM " + tableName + " where Category = '" +categoryex + "'" , null);
I think you should use rawQuery in this form:
rawQuery("SELECT * FROM ? where Category = ?", new String[] {tableName, categoryex});
I think it's more secure this way.
Your quotes are buggered:
Cursor c = MyData.rawQuery("SELECT * FROM " + tableName + " where Category = '" + categoryex + "'" , null);
You also should read up on SQL injection attacks.
it will be more easy if you use this technique instead of rawQuery,its easy way change your table name, columns and where conditions accordingly.
public ArrayList<Invitees> getGroupMembers(String group_name) {
ArrayList<Invitees> contacts = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
String[] projection = {COLUMN_CONTACT, COLUMN_PHONE_NUMBER};
String selection = COLUMN_GROUP_NAME + "=?";
String[] selectionArgs = {group_name};
Cursor cursor = db.query(GROUPS_TABLE_NAME, projection, selection, selectionArgs, null, null, null);
if (cursor.moveToFirst()) {
do {
Invitees invitees = new Invitees();
invitees.setUserName(cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_CONTACT)));
invitees.setInviteePhone(cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_PHONE_NUMBER)));
contacts.add(invitees);
} while (cursor.moveToNext());
}
return contacts;
}
public void execute(String sqlStatement) throws DBException {
Statement statement;
try {
statement = database.createStatement(sqlStatement);
statement.prepare();
statement.execute();
statement.close();
} catch (DatabaseException databaseException) {
throw new DBException(Class.class.getName(), "execute", databaseException.getMessage());
}
}
This is the function in java that i have to implement in android. In android how can i use the createstatement(), statement.prepare() and statement.execute() functions?
You can use "execSQL" if you want to execute any query.
e.g:
SQLiteDatabase db = null;
db.execSQL("INSERT INTO tableName(field1, field2)" + " Values('"
+ value1 + "', '" + value2 + "');");
if you want to fetch data from data base then use Cursor.
e.g:
Cursor c = null;
c = db.rawQuery(QUERY, null);
while (c.moveToNext()) {
String fname = c.getString(c.getColumnIndex("field1"));
String lname = c.getString(c.getColumnIndex("field2"));
}