I am trying to make search suggestions. What I am trying to do is when user enters query I send HTTP Requests to server and fetch the JSON response and save it in database using Content Provider and Content Resolver.
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
MenuItem item = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
Toast.makeText(MainActivity.this, query, Toast.LENGTH_LONG).show();
Intent intent = new Intent(MainActivity.this,SearchActivity.class);
intent.putExtra("query",query);
startActivity(intent);
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
Log.d("Text Changing", newText);
if(newText.length() > 3){
String url = "https://www.xxxxx.com/xxxx/v1/volumes?q=" + newText + "&key=" + getResources().getString(R.string._api_key);
try {
HttpRequest httpRequest = new HttpRequest(url,MainActivity.this);
httpRequest.execute();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
return true;
}
});
return true;
}
void jsonParse(String jsonString) throws JSONException {
JSONObject jsonObject = new JSONObject(jsonString);
StringBuilder mAuthors = new StringBuilder();
if (jsonObject != null) {
JSONArray itemArray = jsonObject.getJSONArray("items");
for (int i = 0; i < itemArray.length(); i++) {
JSONObject itemObject = itemArray.getJSONObject(i);
JSONObject volumeInfo = itemObject.getJSONObject("volumeInfo");
if (volumeInfo.has("title"))
{
Log.d("titles",volumeInfo.getString("title"));
contentValues.put(BookContract.BookRow.BOOK_NAME,volumeInfo.get("title").toString());
}
if (volumeInfo.has("authors")) {
JSONArray authorArray = volumeInfo.getJSONArray("authors");
if (volumeInfo.getJSONArray("authors") != null) {
for (int j = 0; j < authorArray.length(); j++) {
mAuthors.append(volumeInfo.get("authors")+"\n");
}
contentValues.put(BookContract.BookRow.BOOK_AUTHOR,mAuthors.toString());
}
}
}
}
//contentResolver.delete(BookContract.BookRow.CONTENT_URI,null,null);
contentResolver.insert(BookContract.BookRow.CONTENT_URI,contentValues);
}
Now I don't know that to write in Content Provider query method, So that it display search suggestions.