Error querying sqlite database in android studio - java

I have a problem in my application, to see if there is someone who can help me.
It turns out that in my application I have made a database with SQLite that has two tables, one for players and one for results.
#Override
public void onCreate(SQLiteDatabase BaseDeDades) {
BaseDeDades.execSQL("create table jugadors(codi int primary key, nom text, cognoms text, data date, club text, categoria text)");
BaseDeDades.execSQL("create table resultats(codipuntuacio int primary key, codijugador int,codiexercici text, puntuacio text, temps long, data date)");
}
To consult the first of the tables (players) that shows a list of all the players entered in the database, I did it as follows.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_llistajug);
Llistajugadors();
}
public void Llistajugadors(){
AdminSQLiteOpenHelper admin = new AdminSQLiteOpenHelper(this,"administracio",null,1);
SQLiteDatabase BaseDeDades = admin.getWritableDatabase();
if(BaseDeDades!=null){
Cursor c= BaseDeDades.rawQuery("select * from jugadors",null);
int quantitat = c.getCount();
int i=0;
String[] array = new String[quantitat];
if (c.moveToFirst()){
do{
String linia = c.getInt(0)+"-"+c.getString(1);
array[i] = linia;
i++;
}while(c.moveToNext());
}
ArrayAdapter<String>adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,array);
final ListView llista = (ListView)findViewById(R.id.llista);
llista.setAdapter(adapter);
llista.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = getIntent();
intent.putExtra("dato2", llista.getItemAtPosition(position).toString());
setResult(RESULT_OK,intent);
finish();
}
});
}
}
}
The problem has arisen when trying to consult the data of the other table (results) since I have tried to do it the same way
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_llistajug);
jugador = getIntent().getStringExtra("name");
exercici = getIntent().getStringExtra("exercise");
nom = jugador.split("-")[1];
codi = Integer.parseInt(jugador.split("-")[0]);
Resultats();
}
public void Resultats() {
AdminSQLiteOpenHelper admin = new AdminSQLiteOpenHelper(this, "administracio", null, 1);
SQLiteDatabase BaseDeDades = admin.getWritableDatabase();
if (BaseDeDades != null) {
Cursor c2 = BaseDeDades.rawQuery("select * from resultats",null);
int quantitat2 = c2.getCount();
int i2 = 0;
String[] array2 = new String[quantitat2];
if (c2.moveToFirst()) {
do {
String linia2 = c2.getInt(0) + "-" + c2.getString(1);
array2[i2] = linia2;
i2++;
} while (c2.moveToNext());
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, array2);
final ListView llista2 = (ListView) findViewById(R.id.llista2);
llista2.setAdapter(adapter);
}
}
}
But when executing this activity, in this case the application stops.
Does anyone know why if I have done it the same way? Thank you
This is the error that appears in Logcat when executing the activity:
Logcat error
Thanks, the bug was fixed. But now I have another problem with the query. How can I make the query for a string?
codijugador i codi are integers and it works correctly but adding another parameter codiexercici = exerici which are strings gives me an error, are they not done the same way?
Thanks, the bug was fixed. But now I have another problem with the query. How can I make the query for a string?
Thanks, the bug was fixed. But now I have another problem with the query. How can I make the query for a string?
co-player i codi are integers and it works correctly but adding another parameter codiexercici = exerici which are strings gives me an error, are they not done the same way?
Cursor c = BaseDeDades.rawQuery("select * from resultats where codijugador = "+codi+" and codiexercici="+exercici, null);

String must be enclosed inside single quotes, but this is something that you should not do by concatenating the parameters and the single quotes.
Use ? placeholders for the parameters and the 2nd argument of rawQuery() to pass them:
Cursor c = BaseDeDades.rawQuery(
"select * from resultats where codijugador = ? and codiexercici = ?",
new String[] {String.valueOf(codi), exercici}
);

Related

Nullpointer Exception after deleting entry from SQL database

I'm working on an app for a robot where the user can define punch combinations which the robot will later fetch from the device. To allow the user to store these trainings I have defined a class "Trainings" which holds the id, the name and the punch combination of the training. This training is later saved in a database, for which I have written a DatabaseHandler class. Adding and displaying the data works fine, but whenever I want to delete an entry with the method below:
public void deleteTraining(Training training) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_TRAININGS, KEY_ID + " = ?",
new String[] { String.valueOf(training.getID()) });
db.close();
}
and later try to populate my GridView again ( handled by a GridAdapter class), I get a Nullpointer Exception
java.lang.NullPointerException: Attempt to read from field 'java.lang.String com.noeth.tobi.mcrobektrainingsplaner.Training._name' on a null object reference
at com.noeth.tobi.mcrobektrainingsplaner.GridAdapter.getView(GridAdapter.java:50)
the getView method of the GridAdapter:
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
// if it's not recycled, initialize some attributes
btn = new Button(context);
btn.setLayoutParams(new GridView.LayoutParams(370, 350));
btn.setPadding(2,100,2,100);
btn.setOnClickListener(new CustomOnClickListener(position, context));
btn.setOnLongClickListener(new CustomOnLongClickListener(position, context, btn));
}
else {
btn = (Button) convertView;
}
btn.setText(db.getTraining(position)._name); //Here the programm throws a Nullpointer Exception AFTER deleting an entry from the database
btn.setTextColor(Color.WHITE);
btn.setBackgroundResource(R.drawable.button_border);
btn.setTag("not_activated");
btn.setId(position);
return btn;
}
I figured that it must have something to do with the id of the deleted training, as the loop simply goes through all ids so I wrote a method recalcIDs which recalculates the id of every item coming after the deleted training:
recalcIDs
public void recalcIDs(){
int k = 1;
int subtract = 1;
int id;
Training training;
for(int i = deleted.get(0)+1; i < db.getTrainingCount(); i++){
if(deleted.size() > 1){
if(i < deleted.get(k)){
training = db.getTraining(i);
id = training.getID();
training.setID(id-subtract);
}
else{
k+=1;
subtract+=1;
}
}
else{
training = db.getTraining(i);
id = training.getID();
training.setID(id-subtract);
}
}
}
However this does not fix it.
When reinstalling the app and starting with a completely new database everythings works again.
Does anybody have an idea what I've done wrong?
P.S.: Here's the getTraining method where it can't find the name:
Training getTraining(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Training training;
Cursor cursor = db.query(TABLE_TRAININGS, new String[] { KEY_ID,
KEY_NAME, KEY_SK}, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null && cursor.moveToFirst()){
training = new Training(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getLong(2));
cursor.close();
}
else{
training = null;
Toast.makeText(con,"Couldn't find any training sessions!", Toast.LENGTH_LONG).show();
}
// return training
return training;
}
I'm assuming your the Training.setId method doesn't call the database.
You shouldn't change the id of your training because they get managed by the underlaying database. If you only change the ids in you application logic both datasets (application and database) will differ.
I would recommend to reload all the trainings from the database after a user decided to delete one and call the Gridview.notifyDatasetChanged afterwards.

RecyclierView's notifyItemInserted does not work with arrayList

I have 1 ArrayList and 1 RecyclerView. Data from DB are retrieved and stored in the ArrayList for displaying in the RecyclerView. All the things work fine with adding new item to the RecyclerView, but without the adding animation. I know I should use notifyItemInserted for the adding animation, but it didn't work. No inserting animation was appearing. Now I have to go back to the previous page and then get in the page again so that the added item was showing. So, how to add back the inserting animation?
Any help will be very much appreciated. Thanks.
Code to pass the data and set the adapter:
db = new DatabaseHelper(this);
dbList = new ArrayList<>();
dbList = db.getFilteredItems();
RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mRecyclerView.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(this);
llm.setOrientation(LinearLayoutManager.VERTICAL);
//newest to oldest order (database stores from oldest to newest)
llm.setReverseLayout(true);
llm.setStackFromEnd(true);
mRecyclerView.setLayoutManager(llm);
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
adapter = new RecyclerAdapter(this, llm, dbList);
mRecyclerView.setAdapter(adapter);
Code to retrieve data from DB:
//retrieve filtered data from DB
public List<AudioItem> getFilteredItems(){
List<AudioItem> audioList = new ArrayList<>();
String titleName = EditActivity.titleName;
String query = "select * from " + TABLE_NAME + " where " + COLUMN_NAME_RECORDING_NAME + " like '" + titleName + "%'";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query,null);
if (cursor.moveToFirst()){
do {
AudioItem audio = new AudioItem();
audio.setId(Integer.parseInt(cursor.getString(0)));
audio.setName(cursor.getString(1));
audio.setFilePath(cursor.getString(2));
audio.setLength(Integer.parseInt(cursor.getString(3)));
audio.setTime(Long.parseLong(cursor.getString(4)));
audioList.add(audio);
}while (cursor.moveToNext());
cursor.close();
}
return audioList;
}
Code to insert data into the DB:
/* Insert data into database */
public void addRecording(String recordingName, String filePath, long length) {
SQLiteDatabase db = getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_NAME_RECORDING_NAME, recordingName);
cv.put(COLUMN_NAME_RECORDING_FILE_PATH, filePath);
cv.put(COLUMN_NAME_RECORDING_LENGTH, length);
cv.put(COLUMN_NAME_TIME_ADDED, System.currentTimeMillis());
db.insert(TABLE_NAME, null, cv);
db.close();
if (mOnDatabaseChangedListener != null) {
mOnDatabaseChangedListener.onNewDatabaseEntryAdded();
}
}
Code to invoke the inserting animation:
#Override
public void onNewDatabaseEntryAdded() {
//item added to top of the list
Log.e("Count: ", Integer.toString(getItemCount()));
// notifyDataSetChanged();
notifyItemInserted(getItemCount());
//llm.scrollToPosition(getItemCount() - 1);
}
If you make a new ArrayList every time something changes and assign it to a new adapter and assign that new adapter to the RecyclerView, wonky things happen.
You should break the ArrayLists out into a Model type of object or integrate them into your current DB model object. If you do this, you can simply update itemlist and the changes will be reflected in your RecyclerView.
Here's some pseudo code since I don't really have much of your code to work off of:
public class DataModel {
private ArrayList<Foo> itemlist = new ArrayList<>();
public DataModel(){}
public ArrayList<Foo> getItemList() { return itemlist; }
}
public class YourActivity extends Activity {
private DataModel data = new DataModel();
#Override
protected void onCreate(Bundle b) {
if (b == null) {
RecyclerView dataView = (RecyclerView) findViewById(R.id.recyclerView);
dataView.setAdapter(new RecyclerAdapter(this, new LinearLayoutManager(this), data.getItemList()));
}
}
}
After you set things up this way, whenever you update itemlist, you should be seeing the changes automatically reflected. If not, call notifyDataSetChanged().

Slow Performance while listing SMS with the senders in android

I am using the bellow code to list a unique list of people that sent me SMS. It works fine but still its a bit slow it takes 4 to 5 seconds to load and I have 650 SMS on my device any suggestion ?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listSMS();
}
private void listSMS()
{
TextView tview = (TextView) findViewById(R.id.list);
Uri uriSMSURI = Uri.parse("content://sms/inbox");
ContentResolver cr= this.getContentResolver();
Cursor cur = cr.query(uriSMSURI, null, null, null, null);
LinkedHashSet contactList= new LinkedHashSet();
String sms = "";
while (cur.moveToNext()) {
if(!contactList.contains(cur.getString(2)))
{
contactList.add(cur.getString(2));
sms += "From :" + getContactName(cur.getString(2),cr)+"\n";
}
}
cur.close();
tview.append(sms);
}
public static String getContactName(String num, ContentResolver cr) {
Uri u = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,Uri.encode(num));
String[] projection = new String[] { ContactsContract.Contacts.DISPLAY_NAME};
Cursor c = cr.query(u, projection, null, null, null);
try {
if (!c.moveToFirst())
return num;
int index = c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
return c.getString(index);
} finally {
if (c != null)
c.close();
}
}
Instead of preparing the list of contacts with their names up front and then passing it to the adapter, try preparing the list with ids only and then fetch the corresponding names inside the adapter. This will solve the delay to start but will make scrolling of the ListView a bit slower which can be solved by using a View Holder or some caching mechanism to prevent fetching the same name more than once. Also note that the adapter will query for names of contacts that are currently visible to the user only.

Android changing XML layout Changes data fields

Here's a head scratcher...(at least for me)
I have a contact list that displays a list of contacts from my Db. When a user clicks on one of the contacts an edit activity comes up. It all works perfectly as laid out currently, but I need to have the edit activity display the last name entry before the first name. Thinking that all the fields should have a one to one relationship, I went ahead and moved the editText(XML) for the last name above the first name in the edit activity thinking that this should be referenced by the id of the EditText. After doing so, the program is now displaying the first name in the last name field and vise-versa. I have tried wiping the user data on the emulator with no difference. I already realize this is probably one of those UH-DUH! type questions, but if anyone can point out the obvious for me, it would be appreciated. All the code shown is in the now-working state:
I've removed some chunks that would have nothing to do with my issue.
Thanks to anyone having a look at this for me!
Ken
XML:
<EditText
android:id="#+id/contact_edit_first_name"
android:inputType="textPersonName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="#string/contact_edit_first_name"
android:imeOptions="actionNext"
android:background="#color/warn" >
</EditText>
<EditText
android:id="#+id/contact_edit_last_name"
android:inputType="textPersonName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="top"
android:hint="#string/contact_edit_last_name"
android:imeOptions="actionNext"
android:background="#color/warn" >
</EditText>
This is the contact activity that displays the listView rows, and calls
createContact which sends an intent to add, edit or delete rows.
public class ContactsActivity extends ListActivity implements
LoaderManager.LoaderCallbacks<Cursor> {
private SimpleCursorAdapter adapter;
/** Called when the activity is first created. */
#Override
public void onCreate //DO THE ON CREATE STUFF -removed
fillData();
registerForContextMenu(getListView());
Button add_contact = (Button) findViewById(R.id.add_contact_button);
add_contact.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
createContact();
}
});
}
// Create the options menu to INSERT from the XML file
// removed - not relevant
// return true for the menu to be displayed
}
// When the insert menu item is selected, call CreateContact
//Removed
createContact();
return true;
}
return super.onOptionsItemSelected(item);
}
private void createContact() {
Intent i = new Intent(this, ContactEditActivity.class);
startActivity(i);
}
//The onListItemClick sends a URI which flags the contactEditActivity
//that this is an edit rather than a new insert.
#Override
protected void onResume() {
super.onResume();
//Starts a new or restarts an existing Loader in this manager
getLoaderManager().restartLoader(0, null, this);
}
//The fillData method binds the simpleCursorAadapter to the listView.
private void fillData() {
//The desired columns to be bound:
String[] from = new String[] { ContactsDB.COLUMN_LAST_NAME, ContactsDB.COLUMN_FIRST_NAME };
//The XML views that the data will be bound to:
int[] to = new int[] {R.id.label2, R.id.label};
// The creation of a loader using the initLoader method call.
getLoaderManager().initLoader(0, null, this);
adapter = new SimpleCursorAdapter(this, R.layout.contact_row, null, from,
to, 0);
setListAdapter(adapter);
}
// Sort the names by last name, then by first name
String orderBy = ContactsDB.COLUMN_LAST_NAME + " COLLATE NOCASE ASC"
+ "," + ContactsDB.COLUMN_FIRST_NAME + " COLLATE NOCASE ASC" ;
// Creates a new loader after the initLoader () call
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
//ETC
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
adapter.swapCursor(data); //Call requires Min API 11
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
// swap the cursor adapter
}
And Finally, this is the contact edit code that is likely the source of my grief...maybe not. Could be the save state doesn't map to the id's?
#Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.activity_contact_edit);
Log.i(TAG, "INSIDE ONCREATE");
mCategory = (Spinner) findViewById(R.id.category);
mLastName = (EditText) findViewById(R.id.contact_edit_last_name);
mFirstName = (EditText) findViewById(R.id.contact_edit_first_name);
mHomePhone = (EditText) findViewById(R.id.contact_edit_home_phone);
mCellPhone = (EditText) findViewById(R.id.contact_edit_cell_phone);
//****************ECT. ETC.
//DECLARE THE BUTTONS AND SET THE DELETE ENABLED FALSE - REMOVED - NOT PERTINANT
Bundle extras = getIntent().getExtras();
// Check if the URI is from a new instance or a saved record
}
// Set the save button to check the required fields, save the contact and finish
saveButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (TextUtils.isEmpty(mLastName.getText().toString()) ||
TextUtils.isEmpty(mFirstName.getText().toString())) {
makeToast();
} else {
setResult(RESULT_OK);
finish();
}
}
});
// Set the delete button to delete the contact and finish - REMOVED - NOT PERTINANT
private void fillData(Uri uri) {
// QUERY PARAMETER projection - A list of which columns to return.
// Passing null will return all columns, which is inefficient (but used now!)
// null, null and null are: selection, selection args, and sort order for specific items
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
String category = cursor.getString(cursor
.getColumnIndexOrThrow(ContactsDB.COLUMN_CATEGORY));
for (int i = 0; i < mCategory.getCount(); i++) {
String s = (String) mCategory.getItemAtPosition(i);
Log.i("CATEGORY", s); ////////////////////////////////////////////
if (s.equalsIgnoreCase(category)) {
mCategory.setSelection(i);
}
};
mLastName.setText(cursor.getString(cursor
.getColumnIndexOrThrow(ContactsDB.COLUMN_LAST_NAME)));
mFirstName.setText(cursor.getString(cursor
.getColumnIndexOrThrow(ContactsDB.COLUMN_FIRST_NAME)));
mHomePhone.setText(cursor.getString(cursor
.getColumnIndexOrThrow(ContactsDB.COLUMN_PHONE_NUMBER)));
mCellPhone.setText(cursor.getString(cursor
.getColumnIndexOrThrow(ContactsDB.COLUMN_CELL_NUMBER)));
mWorkPhone.setText(cursor.getString(cursor
.getColumnIndexOrThrow(ContactsDB.COLUMN_WORK_NUMBER)));
mFax.setText(cursor.getString(cursor
//****************ECT. ETC.
//close the cursor
}
}
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
saveState();
outState.putParcelable(whateverContentProvider.CONTENT_ITEM_TYPE, contactUri);
}
#Override
protected void onPause() {
super.onPause();
saveState();
}
private void saveState() {
String category = (String) mCategory.getSelectedItem();
String someLAST = mLastName.getText().toString().valueOf(findViewById(R.id.contact_edit_last_name));
String lastName = mLastName.getText().toString();
String firstName = mFirstName.getText().toString();
String someFIRST = mFirstName.getText().toString().valueOf(findViewById(R.id.contact_edit_first_name));
String homePhone = mHomePhone.getText().toString();
String somePhone = mHomePhone.getText().toString().valueOf(findViewById(R.id.contact_edit_home_phone));
String cellPhone = mCellPhone.getText().toString();
String workPhone = mWorkPhone.getText().toString();
//****************ECT. ETC.
//Some logging I used to show that the first name field still came up first
//after changing the order of the editTexts.
Log.i("LAST NAME", lastName);
Log.i("SOME LAST", someLAST);
Log.i("FIRST NAME", firstName);
Log.i("SOME FIRST", someFIRST);
Log.i("Home Phone", homePhone);
Log.i("SOME PHONE", somePhone);
// Save if first name and last name are entered
// The program will save only last name when a user presses back button with text in last name
if (lastName.length() == 0 || firstName.length() == 0) {
return;
}
// ContentValues class is used to store a set of values that the contentResolver can process.
ContentValues values = new ContentValues();
values.put(ContactsDB.COLUMN_CATEGORY, category);
values.put(ContactsDB.COLUMN_LAST_NAME, lastName);//ANNIE
values.put(ContactsDB.COLUMN_FIRST_NAME, firstName);
values.put(ContactsDB.COLUMN_PHONE_NUMBER, homePhone);
//****************ECT. ETC.
if (contactUri == null) {
// Create a new contact
contactUri = getContentResolver().insert(whateverContentProvider.CONTENT_URI, values);
} else {
// Update an existing contact
getContentResolver().update(contactUri, values, null, null);
}
}
//MAKE A TOAST DOWN HERE - REMOVED - NOT PERTINANT
}
Have you tried cleaning the project (regenerating de R).
Also, try restarting your IDE.
This may seem stupid but actually can solve the issue...
try cleaning your project. Weird things happen sometimes within Eclipse.

How do I implement autocomplete with cursoradapter

I have an SQLite database containing 2 tables 4000+ rows each used for autocomplete. I saw very simple examples that use an array of strings to provide autocomplete or they use the list of contacts to do the same. Obviously none of these work in my case. How do I use my own SQLite database with my own autocomplete data, for the autocomplete. Do I have to create content providers? How? Please give me some examples because I couldn't find any. I have managed to override SQLiteOpenHelper to copy the database from the assets folder to the /data/data/MY_PACKAGE/databases/ folder on the android. I have created a custom CursorAdapter that uses my custom SQLiteOpenHelper and returns a cursor from runQueryOnBackgroundThread. I get strange errors about some _id column missing. I have added the _id column to my tables. I also don't understand what is the Filterable interface doing and when does my data get filtered. What methods/classes do I need to override? Thanks.
It works.
You need the SQLiteOpenHelper from here. You basically have to copy your database into a specific folder from your assets folder. Then you need a custom CursorAdapter that uses your custom SQLiteOpenHelper.
Here is the onCreate method for my activity.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
KeywordsCursorAdapter kwadapter = new KeywordsCursorAdapter(this, null);
txtKeyword = (AutoCompleteTextView)this.findViewById(R.id.txtKeyword);
txtKeyword.setAdapter(kwadapter);
txtCity = (AutoCompleteTextView)this.findViewById(R.id.txtCity);
btnSearch = (Button)this.findViewById(R.id.btnSearch);
btnSearch.setOnClickListener(this);
}
Here is the cursoradapter. You can pass null for cursor when constructing.
public class KeywordsCursorAdapter extends CursorAdapter {
private Context context;
public KeywordsCursorAdapter(Context context, Cursor c) {
super(context, c);
this.context = context;
}
//I store the autocomplete text view in a layout xml.
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.keyword_autocomplete, null);
return v;
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
String keyword = cursor.getString(cursor.getColumnIndex("keyword"));
TextView tv = (TextView)view.findViewById(R.id.txtAutocomplete);
tv.setText(keyword);
}
//you need to override this to return the string value when
//selecting an item from the autocomplete suggestions
//just do cursor.getstring(whatevercolumn);
#Override
public CharSequence convertToString(Cursor cursor) {
//return super.convertToString(cursor);
String value = "";
switch (type) {
case Keywords:
value = cursor.getString(DatabaseHelper.KEYWORD_COLUMN);
break;
case Cities:
value = cursor.getString(DatabaseHelper.CITY_COLUMN);
break;
}
return value;
}
#Override
public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
//return super.runQueryOnBackgroundThread(constraint);
String filter = "";
if (constraint == null) filter = "";
else
filter = constraint.toString();
//I have 2 DB-s and the one I use depends on user preference
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
//String selectedCountryCode = prefs.getString("selectedCountry", "GB");
String selectedCountryCode = prefs.getString(context.getString(R.string.settings_selected_country), "GB");
selectedCountryCode += "";
//Here i have a static SQLiteOpenHelper instance that returns a cursor.
Cursor cursor = MyApplication.getDbHelpers().get(selectedCountryCode.toLowerCase()).getKeywordsCursor(filter);
return cursor;
}
}
Here is the part that returns the cursor: it's just a select with a like condition.
public class DatabaseHelper extends SQLiteOpenHelper {
...
public synchronized Cursor getKeywordsCursor (String prefix) {
if (database == null) database = this.getReadableDatabase();
String[] columns = {"_id", "keyword"};
String[] args = {prefix};
Cursor cursor;
cursor = database.query("keywords", columns, "keyword like '' || ? || '%'", args, null, null, "keyword", "40");
int idcol = cursor.getColumnIndexOrThrow("_id");
int kwcol = cursor.getColumnIndexOrThrow("keyword");
while(cursor.moveToNext()) {
int id = cursor.getInt(idcol);
String kw = cursor.getString(kwcol);
Log.i("keyword", kw);
}
cursor.moveToPosition(-1);
return cursor;
}
...
}
You can also create a custom content provider but in this case it would be just another useless class you need to override.

Categories