Android搜索视图自动建议点击带来相关数据
我知道有很多建议的解决方案,其中大多数我都明白了使用AutoCompleteTextView和我希望使用Search view作为小型开发人员我试图找到适合我目标的解决方案,我有php脚本,可以提供这些json数据Android搜索视图自动建议点击带来相关数据,android,search,searchview,search-suggestion,matrixcursor,Android,Search,Searchview,Search Suggestion,Matrixcursor,我知道有很多建议的解决方案,其中大多数我都明白了使用AutoCompleteTextView和我希望使用Search view作为小型开发人员我试图找到适合我目标的解决方案,我有php脚本,可以提供这些json数据 [ {"fish_id":"1","fish_name":"Indian Mackerel","fish_weight":"2kg","price":"$10"}, {"fish_id":"2","fish_name":"Manthal Repti","fish_weight":"0
[
{"fish_id":"1","fish_name":"Indian Mackerel","fish_weight":"2kg","price":"$10"},
{"fish_id":"2","fish_name":"Manthal Repti","fish_weight":"0.5kg","price":"$3"},
{"fish_id":"3","fish_name":"Baby Sole Fish","fish_weight":"5kg","price":"$12"},
{"fish_id":"4","fish_name":"Clam Meat","fish_weight":"1kg","price":"$7"},
{"fish_id":"5","fish_name":"Indian Prawn","fish_weight":"0.2kg","price":"$5"}
]
经过长时间的搜索,我在自动建议中找到了“fish_name”数据,效果很好。主要目标是当我从自动建议列表中单击项目时,它必须显示json提供的所有相关内容,因此我得到了从sqlite数据库中获取数据的概念,它的问题是,它必须根据所选项目向服务器发送请求并带来结果,因此有点烦人和浪费时间
那么,我如何才能将所有这些数据带到应用程序中,并在自动建议中显示“fish_name”,当单击项目时,它必须显示所有需要的内容,即“fish_name”、“price”和“fish_weight”,以便提高应用程序的效率
///这里是主要的活动,里面有搜索功能
/// main activity with search fuctionarity
public class MainActivity extends AppCompatActivity {
SearchView searchView = null;
private String[] strArrData = {"No Suggestions"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textViewResult = (TextView) findViewById(R.id.textViewResult);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final String[] from = new String[] {"fishName"};
final int[] to = new int[] {android.R.id.text1};
// setup SimpleCursorAdapter
myAdapter = new SimpleCursorAdapter(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, null, from, to, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
// Fetch data from mysql table using AsyncTask
new AsyncFetch().execute();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// adds item to action bar
getMenuInflater().inflate(R.menu.menu_main, menu);
// Get Search item from action bar and Get Search service
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchManager searchManager = (SearchManager) MainActivity.this.getSystemService(Context.SEARCH_SERVICE);
if (searchItem != null) {
searchView = (SearchView) searchItem.getActionView();
}
if (searchView != null) {
searchView.setSearchableInfo(searchManager.getSearchableInfo(MainActivity.this.getComponentName()));
searchView.setIconified(false);
searchView.setSuggestionsAdapter(myAdapter);
// Getting selected (clicked) item suggestion
searchView.setOnSuggestionListener(new SearchView.OnSuggestionListener() {
@Override
public boolean onSuggestionClick(int position) {
// Add clicked text to search box
CursorAdapter ca = searchView.getSuggestionsAdapter();
Cursor cursor = ca.getCursor();
cursor.moveToPosition(position);
String mimi= cursor.getString(cursor.getColumnIndex("fishName"));
searchView.setQuery(cursor.getString(cursor.getColumnIndex("fishName")),false);
int id = (int) searchView.getSuggestionsAdapter().getItemId(position);
getData2(mimi);
return true;
}
@Override
public boolean onSuggestionSelect(int position) {
return true;
}
});
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String s) {
return false;
}
@Override
public boolean onQueryTextChange(String s) {
// Filter data
final MatrixCursor mc = new MatrixCursor(new String[]{ BaseColumns._ID, "fishName" });
for (int i=0; i<strArrData.length; i++) {
if (strArrData[i].toLowerCase().startsWith(s.toLowerCase()))
mc.addRow(new Object[] {i, strArrData[i]});
}
myAdapter.changeCursor(mc);
return false;
}
});
}
return true;
}
@Override
protected void onNewIntent(Intent intent) {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
if (searchView != null) {
searchView.clearFocus();
}
// User entered text and pressed search button. Perform task ex: fetching data from database and display
}
}
///具有搜索功能的主活动
公共类MainActivity扩展了AppCompatActivity{
SearchView SearchView=null;
私有字符串[]strArrData={“无建议”};
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textViewResult=(TextView)findViewById(R.id.textViewResult);
Toolbar Toolbar=(Toolbar)findViewById(R.id.Toolbar);
设置支持操作栏(工具栏);
最终字符串[]from=新字符串[]{“fishName”};
final int[]to=new int[]{android.R.id.text1};
//设置SimpleCorsorAdapter
myAdapter=new SimpleCursorAdapter(MainActivity.this,android.R.layout.simple\u微调器\u下拉菜单\u项,null,from,to,CursorAdapter.FLAG\u REGISTER\u CONTENT\u OBSERVER);
//使用AsyncTask从mysql表获取数据
新建AsyncFetch().execute();
}
@凌驾
公共布尔onCreateOptions菜单(菜单){
//将项目添加到操作栏
getMenuInflater().充气(右菜单菜单菜单主菜单);
//从操作栏获取搜索项并获取搜索服务
MenuItem searchItem=menu.findItem(R.id.action\u search);
SearchManager SearchManager=(SearchManager)MainActivity.this.getSystemService(Context.SEARCH\u服务);
if(searchItem!=null){
searchView=(searchView)searchItem.getActionView();
}
if(searchView!=null){
searchView.setSearchableInfo(searchManager.getSearchableInfo(MainActivity.this.getComponentName());
searchView.setIconified(false);
searchView.setSuggestionAdapter(myAdapter);
//获取所选(单击)项目建议
searchView.setOnSuggestionListener(新的searchView.OnSuggestionListener(){
@凌驾
公共布尔onSuggestionClick(整数位置){
//将单击的文本添加到搜索框
CursorAdapter ca=searchView.GetSuggestionAdapter();
Cursor=ca.getCursor();
光标。移动位置(位置);
字符串mimi=cursor.getString(cursor.getColumnIndex(“fishName”));
setQuery(cursor.getString(cursor.getColumnIndex(“fishName”)),false;
int id=(int)searchView.GetSuggestionAdapter().getItemId(位置);
getData2(mimi);
返回true;
}
@凌驾
公共布尔值onSuggestionSelect(整数位置){
返回true;
}
});
searchView.setOnQueryTextListener(新的searchView.OnQueryTextListener(){
@凌驾
公共布尔值onQueryTextSubmit(字符串s){
返回false;
}
@凌驾
公共布尔值onQueryTextChange(字符串s){
//过滤数据
final MatrixCursor mc=new MatrixCursor(新字符串[]{BaseColumns.\u ID,“fishName”});
对于(int i=0;isee感谢@pskink我已经看到了这个概念,但我在如何根据asnwer修改代码方面做了很多工作,你能告诉我如何在我的代码中添加这个概念吗?你只有不到50行代码,这里有什么不清楚的?我没有弄清楚的是在MatrixCursor中添加数据以及来自json数组的数据。我在Asycntak post execute上有json数组和MatrixCursor分开,那么如何让它们一起工作,而在你建议的答案中是相同的zone@pskinkjust用你的web服务替换我的web服务(Wikipedia search),仅需更改runQuery
方法即可
@Override
protected void onPostExecute(String result) {
//this method will be running on UI thread
ArrayList<String> dataList = new ArrayList<String>();
pdLoading.dismiss();
if(result.equals("no rows")) {
// Do some action if no data from database
}
else{
try {
JSONArray jArray = new JSONArray(result);
// Extract data from json and store into ArrayList
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
dataList.add(json_data.getString("fish_name"));
}
strArrData = dataList.toArray(new String[dataList.size()]);
}
catch (JSONException e) {
// You to understand what actually error is and handle it appropriately
Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
Toast.makeText(MainActivity.this, result.toString(), Toast.LENGTH_LONG).show(); }
}
}
private void getData2(String fish_name ) {
if (fish_name.equals("")) {
Toast.makeText(this, "Please select item", Toast.LENGTH_LONG).show();
return;
}
loading = ProgressDialog.show(this,"Please wait...","Fetching...",false,false);
String url = Config.DATA_URL+fish_name ;
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
loading.dismiss();
showJSON(response);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this,error.getMessage().toString(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String response){
String name="";
String weight="";
String price = "";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
JSONObject allegeData = result.getJSONObject(0);
name = allegeData.getString("fish_name");
weight = allegeData.getString("fish_weight");
price = allegeData.getString("price");
} catch (JSONException e) {
e.printStackTrace();
}
textViewResult.setText("Fish Name :\t"+name+"\n Weight :\t" +weight + "\n Price:\t"+ price);
}