SearchActivity如下:
view
我试图在用户在搜索栏上进行搜索时调用活动。我将public class SearchActivity extends AppCompatActivity {
// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private SimpleCursorAdapter myAdapter;
SearchView searchView = null;
private WarehouseSalesDetails[] strArrData;
private String selectedID;
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.search_item);
Toolbar toolBarSearch = (Toolbar)findViewById(R.id.toolbarSearch);
setSupportActionBar(toolBarSearch);
final String[] from = new String[]{"title"};
final int[] to = new int[]{android.R.id.text1};
//setup SimpleCursorAdapter
myAdapter = new SimpleCursorAdapter(SearchActivity.this,android.R.layout.simple_spinner_dropdown_item,null,from,to,
CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
new RetrieveWarehouseSalesTask(this).execute();
}
@Override
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.menu_search,menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchManager searchManager = (SearchManager)SearchActivity.this.getSystemService(Context.SEARCH_SERVICE);
if(searchItem!=null){
searchView = (SearchView) searchItem.getActionView();
}
if(searchView!=null){
searchView.setSearchableInfo(searchManager.getSearchableInfo(SearchActivity.this.getComponentName()));
searchView.setIconified(false);
searchView.setSuggestionsAdapter(myAdapter);
//getting selected on 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);
searchView.setQuery(cursor.getString(cursor.getColumnIndex("title")),false);
Log.d("strArr id",strArrData[position].id);
selectedID = strArrData[position].id;
return true;
}
@Override
public boolean onSuggestionSelect(int position){
return true;
}
});
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener(){
@Override
public boolean onQueryTextSubmit(String s){
Intent intent = new Intent(SearchActivity.this,RetrieveIndividualWarehouseSales.class);
intent.putExtra("pid",selectedID);
startActivity(intent);
return false;
}
@Override
public boolean onQueryTextChange(String s){
//filter data
final MatrixCursor mc = new MatrixCursor(new String[]{
BaseColumns._ID,"title"
});
for(int i = 0; i<strArrData.length; i++){
if(strArrData[i].title.toLowerCase().startsWith(s.toLowerCase())){
mc.addRow(new Object[]{i,strArrData[i].title});
}
}
myAdapter.changeCursor(mc);
return false;
}
});
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item){
return super.onOptionsItemSelected(item);
}
@Override
protected void onNewIntent(Intent intent){
if(Intent.ACTION_SEARCH.equals(intent.getAction())){
String query = intent.getStringExtra(SearchManager.QUERY);
if(searchView!=null){
searchView.clearFocus();
}
}
}
class RetrieveWarehouseSalesTask extends AsyncTask<Void,Void,Void> {
private String TAG = ActiveWarehouseSalesFragment.RetrieveWarehouseSalesTask.class.getSimpleName();
private String TAG_PID = "pid";
public ProgressDialog pDialog;
private Context context;
//URL to get JSON details
private String url = "http://example.com/example.php";
ArrayList<HashMap<String,String>> sales_details;
List<WarehouseSalesDetails> data = new ArrayList<>();
JSONObject jsonObj;
String jsonStr;
JSONArray sales;
//for recycler view
private RecyclerView warehouse_recycler;
private AdapterRecycler mAdapter;
public RetrieveWarehouseSalesTask(Context context){
this.context = context;
sales_details = new ArrayList<>();
}
@Override
protected void onPreExecute(){
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setMessage("Searching...");
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected Void doInBackground(Void... arg0){
HttpHandler sh = new HttpHandler();
//making a request to URL and getting response
jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url (SearchActivity): " + jsonStr);
return null;
}
@Override
protected void onPostExecute(Void result){
//ArrayList<String> dataList = new ArrayList<String>();
super.onPostExecute(result);
if(pDialog.isShowing()){
pDialog.dismiss();
}
if(jsonStr != null){
try{
jsonObj = new JSONObject(jsonStr);
//Getting JSON Array Node
sales = jsonObj.getJSONArray("Result");
//looping through all results
for(int i = sales.length() - 1; i >= 0 ;i--){
JSONObject s = sales.getJSONObject(i);
WarehouseSalesDetails wsd = new WarehouseSalesDetails();
wsd.id = s.getString("id");
wsd.company_name = s.getString("company_name");
wsd.promotion_image= s.getString("promotion_image");
wsd.title = s.getString("title");
wsd.promotional_period = s.getString("promotional_period");
wsd.viewCount = s.getString("view_count");
data.add(wsd);
}
//strArrData = dataList.toArray(new String[dataList.size()]);
strArrData = data.toArray(new WarehouseSalesDetails[data.size()]);
Log.d("TAG",sales_details.toString());
}catch(final JSONException e){
Log.e(TAG, "JSON parsing error: " + e.getMessage());
}
}else{
Log.e(TAG,"Couldn't get json from server");
}
/*//update RecyclerView
warehouse_recycler = (RecyclerView)((AppCompatActivity) context).findViewById(R.id.recyclerView);
mAdapter = new AdapterRecycler(context, data);
System.out.println("mAdapter size is: " + mAdapter.getItemCount());
System.out.println("Data size is: " + data.size());
final LinearLayoutManager layoutManager = new LinearLayoutManager(context);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
warehouse_recycler.setLayoutManager(layoutManager);
//mAdapter.notifyDataSetChanged();
warehouse_recycler.setAdapter(mAdapter);
warehouse_recycler.invalidate();
*/
}
}
}
和id
存储在title
中。显示的建议显示正确的值。但是,当我点击其中一个建议时,它总是传入错误的strArrData
。我发现,数组总是存储前几个json值的值。我该怎么解决这个问题?
答案 0 :(得分:0)
使用Hashmap找到解决方案。
首先将所有json值存储在hashmap中,如下所示:
HashMap<String, String> idMap = new HashMap<String, String>();
idMap.put(s.getString("id"),s.getString("title"));
其次,在您的类中实现此方法以基于hashmap值获取hashmap键:
public static Object getKeyFromValue(Map hm, Object value) {
for (Object o : hm.keySet()) {
if (hm.get(o).equals(value)) {
return o;
}
}
return null;
}
最后:
String selectedID = getKeyFromValue(idMap,selectedTitle).toString();
Log.d("selected id",selectedID);
Intent intent = new Intent(SearchActivity.this,NextActivity.class);
intent.putExtra("pid",selectedID);
startActivity(intent);