I'm having massive problem in implementing autocomplete/Recent Suggestions in my app. I referred to the this link and tried to put it in my code : Android: Providing recent search suggestions without searchable activity? Somehow its not working.The database being used is sqlite. Here is my SearchActivity which is Main Activity in the above link:
public class SearchActivity extends GASessionMennagerActiviy {
private ArrayList<HashMap<String, String>> TripData = new ArrayList<HashMap<String, String>>();
static ListView Triplist;
RecommendedTripAdapter recommendedTripAdapter;
GetSearchTripsApi getTripsApi;
DB db;
CustomLoader p;
Preferences pref;
private SearchView searchView;
String searchKeywork;
private TextView empty;
private Button filterBtn;
private static String LoginUserId;
private String authId;
private TextView defaultText;
private static String[] FriendNames;
public static JsonArray tempjson = new JsonArray();
public static boolean setNewFilter = true;
// ==========================
static Dialog dialog;
static String SortType = "Relevance";
private static ArrayList<String> items;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.trip_by_locatoin);
// getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
// handleIntent(getIntent());
//autoComplete.setThreshold(1);
EndlessScrollListener.currentPage = 0;
EndlessScrollListener.previousTotal = 0;
try {
p = new CustomLoader(this,
android.R.style.Theme_Translucent_NoTitleBar);
db = new DB(this);
} catch (Exception e) {
// TODO: handle exception
}
mixPanelAppTraking = new MixPanelAppTraking();
// ====reset filters====
ResetFeilters();
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setIcon(R.drawable.action_bar_icon);
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#000000")));
@SuppressWarnings("null")
@SuppressLint("NewApi")
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// getMenuInflater().inflate(R.menu.main, menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
// Associate searchable configuration with the SearchView
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
MenuItem searchItem = menu.findItem(R.id.search);
searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
// searchView = (SearchView) menu.findItem(R.id.search).getActionView();
searchView.setSearchableInfo(searchManager
.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(false);
searchView.setOnQueryTextListener(new OnQueryTextListener() {
//@SuppressWarnings("null")
@Override
public boolean onQueryTextSubmit(String arg0) {
// TODO Auto-generated method stub
try {
defaultText.setVisibility(View.GONE);
// =========================
setNewFilter = true;
p.show();
searchKeywork = arg0;
TripData = new ArrayList<HashMap<String, String>>();
empty.setVisibility(View.GONE);
GetSearchTripsApi.innerJson = null;
// HitApi(0, searchKeywork, 0);
Constants.searchKeywork = searchKeywork;
GetTripsAPIs(0);
// =====Send GA SCREEN View====
try {
GAnalytics.SendScreenView("Search", GetGAText(),
getApplication());
} catch (Exception e) {
e.printStackTrace();
}
// =========event for mixpanel====
mixPanelAppTraking.SendSearchEvents(
getApplicationContext(), GetGAText(),
getString(R.string.action_search));
getWindow()
.setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
HashMap<String,String>hash1 = null;
hash1.put(Table.search_history.history.toString(), searchKeywork);
db.autoInsertUpdate(Table.Name.search_history, hash1, null, null);
return true;
} catch (Exception e) {
// TODO: handle exception
}
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
Cursor cursor = db.getSuggestions(newText);
if(cursor.getCount() != 0)
{
String[] columns = new String[] {DB.FIELD_SUGGESTION };
int[] columnTextId = new int[] { android.R.id.text1};
SuggestionSimpleCursorAdapter simple = new SuggestionSimpleCursorAdapter(getBaseContext(),
android.R.layout.simple_list_item_1, cursor,
columns , columnTextId
, 0);
searchView.setSuggestionsAdapter(simple);
return true;
}
else
{
return false;
}
}
});
}
now here is the DB and im using the last 2 methods on the end of this code.
public class DB {
public static String _DB_NAME = "tripoto.sqlite";
public static String _DB_BAK_NAME = "tripoto_backup.sqlite";
private static String _DB_PATH;
public final static String FIELD_SUGGESTION = "history";
private static int _DB_VERSION = 11;
;
private static Context _context;
private SQLiteDatabase sqdb;
private DBHelper helper;
/* private Handler handler; */
private DBListener dbListener;
private static boolean hasBackUp = false;
Preferences pref;
//
public DB(Context context) {
initialize(context, _DB_NAME, true);
}
//
public DB(Context context, boolean initialize) {
initialize(context, _DB_NAME, initialize);
}
public DB(Context context, String dbName, boolean initialize) {
initialize(context, dbName, initialize);
}
//
private void initialize(Context context, String dbName, boolean initialize) {
this._context = context;
pref = new Preferences(_context);
/* handler = new Handler(); */
_DB_PATH = "/data/data/" + context.getPackageName() + "/databases/";
helper = new DBHelper(this._context, dbName, null, _DB_VERSION);
deleteDB();
if (initialize)
deleteDB();
// createorUpgradeDatabse();
}
//
public void clear() {
_context = null;
sqdb = null;
helper = null;
/* handler = null; */
dbListener = null;
}
//
public void setDBListener(DBListener listener) {
dbListener = listener;
}
//
public void open() {
sqdb = helper.getWritableDatabase();
}
public void close() {
if (sqdb != null && sqdb.isOpen())
sqdb.close();
}
//
public SQLiteDatabase getSqliteDB() {
return sqdb;
}
public boolean extract(Context c) {
Log.d("Back Up Called", "");
boolean status = false;
File sf = new File(_DB_PATH, _DB_NAME);
File sf1 = new File(_DB_PATH, _DB_BAK_NAME);
File df = new File(Media.getAlbumDir(c, Media.DB_DIR), _DB_NAME);
File df1 = new File(Media.getAlbumDir(c, Media.DB_DIR), _DB_BAK_NAME);
// if (sf.exists()) {
try {
df.createNewFile();
copyDataBase(sf, df);
} catch (IOException e) { // TODO: handle exception
e.printStackTrace();
}
return status;
}
//
public void createorUpgradeDatabse() {
boolean dbExist = checkDataBase();
Log.d("ash_db", "Database Existence === " + dbExist);
if (!dbExist) {
// By calling this method and empty database will be created into
// the default system path
// of your application so we are gonna be able to overwrite that
// database with our database.
try {
sqdb = helper.getWritableDatabase();
} catch (SQLException e) {
Log.d("ash_exp", e.getMessage()
+ " at open(database not open for writing)");
}
try {
copyDataBase();
Log.d("ash_db", "Database Copied");
} catch (IOException e) {
Log.d("ash_exp", e.getMessage()
+ " at open (Database not Copied)");
}
}else {
sqdb = helper.getWritableDatabase();
}
}
//
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = _DB_PATH + _DB_NAME;
File file = new File(myPath);
if (file.exists() && !file.isDirectory())
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
} catch (Exception e) {
// Log.d("ash","Database not exist yet");
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
//
private void copyDataBase() throws IOException {
// Open your local db as the input stream
InputStream myInput = _context.getAssets().open(_DB_NAME);
// Path to the just created empty db
String outFileName = _DB_PATH + _DB_NAME;
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
// Close the streams
myOutput.close();
myInput.close();
}
//
private static void copyDataBase(File from, File to) throws IOException {
// Open your local db as the input stream
InputStream myInput = new FileInputStream(from);
// Path to the just created empty db
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(to);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
//
public void clear(String tableName, String where) {
getSqliteDB().execSQL(
"delete from " + tableName
+ (where == null ? "" : " where " + where));
}
//===================
public void autoInsertUpdate(String tableName, HashMap<String, String> values, String where, String[] args) {
if (where != null && isRecordExist(tableName, where, args) != Constants.kZero) {
update(tableName, values, where, args);
} else {
insert(tableName, values);
}
}
//====================
public int isRecordExist(String tableName, String where, String[] args) {
try {
int status = Constants.kZero;
Cursor c = getSqliteDB().query(tableName, null, where, args, null, null, null);
if (c.getCount() > 0) {
c.moveToNext();
status = c.getInt(0);
}
c.close();
return status;
} catch (Exception e) {
// TODO: handle exception
return Constants.kZero;
}
}
public int isRecordExist(String query, String[] args) {
int status = Constants.kZero;
Cursor c = getSqliteDB().rawQuery(query, args);
if (c.getCount() > 0) {
c.moveToNext();
status = c.getInt(0);
}
c.close();
return status;
}
//
public long insert(String tableName, HashMap<String, String> values) {
ContentValues vals = createContentValues(values);
return getSqliteDB().insert(tableName, null, vals);
}
//
public int update(String tableName, HashMap<String, String> values,
String where, String[] args) {
ContentValues vals = createContentValues(values);
return getSqliteDB().update(tableName, vals, where, args);
}
//
public ArrayList<HashMap<String, String>> find(String sql, String[] args) {
ArrayList<HashMap<String, String>> infos = new ArrayList<HashMap<String, String>>();
try {
Cursor c = getSqliteDB().rawQuery(sql, args);
if (c.moveToFirst()) {
while (!c.isAfterLast()) {
HashMap<String, String> info = new HashMap<String, String>();
String[] cols = c.getColumnNames();
for (String col : cols)
info.put(col, c.getString(c.getColumnIndex(col)));
c.moveToNext();
infos.add(info);
}
}
c.close();
} catch (Exception e) {
// TODO: handle exception
}
return infos;
}
//
public ArrayList<HashMap<String, String>> find(String tableName,
String where, String[] args, String other) {
String sql = "select * from " + tableName+ (where == null ? "" : " where " + where)+ (other == null ? "" : " " + other);
ArrayList<HashMap<String, String>> infos = find(sql, args);
return infos;
}
//
public Cursor findCursor(String sql, String[] args) {
Cursor cursor = getSqliteDB().rawQuery(sql, args);
return cursor;
}
//
public int getMaxValue(String tableName, String fieldName,
String whereCaluse) {
int maxVal = 0;
String query = "SELECT MAX(" + fieldName + ") FROM " + tableName;
if (whereCaluse != null) {
query = query + " WHERE " + whereCaluse;
}
Cursor c = findCursor(query, null);
if (c.moveToNext())
maxVal = c.getInt(0);
return maxVal;
}
//
public String getStringMaxValue(String tableName, String fieldName,
String whereCaluse) {
String maxVal = "";
String query = "SELECT MAX(" + fieldName + ") FROM " + tableName;
if (whereCaluse != null) {
query = query + " WHERE " + whereCaluse;
}
Cursor c = findCursor(query, null);
if (c.moveToNext())
maxVal = c.getString(0);
return maxVal;
}
public int getMinValue(String tableName, String fieldName,
String whereCaluse) {
int minVal = 0;
String query = "SELECT MIN(" + fieldName + ") FROM " + tableName;
if (whereCaluse != null) {
query = query + " WHERE " + whereCaluse;
}
Cursor c = findCursor(query, null);
if (c.moveToNext())
minVal = c.getInt(0);
return minVal;
}
//
public String getStringMinValue(String tableName, String fieldName,
String whereCaluse) {
String minVal = "";
String query = "SELECT MIN(" + fieldName + ") FROM " + tableName;
if (whereCaluse != null) {
query = query + " WHERE " + whereCaluse;
}
Cursor c = findCursor(query, null);
if (c.moveToNext())
minVal = c.getString(0);
return minVal;
}
//
public int getCount(String tableName, String whereCaluse) {
int minVal = 0;
String query = "SELECT COUNT(*) FROM " + tableName;
if (whereCaluse != null) {
query = query + " WHERE " + whereCaluse;
}
Cursor c = findCursor(query, null);
if (c.moveToNext())
minVal = c.getInt(0);
return minVal;
}
//
public Cursor findCursor(String tableName, String where, String[] args, String other) {
String sql = "select * from " + tableName + (where == null ? "" : " where " + where) + (other == null ? "" : " " + other);
Cursor c = findCursor(sql, args);
return c;
}
//
private ContentValues createContentValues(HashMap<String, String> values) {
ContentValues vals = new ContentValues();
String[] keys = values.keySet().toArray(new String[] {});
for (String key : keys)
vals.put(key, values.get(key));
return vals;
}
// ==
public static class Table {
// =====
public static class Name {
public final static String search_history="search_history";
}
// ------------------------------------------------
// ------------------------------------------------
public enum search_history{
history;
}
}
// =================================
public interface DBListener {
/** Executed when data is fetched via rawQuery */
public void onDataFetchedSucessfully(int queryId, Cursor c);
}
// =================================
class DBHelper extends SQLiteOpenHelper {
//
public DBHelper(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
}
//
@Override
public void onCreate(SQLiteDatabase db) {
// createTables(db);
}
private void insertAnyInitialRecords(SQLiteDatabase db) {
}
}
}
//============delete db=========
private void deleteDB() {
if (checkDataBase()) {
try {
try {
sqdb = helper.getWritableDatabase();
ArrayList<HashMap<String, String>> find = find(Table.Name.users, Table.users.id+" = '"+pref.get(Constants.loginUserId)+"'", null, null);
if (find.size() > 0 && find.get(0).get(Table.users.authid.toString()) != null && !find.get(0).get(Table.users.authid.toString()).equals("")) {
pref.set(Constants.loginAuthId, find.get(0).get(Table.users.authid.toString())).commit();
pref.set(Constants.loginUserImage, find.get(0).get(Table.users.profile_photo.toString())).commit();
pref.set(Constants.loginUserName, find.get(0).get(Table.users.full_name.toString())).commit();
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
//====close object===
try {
sqdb.close();
} catch (Exception e) {
// TODO: handle exception
}
int dbVersion = pref.getInt(Constants.DB_version);
if (dbVersion == 0) {
// dbVersion = _DB_VERSION;
}
// Toast.makeText(_context, dbVersion+"======="+_DB_VERSION+"==="+ pref.get(Constants.IsFirstTime), Toast.LENGTH_LONG).show();
if (_DB_VERSION > dbVersion) {
//=========
File dbFile = _context.getDatabasePath(_DB_PATH + _DB_NAME);
if (!dbFile.delete()) {
}else{
pref.set(Constants.BasicInfoTS, "0").commit();
pref.setBoolean(Constants.NotOnStartHome, false).commit();
pref.set(Constants.DB_version, _DB_VERSION).commit();
}
}else{
sqdb = helper.getWritableDatabase();
}
} catch (Exception e) {
// TODO: handle exception
}
}else{
createorUpgradeDatabse();
}
}
//=============================================
public long insertSuggestion(String text)
{
ContentValues values = new ContentValues();
values.put(Table.search_history.history.toString(), text);
return sqdb.insert(Table.Name.search_history, null, values);
}
public Cursor getSuggestions(String text)
{
return sqdb.query(Table.Name.search_history,null, null, null, null, null, null);//(true, Table.Name.search_history, Table.search_history.history.toString(), null, null, null, null, null,null);
}
//=================================================
}
and here is my cursor adapter
public class SuggestionSimpleCursorAdapter
extends SimpleCursorAdapter
{
public SuggestionSimpleCursorAdapter(Context context, int layout, Cursor c,
String[] from, int[] to) {
super(context, layout, c, from, to);
}
public SuggestionSimpleCursorAdapter(Context context, int layout, Cursor c,
String[] from, int[] to, int flags) {
super(context, layout, c, from, to, flags);
}
@Override
public CharSequence convertToString(Cursor cursor) {
int indexColumnSuggestion = cursor.getColumnIndex(DB.FIELD_SUGGESTION);
return cursor.getString(indexColumnSuggestion);
}
}
Now when i use my button no error appears but nothing happens as well. Having seen a lot of tutorials im just unable to implement any of this in my code. Kindly help.
Aucun commentaire:
Enregistrer un commentaire