我正在努力提出搜索建议。我想要做的是当用户输入查询时我将HTTP请求发送到服务器并获取JSON响应并使用Content Provider和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);
}
现在我不知道要在Content Provider中编写查询方法,以便显示搜索建议。