0

I know there is a lot of solutions suggested and most of them i got understand them clear use AutoCompleteTextView and i want usesearch view as small developer i try to find the solution to fit my goal , i have php script that bring these json data

[
{"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"}
]

After long search i found this which bring data "fish_name" on auto suggestion and it works fine.The main goal is when i click item from auto suggestion list it has to display all related contents as brough by json, So i got this concept which bring data from sqlite database, the problem with it is it has to send request to the server based on selected item and bring results, so it kind annoying and time wasting.

So how can i bring all this data to the app and display "fish_name"on auto suggest and when item clicked it has to display all disired contents i mean "fish_name","price" and "fish_weight", so that i can increase app efficiency.

///Here is main activity with search fuctionarity inside

 /// 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(); }
             }
             }

// Method to fetch data base on the fish_name selected using volley

     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);
        }
f2k
  • 99
  • 11
  • see http://stackoverflow.com/a/19860624/2252830 – pskink Apr 26 '17 at 08:19
  • thanks @pskink i have seen the concept but i stack on how to modify codes based on your asnwer, can you please how to add the concept in my codes? – f2k Apr 26 '17 at 08:53
  • you have less than 50 lines of code, what's unclear here? – pskink Apr 26 '17 at 09:11
  • what i did not get clear is adding of data in MatrixCursor with data from json array.. i have json array on Asycntak post execute and MatrixCursor separate so how to make them work togather while in the answer you suggested are in the same zone@pskink – f2k Apr 26 '17 at 09:39
  • just replace my web service (Wikipedia search) with yours, that's all, simply change `runQuery` method – pskink Apr 26 '17 at 09:42
  • ok let me try it@pskink – f2k Apr 26 '17 at 10:43
  • am using search view and what you gave me is AutoCompleteTextView @pskink – f2k Apr 26 '17 at 22:40
  • @pskink only i miss is this in my code AsyncTask onPostExecute when i add this app crash. try { JSONArray jArray = new JSONArray(result); for (int i = 0; i < jArray.length(); i++) { JSONObject json_data = jArray.getJSONObject(i); dataList.add(json_data.getString("fish_name"));dataList.add(json_data.getString("fish_weight"));dataList.add(json_data.getString("price")); } strArrData = dataList.toArray(new String[dataList.size()]); }, – f2k Apr 26 '17 at 22:54
  • remove `searchView.setOnQueryTextListener(...` call `searchView.setSuggestionsAdapter()` with my adapter and remove your custom `AsyncTask`, basically with `SearchView` it works the same as with `AutoCompleteTextView` - the only difference is with `ACTV` you call `setAdapter` while with `SW` you call `setSuggestionsAdapter` – pskink Apr 27 '17 at 05:04
  • ok let me try it@pskink – f2k Apr 27 '17 at 06:17
  • i still get confused as i said before am real beginner , if you do not mind can you help me with example where and what should i add or remove , since i tried your example but the problem am working on oncreate option menu and you suggeted to use it in on create@pskink is almost two days and am still in dark – f2k Apr 27 '17 at 14:00
  • Did you run my code? If so, then use my adapter and pass it to setSuggestionAdapter, run it again, then modify my adapter so it calls your web api – pskink Apr 27 '17 at 14:04
  • i run it just by changing url the rest of the codes are the same but when i search it give no results @pskink – f2k Apr 27 '17 at 14:53
  • yes,i run it just by changing url the rest of the codes are the same but when i search it give no results @pskink – f2k Apr 27 '17 at 15:08

0 Answers0