Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android: Implement app search suggestion based on server response

I need to build a search functionality in my android app which relies on json response from the server. The users will enter the search query in a searchview located in the actionbar. Based on what the user types a query will be made to the server and the server returned response should appear as drop down suggestion. How should I go about it . Based on the docs i have read I need to implement a content provider. What would be neatest way of implementing app search ?

like image 677
Vihaan Verma Avatar asked Jan 27 '14 07:01

Vihaan Verma


People also ask

How do I add search suggestions to my android?

To enable search suggestions from your application, the user must open "Searchable items" (in Settings > Search) and enable your application as a searchable item.

How do I create a search bar in XML?

To add a SearchView widget to the app bar, create a file named res/menu/options_menu. xml in your project and add the following code to the file. This code defines how to create the search item, such as the icon to use and the title of the item.

Does Android have a search function?

Search is a core user feature on Android. Users should be able to search any data that is available to them, whether the content is located on the device or the Internet. To help create a consistent search experience for users, Android provides a search framework that helps you implement search for your application.


1 Answers

See the below code I have implemented for EditText.You can also do something like this:

private ArrayList<JSONObject> mRightListOverlapData, mRightTempData;
mEdit_Search.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {


        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub
            mRightListOverlapData.clear();
            String searchTag = mEdit_Search.getText().toString();
            if (searchTag == null || searchTag.equals("")) {


                mRightTempData.clear();
                mOverlapAdapter.notifyDataSetChanged();

            } else if (searchTag.length() == 1) {

                    mRightListOverlapData.addAll(mRightTempData);



                    mOverlapAdapter.notifyDataSetChanged();
                } else {
                    **startServiceForSearchSuggestion(searchTag);**
                }


            } else {

                try {
                    if (mRightTempData.size() > 0) {

                        for (int i = 0; i < mRightTempData.size(); i++) {
                            if (mRightTempData.get(i)
                                    .getString("search_text").toLowerCase()
                                    .startsWith(searchTag.toLowerCase())) {
                                mRightListOverlapData.add(mRightTempData
                                        .get(i));
                            }
                        }
                        if (mRightListOverlapData.size() == 0) {
                            JSONObject noData = new JSONObject();
                            noData.put("search_text", "No Data");
                            mRightListOverlapData.add(noData);

                        }
                    }

                    mOverlapAdapter.notifyDataSetChanged();
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        }
    });

It will call webService when user enters 1st character in EditText.And then save all response into tempArray and when user enters another character it will search that element from tempArray. Method startServiceForSearchSuggestion() is:

private void startServiceForSearchSuggestion(String search_tag) {
    if (!Utils.isNetworkAvailable(getBaseContext())) {
        Toast.makeText(getBaseContext(), "No Network Available",
                Toast.LENGTH_SHORT).show();
    } else {
        Intent intent1 = new Intent(this, WebService.class);
        intent1.putExtra(METHOD, GET_SEARCH_SUGGESTION);
        intent1.putExtra("search_tag", search_tag);
        startService(intent1);
    }
}

It will start webservice to get response from server. The service class is:

 public class WebService extends Service implements WebServiceConstants {
    private AppPreferences mPrefs;
    private static String TAG_WEB_SERVICE = "WebService";
    private static String DEVICE_TYPE = "android";
    private static String MESSAGE_CENTER = "gcm";
    private static String URL_JSON = "YOUR_URL";
    private Context mContext;
    private int METHOD_NAME = 1;
    private String mSearch_Tag = "";
    private DBQuery mDBQuery;
    public static boolean is_Service_Running = false;

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        mContext = this;
        mPrefs = new AppPreferences(mContext);
        mDBQuery = new DBQuery(mContext);

    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onStart(Intent intent, int startId) {
        // TODO Auto-generated method stub
        try {
            METHOD_NAME = intent.getIntExtra(METHOD, 1);

                mSearch_Tag = intent.getStringExtra("search_tag");

            LoadDataFromServer data = new LoadDataFromServer();
            data.execute();
        } catch (NullPointerException e) {
            // TODO: handle exception
        }
        super.onStart(intent, startId);
    }

public class LoadDataFromServer extends AsyncTask<Void, Void, Void> {
        JSONObject response;

        @Override
        protected Void doInBackground(Void... params) {
            // TODO Auto-generated method stub
            JSONObject root = getJsonHeader();
            switch (METHOD_NAME) {


            case GET_SEARCH_SUGGESTION:
                response = getResponse(yourJsonRequestObject);
                break;

            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub
            try {

                switch (METHOD_NAME) {


                case GET_SEARCH_SUGGESTION:
                    Log.v(TAG_WEB_SERVICE,
                            "Response = GET_SEARCH_SUGGESTION : "
                                    + response.toString());
                    sendBroadcast(new Intent(METHOD_GET_SEARCH_SUGGESTION)
                            .putExtra("Response", response.toString()));

                    break;

                default:
                    break;
                }
            } catch (NullPointerException e) {
                // TODO: handle exception
            }

        }

    }
    }

onPostExecute method you have to send broadcast to your activity and onReceive of this broadCast you can save your Json data into arrayList.Like this:

private BroadcastReceiver mReceiverSearchSuggestion = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            JSONObject root;
            try {
                root = new JSONObject(intent.getStringExtra("Response"));
                setSearchSuggestions(root);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    };

Methods:

1.

private JSONObject getResponse(JSONObject obj) {
        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpParams myParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(myParams, 10000);
        HttpConnectionParams.setSoTimeout(myParams, 10000);
        String temp = "";

        try {

            HttpPost httppost = new HttpPost(URL_JSON);
            httppost.setHeader("Content-type", "application/json");
            StringEntity se = new StringEntity(obj.toString());
            se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                    "application/json"));
            httppost.setEntity(se);

            HttpResponse response = httpclient.execute(httppost);
            temp = EntityUtils.toString(response.getEntity());
            Log.v(TAG_WEB_SERVICE, "Temp = " + temp);
            if (temp == null || temp.trim().equals("")) {

            } else {
                return new JSONObject(temp);
            }
        } catch (ClientProtocolException e) {

        } catch (IOException e) {

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

2.

private void setSearchSuggestions(JSONObject root) {
        // TODO Auto-generated method stub
        try {
            JSONObject search_suggestion = root
                    .getJSONObject(METHOD_GET_SEARCH_SUGGESTION);
            if (search_suggestion.getString("response_type").equalsIgnoreCase(
                    "success")) {
                if (search_suggestion.has("data")) {
                    mRightTempData.clear();
                    mRightListOverlapData.clear();
                    JSONArray data = search_suggestion.getJSONArray("data");
                    for (int i = 0; i < data.length(); i++) {
                        JSONObject value = data.getJSONObject(i);

                        mRightTempData.add(value);
                    }

                } else {
                    Toast.makeText(getBaseContext(),
                            "No data related to search", Toast.LENGTH_SHORT)
                            .show();
                }
            } else {
                Toast.makeText(getBaseContext(),
                        "Search Suggestion : Type Failure", Toast.LENGTH_SHORT)
                        .show();
            }


    }

I have set adapter with arrayList of Json Object like this:

        mOverlapAdapter = new RightOverlapAdapter(getBaseContext(),
            mRightListOverlapData);

    mDListRightOverLap.setAdapter(mOverlapAdapter);

You can directly read data from ArrayList of JSONObject with specified tag into getView method of your adapter.

You need define this service in Manifest like this:

 <service android:name="com.your.package.WebService" />

Hope it will help you.

like image 73
AndiM Avatar answered Oct 13 '22 17:10

AndiM