Android SQL query not ordering data - android

I have written a small android app that grabs some data and displays it in a ListView.
I want to have the list sorted in ascending order (no prob). But when I add a new item it stays at the bottom of the list even when the view/app is reloaded. It seems the only data that is being sorted is the entries that were created in the database OnCreate() method.
I'm not sure what code to provide but i'll start by showing you snippets of the DBAdapter class, then from the main app class.
Database construction query:
private static final String DATABASE_CREATE =
"create table "+ DATABASE_TABLE
+ "("
+ FIELD_ROWID+" integer primary key autoincrement, "
+ FIELD_NAME +" varchar(30) not null, " + FIELD_TELEPHONE + " varchar(20) not null, "
+ FIELD_ADDRESS + " text not null,"
+ FIELD_URL + " varchar(255) not null);";
Function to get list of data:
public Cursor getRestaurants()
{
Cursor result = null;
try{
result = db.query(DATABASE_TABLE, new String[] {FIELD_ROWID, FIELD_NAME}, null, null, null, null, FIELD_NAME+" ASC");
}
catch (Exception e)
{
Log.v("applog", e.getMessage());
}
return result;
}
Here is a snippet of the main method. Here you can see that I am calling the getRestaurants() function shown above. I'm stumped as to why the data isn't being sorted.
Any advice greatly appreciated. Thanks in advance.
public class Assignment2 extends ListActivity {
// Set up some global variables.
private static final int ADD_NEW_ID = Menu.FIRST;
private static final int CLOSE_APP_ID = ADD_NEW_ID+1;
private final DBAdapter db = new DBAdapter(this);
private static CursorAdapter curAdapter = null;
private static Cursor rawData = null;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
db.open(); // Open connection to restaurant db.
rawData = db.getRestaurants();
Log.v("applog", rawData.getCount()+" Restaurants loaded from DB.");
if(rawData.getCount() == 0)
{
Toast.makeText(getApplicationContext(), "No restaurants found.", Toast.LENGTH_SHORT).show();
}
try
{
/* The following two arrays are used to map DB fields to ListView items
* From a custom layout file.
*/
// Array of db fields to be used when converting cursor to ListView
String[] strFields = { "name", BaseColumns._ID };
// Array of listview id's to be used when populating the ListView
int[] intFields = { R.id.first };
curAdapter = new SimpleCursorAdapter(this, R.layout.row, rawData, strFields, intFields);
}
catch (Exception e)
{
Log.v("applog", e.getMessage());
}
// Apply the converter cursor to the current ListView
setListAdapter(curAdapter);
db.close(); // Close connection to restaurant db.

Im not sure exactly what your problem is but, it all looks good minus these lines of code I have when I get a callback from my new data insert
if(cursor!=null)cursor.requery();
adapter.notifyDataSetChanged();
Hopefully this will fix your issue.

Related

Create a android sqlite contain a table with only single row

I want to create a android sqlite table with only one single row, for insert or update and read, how can i do that, cause i only know how to create mulitiple row
the table contain only 1 single row , is for user insert data and store , when read the data will come out , and last the update mean it will override the data which in that row.
this is my DBHelperNote.java
public static final String TABLE_GOAL = "goal";
public static final String GOAL_ID= "goal_id";
public static final String GENDER = "gender";
public static final String AGE = "age";
public static final String HEIGHT = "height";
public static final String WEIGHT = "weight";
public static final String GOAL = "goal";
private static final String CREATE_TABLE_GOAL = "CREATE TABLE " + TABLE_GOAL + " (" +
GOAL_ID + " INTEGER PRIMARY KEY, " +
GENDER + " text not null, " +
AGE + " text not null, "+
HEIGHT + " text not null, "+
WEIGHT + " text not null, "+
GOAL + " text not null "+
" );";
this is SQLControlerWeight.java
public void insertGoal(String gd,String age,String hg,String wg,,String gl) {
ContentValues cv = new ContentValues();
cv.put(DBHelperNote.GENDER, gd);
cv.put(DBHelperNote.AGE, age);
cv.put(DBHelperNote.HEIGHT, hg);
cv.put(DBHelperNote.WEIGHT, wg);
cv.put(DBHelperNote.GOAL, gl);
database.insert(DBHelperNote.TABLE_GOAL, null, cv);
}
public Cursor readGoal() {
String[] allColummn = new String[] {
DBHelperNote.GOAL_ID,
DBHelperNote.GENDER,
DBHelperNote.AGE,
DBHelperNote.HEIGHT,
DBHelperNote.WEIGHT,
DBHelperNote.GOAL,
};
Cursor c = database.query(DBHelperNote.TABLE_GOAL, allColummn, null,
null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
this actually is the method to read data put but it is from array mean multiple row , but i don't Know how to change it to only call one row
dbconnection = new SQLControlerWeight(this);
dbconnection.openDatabase();
Cursor cursor = dbconnection.readGoal();
String[] from = new String[]{
DBHelperNote.GOAL_ID,
DBHelperNote.GENDER,
DBHelperNote.AGE,
DBHelperNote.HEIGHT,
DBHelperNote.WEIGHT,
DBHelperNote.GOAL,
};
int[] to = new int[]{
R.id.goal_id,
R.id.field_gender,
R.id.field_age,
R.id.field_height,
R.id.field_weight,
R.id.field_goal,
};
As you will be having GOAL_ID ones inserted you can modify you insert function as
public void insertGoal(String goal_id, String gd,String age,String hg,String wg,,String gl) {
ContentValues cv = new ContentValues();
if (goal_id != null){
cv.put(DBHelperNote.GOAL_ID, goal_id);
}
cv.put(DBHelperNote.GENDER, gd);
cv.put(DBHelperNote.AGE, age);
cv.put(DBHelperNote.HEIGHT, hg);
cv.put(DBHelperNote.WEIGHT, wg);
cv.put(DBHelperNote.GOAL, gl);
database.replace(DBHelperNote.TABLE_GOAL, null, cv);
}
Modification done is changed insert to replace, which will make sure if primary key value is provided and row exists with that id then it will replace the existing row without creating new one. Most important is the if condition for checking whether goal_id is null or not, if null then don't provide that in contentvalue.
Modify the if condition properly for proper comparison for Goal_id as i have just used the one i can visualize from your question content.
Use RawQuery method its little bit easier.
c1 = db.rawQuery("select * from Table_Name", null);
c1.moveToFirst();
do {
str = c1.getString(c1.getColumnIndex("FieldName"));
ab.add(str);
} while (c1.moveToNext());

Android SQLite: Spinner + select sql methods

I have a Spinner which is showing SQLite data. For that I am using this select method:
public List<String> getAllProductsName(int id)
{
String buildSQL = "SELECT nome FROM " + DatabaseHelper.Produtos.TABELA + " WHERE id =" + id;
List<String> nomes = new ArrayList<String>();
SQLiteDatabase db = this.getDatabase();
Cursor cursor = database.rawQuery(buildSQL, null);
if (cursor.moveToFirst()) {
do {
nomes.add(cursor.getString(0));
} while (cursor.moveToNext());
}
return nomes;
}
The thing is, I am getting only the names but I need the ID as well. I know i could use "SELECT nome, _id FROM ", but how would I return that? Could i possibly return 2 lists (one with IDS and the other one with the Names) in the same method?
Or maybe I should create a new method that show the Names only (when i give the ID as a parameter)? Please help! thanks in advance! :)
How about something like this ... using and returning HashMap that contains ID as keys and nome as values
public HashMap<Integer,String> getAllProductsName(int id)
{
String buildSQL = "SELECT nome,_id FROM " + DatabaseHelper.Produtos.TABELA + " WHERE id =" + id;
HashMap<Integer,String> idAndNomes = new HashMap<Integer,String>();
SQLiteDatabase db = this.getDatabase();
Cursor cursor = database.rawQuery(buildSQL, null);
if (cursor.moveToFirst()) {
do {
idAndNomes.put(cursor.getInt(1), cursor.getString(0)));
} while (cursor.moveToNext());
}
return idAndNomes;
}
Then you can use:
idAndNomes.keySet() - Returns a set of the keys contained in this map. In our case ID.
idAndNomes.values() - Returns a collection of the values contained in this map. In our case nomes.

How to avoid duplicate contact name (data ) while loading contact info to listview?

I am populating contact list details to list view successfully.
My code:
String order = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC";
Cursor curLog = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null,order);
How can I avoid the duplicate data In List view as the contact details is repeating if its joined contact i.e. joined with both phone and Google?. The screen is like
I want to select programmatically only 1 name not the both? Any Idea how I can select?
I have used a rough way to avoid this problem which helped me so much and working nicely.
i.e
Use local database (SQLite) to avoid duplicate data by make phone number to unique.
I have made one SQLite DB to handle this problem:
ContactMerger.java:
public class ContactMerger {
private static final String CONTACT_TABLE = "_contact_table";
private static final String CONTACT_ID = "_contactId";
private static final String CONTACT_NAME = "_contactName";
private static final String CONTACT_MOBILE_NUMBER = "_contactNumber";
private static final String CONTACT_DATE = "_contactDate";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "DB_Contact";
private final Context context;
private SQLiteDatabase ourDatabase;
private DbHelper ourHelper;
private class DbHelper extends SQLiteOpenHelper {
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String contactQuery = "CREATE TABLE " + CONTACT_TABLE + " ("
+ CONTACT_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ CONTACT_NAME + " TEXT NOT NULL, " + CONTACT_DATE
+ " TEXT NOT NULL, " + CONTACT_MOBILE_NUMBER
+ " TEXT NOT NULL UNIQUE);";
db.execSQL(contactQuery);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + CONTACT_TABLE);
onCreate(db);
}
}
public ContactMerger(Context context) {
this.context = context;
}
public ContactMerger open() throws SQLException {
ourHelper = new DbHelper(context);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close() {
ourHelper.close();
}
// Insert Data to Contact Table
public long insertContacts(String name, String number, String date) throws SQLException {
ContentValues cv = new ContentValues();
cv.put(CONTACT_NAME, name);
cv.put(CONTACT_DATE, date);
cv.put(CONTACT_MOBILE_NUMBER, number);
Log.d("Insert Data", cv.toString());
return ourDatabase.insert(CONTACT_TABLE, null, cv);
}
//Get Contact details from Contact Table
public ArrayList<ContactHolder> getContactDetails() throws Exception{
ArrayList<ContactHolder> contactDetails = new ArrayList<ContactHolder>();
String[] columns = new String[] { CONTACT_ID, CONTACT_NAME, CONTACT_DATE, CONTACT_MOBILE_NUMBER };
Cursor c = ourDatabase.query(CONTACT_TABLE, columns, null, null, null,null, null);
int iContactName = c.getColumnIndex(CONTACT_NAME);
int iContactDate = c.getColumnIndex(CONTACT_DATE);
int iContactMobileNumber = c.getColumnIndex(CONTACT_MOBILE_NUMBER);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
ContactHolder data = new ContactHolder();
data.setName(c.getString(iContactName));
data.setDate(c.getString(iContactDate));
data.setNumber(c.getString(iContactMobileNumber));
contactDetails.add(data);
}
return contactDetails;
}
}
Here ContactHolder is just a getter/setter class to handle contact entities.
First I inserted all Contact information once in my MainActivity by the help of a background thread. It prevents to insert the contact info multiple times.
Something like:
private ArrayList<ContactHolder> contactHolder;
private void setCallLogs(Cursor managedCursor) {
contactHolder = new ArrayList<ContactHolder>();
int _number = managedCursor
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
int _name = managedCursor
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
int _id = managedCursor
.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID);
while (managedCursor.moveToNext()) {
ContactHolder holder = new ContactHolder();
holder.setNumber(managedCursor.getString(_number));
holder.setName(managedCursor.getString(_name));
holder.setDate(managedCursor.getString(_id));
contactHolder.add(holder);
}
Thread t = new Thread(new Runnable() {
#Override
public void run() {
for(int i=0; i<contactHolder.size(); i++){
try{
ContactMerger merger = new ContactMerger(HomeActivity.this);
merger.open();
merger.insertContacts(contactHolder.get(i).getName(),
contactHolder.get(i).getNumber(),
contactHolder.get(i).getdate());
merger.close();
} catch(Exception e){
e.printStackTrace();
}
}
}
});
t.start();
}
At last I gtt all contact information inside an Asynctask(doInbackground()) and put in adapter/listview in its onPostExecute() method in the class I want to show.
Here:
#Override
protected ArrayList<ContactHolder> doInBackground(String... parameters) {
ArrayList<ContactHolder> filterContacts = new ArrayList<ContactHolder>();
ContactMerger merger = new ContactMerger(Aaja_Contact.this);
merger.open();
try {
filterContacts = merger.getContactDetails();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
merger.close();
return filterContacts;
}
I believe this may happen if the contact number is stored in two different ways/formats: for example in your case the number for Akshay may be saved as 982-0123456 and 9820123456
Did you try displaying the number along with the Name by including the Number as well in the list view?
You need to retrieve the data from the Cursor to HashSet (which don't allows duplicate itmes) and then pass the HashSet object to your ListView's Adapter
This is a dump solution but it will help you:
ListView listView;
Set<String> listItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
listItems = new HashSet<String>();
String order = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC";
Cursor curLog = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null,order);
if(curLog != null) {
while(curLog.moveToNext()) {
String str = curLog.getString(curLog.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY));
listItems.add(str);
}
}
String listString = listItems.toString();
listString = listString.substring(1,listString.length()-1);
String[] newList = listString.split(", ");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, newList);
listView.setAdapter(adapter);
}
Good luck..
Since you're querying Phone.CONTENT_URI, I'm assuming you're looking for contacts with phone number.. then you can use ContactsContract.Contacts.CONTENT_URI
String order = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC";
Cursor curLog = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null,
ContactsContract.Contacts.HAS_PHONE_NUMBER + "=?", new String[] { "1" }, order);
Its because the listview is showing both normal contacts as well as whatsapp( or like this) linked contacts. Best is to store all the contacts in a Database and then retrieve the contacts using "select distinct..." command of SQL.
String order = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC";
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, order);
String temp_name="";
while (phones.moveToNext())
{
String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
if (name.equals(temp_name))
continue;
temp_name=name;
//add name to your list or adapter here`enter code here`
}
phones.close();
When you loop through your contacts, here's something you can do in the looping statement while you add your next object to avoid creating a duplicate contact:
UserList object=new UserList(name,number);
if(arrayList.size()==0)
{
arrayList.add(object);
}
if(arrayList.size()>0) {
position = arrayList.size();
if (!(arrayList.get(arrayList.position - 1).getName().equals(number) ||
arrayList.get(position - 1).getNumber().equals(number)))
{
arrayList.add(object); }
}
Here, in my object of 'UserList' class, the name and number would repeat from the contact list, so this code just checks if the previous object has the same name or number before adding in the new one.
Old question but still relevant. I could not find suitable query to skip dupes with contentresolver but it's possible to compare all contacts for duplicates by phone number.
With com.googlecode.libphonenumber library it's really simple. Method public MatchType isNumberMatch(CharSequence firstNumber, CharSequence secondNumber) compares number, coutry code, mask and return one of MatchType enum value.

removing, restoring items in ListView and database

I have a ListView with items that are added dynamically. When an item is added, it is added to the ListView and also inserted into a SQLite Database so that the items in the list can be saved. I can also remove specific items by getting the postion if the item and then removing it with that information.
This is how I add items (I use multiple classes):
In DataModel.class:
public void addItem(Object data) {
String string = String.valueOf(data);
mPlanetsList.add(createPlanet("planet", string));
History history = new History();
history.getDataHashMap().put("planet", data);
history.addToHistoryDB();
mHistoryList.add(history);
if (null != mOnItemAddHandler) {
mOnItemAddHandler.onItemAdded(data);
}
}
In History.class:
public void addToHistoryDB() {
MySQLiteOpenHelper mDbHelper = MySQLiteOpenHelper.getInstance();
SQLiteDatabase db = mDbHelper.getWritableDatabase();
ContentValues values = getContentValues();
rawId = (int) db.insert(TABLE_NAME, COL_ID, values);
db.close();
}
This is how I remove items:
In DataModel.class:
public void removeItem(int index) {
if (mPlanetsList == null || index < 0 || index >= mPlanetsList.size()) {
return;
}
// remove from mPlanetList
mPlanetsList.remove(index);
History history = mHistoryList.get(index);
mHistoryList.remove(index);
if (null != history) {
history.remove();
history = null;
}
// notify, the HistoryFragment will update view
if (null != mOnItemAddHandler) {
mOnItemAddHandler.onItemRemove(index);
}
In History.class:
public void remove() {
MySQLiteOpenHelper mDbHelper = MySQLiteOpenHelper.getInstance();
SQLiteDatabase db = mDbHelper.getWritableDatabase();
int r = db.delete(TABLE_NAME, "_id = ?", // delete the int r ??
new String[] { String.valueOf(rawId) });
db.close();
}
When the app in removed from the 'recent apps' or is restarted, initList() is called which restored the ListView items from the Database.
This is the code:
DataModel:
private void initList() {
mHistoryList = History.getList();
for (int i = 0; i < mHistoryList.size(); i++) {
Object obj = mHistoryList.get(i).getDataHashMap().get("planet");
mPlanetsList.add(createPlanet("planet", String.valueOf(obj)));
}
}
History:
public static ArrayList<History> getList() {
Cursor cursor = null;
try {
MySQLiteOpenHelper mDbHelper = MySQLiteOpenHelper.getInstance();
SQLiteDatabase db = mDbHelper.getWritableDatabase();
String sql = "select * from " + History.TABLE_NAME;
ArrayList<History> list = new ArrayList<History>();
cursor = db.rawQuery(sql, null);
if (cursor != null) {
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor
.moveToNext()) {
History item = new History();
item.fromCuror(cursor);
list.add(item);
}
}
return list;
} finally {
if (null != cursor && Integer.parseInt(Build.VERSION.SDK) < 14) {
cursor.close();
}
}
}
This method works fine as long as the order of the list is not changed - I can add items and removes items and it all works perfectly. However, I would like items to be added to the top of the list rather than the bottom.
So I read around on how to add items to the top of a ListView and found that by adding a 0 as the position when adding the item, the new items go to the top of the list.
mPlanetsList.add(0, createPlanet("planet", string)); // I put the 0 in wherever the item is added eg when adding from the database
When I do this, however, the items viewed/deleted in the ListView do not continue to correspond with the data in the Database. For example, Lets say I add three items to the List: dog then cat then horse. The ListView shows them in the correct order (horse at the top). If I then delete an item, lets say: cat , the ListView updates and everyting is good. But if I then restart the app, initList() is called. This is where the problem occurs - It is not cat that is removed from the list, it is horse or dog.
Possible points where I think the problem could be:
a) in the initList() - It is not adding the correct items
b) in the removeItem() - It is not removing the correct items from the Database.
c) in the getList() - maybe something with the cursor???
This think b) is more likely but I don't know where the problem is exactly or what to change it too.
EDIT:
After a little testing, I found that I was right that b) is where it goes wrong.
The steps to reproduce:
Create three items: cat then dog then horse. The ListView shows them in the correct order ie horse at the top, cat at the bottom. The Database shows them with cat at the top, horse at the bottom.
When I delete horse (top of ListView, bottom of Database) the ListView updates correctly, but in the Database it is not horse that has been deleted but in fact cat.
So because of the wrong removal, when the Database is used to restore the ListView, the ListView appears wrong.
I hope this makes things clearer!
EDIT 2: This is how I create my table:
public static final String TABLE_NAME = "history_table";
public static final String COL_TITLE = "title";
public static final String COL_CONTENT = "content";
public static final String COL_DATE = "date";
public static final String COL_TYPE = "type";
public static final String COL_ONGOING = "ongoing";
public static final String COL_DATA = "data";
public static final String COL_ID = "_id";
public static final String DATABASE_CREATE = "create table " + TABLE_NAME
+ "(" + COL_ID + " integer primary key autoincrement, " + COL_TITLE
+ " text not null, " + COL_CONTENT + " text not null, " + COL_DATE
+ " text not null, " + COL_TYPE + " text not null, " + COL_ONGOING
+ " text not null, " + COL_DATA + " text not null );";
This is getContentValues():
public ContentValues getContentValues() {
ContentValues values = new ContentValues();
values.put(History.COL_TITLE, "MyTitle");
values.put(History.COL_CONTENT, "MyContent");
values.put(History.COL_DATE, "Date placeholder");
values.put(History.COL_TYPE, "QuickNote");
values.put(History.COL_ONGOING, "Ongoing placeholder");
values.put(History.COL_DATA, new JSONObject(mDataHashMap).toString());
return values;
}
EDIT 3:
I have basically narrowed it down to the fact that because the order of items in the ListView and in the Database are different, deleting items by their postition in the list does not work. So would a possible solution would be to invert the order of items in the database to match the ListView (good idea / possible ?).
EDIT 3.1:
https://stackoverflow.com/a/7348117/2442638
This order by descending may help. I don't know where I should put it though
EDIT 3.5:
I now have the ordering working. The deleting very nearly works, but there is now a problem that the first deletion doesn't work. The rest work after that. I am sorting by the _id and as that is autoincrement maybe it starts at 1 or 0 and the list starts at the other. I will do more research
There are two list in the app: mHistoryList and mPlanetsList, You should keep the order of the data itmes in them are the same.
You can add items to the top of listview by calling the method addItem in DataModel:
public void addItem(Object data) {
History history = new History();
history.getDataHashMap().put("planet", data);
history.addToHistoryDB();
mHistoryList.add(0, history);
mPlanetsList.add(0, history.createPlanet());
if (null != mOnItemAddHandler) {
mOnItemAddHandler.onItemAdded(data);
}
}
Then the new data will be at the top of the listview.
After app restart, the code below will be called:
private void initList() {
mHistoryList = History.getList();
for (int i = 0; i < mHistoryList.size(); i++) {
mPlanetsList.add(mHistoryList.get(i).createPlanet());
}
}
We should make sure the data from History.getList(); has the same order, in another word, the new data time in the head of the list.
So we should change the code to (order by _id desc):
public static ArrayList<History> getList() {
Cursor cursor = null;
try {
MySQLiteOpenHelper mDbHelper = MySQLiteOpenHelper.getInstance();
SQLiteDatabase db = mDbHelper.getWritableDatabase();
// order by _id desc
String sql = "select * from " + History.TABLE_NAME + " order by _id desc";
ArrayList<History> list = new ArrayList<History>();
cursor = db.rawQuery(sql, null);
if (cursor != null) {
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
History item = new History();
item.fromCuror(cursor);
list.add(item);
}
}
return list;
} finally {
if (null != cursor && Integer.parseInt(Build.VERSION.SDK) < 14) {
cursor.close();
}
}
}

sqlite search query for finding a particular data from column?

I am making app for finding number plates of india.
my database contains two columnns "code" and "city" code contains data like MH1,MH2 etc.
and city contains data like Pune,Mumbai.
App contains one edittext box and listview.
Listview consists whole data from database like GJ3 Rajkot, GJ10 Jamnagar etc.
if i write GJ in edittext box whole only data of GJ must be apperaed in listview.
Here is the query :
SELECT *
FROM table_name
WHERE code LIKE '%GJ%'
LIMIT 0 , 30
Try this :
Cursor c = mDb.rawQuery(
"select * from table_name where column_name = ?",
new String[] { "search" });
EDIT :
Follow the tutorial of the given above link and add below method into TestAdapter
public Cursor get_tag_Data()
{
try
{
String sql ="select * from table_name where column_name = ?", new String[] { edittext.getText().toString().trim()}";
Cursor mCur = mDb.rawQuery(sql, null);
if (mCur!=null)
{
mCur.moveToNext();
}
return mCur;
}
catch (SQLException mSQLException)
{
Log.e(TAG, "getTestData >>"+ mSQLException.toString());
throw mSQLException;
}
}
and call this method from your class like:
TestAdapter mDbHelper = new TestAdapter(urContext);
mDbHelper.createDatabase();
mDbHelper.open();
Cursor testdata = mDbHelper.get_tag_Data();
mDbHelper.close();
EDIT:
Declare below method into your database class,
public List<String> getQuestions(String difficulty) {
public static List<String> question_Set;
question_Set = new ArrayList<String>();
Cursor c = mDb.rawQuery(
"select * from table_name where column_name = ?", new String[] { difficulty });
while (c.moveToNext()) {
question_Set.add(c.getString(1).trim());
}
return question_Set;
}
Now call like
DB.getQuestions(edittext.getText().toString().trim()); // DB is your database class name

Categories

Resources