我知道有很多建议的解决方案,其中大多数我明白他们清楚地使用 AutoCompleteTextView,我希望使用搜索视图作为小型开发人员我试图找到适合我的目标的解决方案,我有 php 脚本可以带来这些 json 数据
[
{"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
}
}
//AsyncTask onPostExecute
@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(); }
}
}
// 根据使用 volley 选择的 fish_name 获取数据库的方法
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);
}