0

my goal is to have a search bar in my app, but it's not fully functional yet. The search bar is there, but it has no function.

I'm following this tutorial, but I'm stuck. Any help would be greatly appreciated.

Here are my codes:

MainActivity.java

package com.example.jsonparser;

import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v7.widget.SearchView;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

public class MainActivity extends AppCompatActivity {

    private String TAG = MainActivity.class.getSimpleName();

    private ProgressDialog pDialog;
    private ListView lv;

    // URL to get contacts JSON
    private static String url = "http://pastebin.com/raw/nL15tpa3";

    ArrayList<HashMap<String, String>> itemList;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.search, menu);
        final MenuItem searchItem = menu.findItem(R.id.action_search);
        final SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                searchView.clearFocus();
                searchView.setQuery("", false);
                searchView.setIconified(true);
                searchItem.collapseActionView();
                MainActivity.this.setTitle(query);
                return true;
            }

            @Override
            public boolean onQueryTextChange(String s) {
                return false;
            }

        });
        return true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        itemList = new ArrayList<>();

        lv = (ListView) findViewById(R.id.list);

        new GetItems().execute();
    }

    /**
     * Async task class to get json by making HTTP call
     */
    private class GetItems extends AsyncTask<Void, Void, Void> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            HttpHandler sh = new HttpHandler();

            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url);

            Log.e(TAG, "Response from url: " + jsonStr);

            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);

                    // Getting JSON Array node
                    JSONArray items = jsonObj.getJSONArray("Data");

                    // looping through All Items
                    for (int i = 0; i < items.length(); i++) {
                        JSONObject c = items.getJSONObject(i);

                        String ModelCode = c.getString("ModelCode");
                        String ModelName = c.getString("ModelName");

                        // tmp hash map for single item
                        HashMap<String, String> item = new HashMap<>();

                        // adding each child node to HashMap key => value
                        item.put("ModelCode", ModelCode);
                        item.put("ModelName", ModelName);

                        // adding item to item list
                        itemList.add(item);
                    }

                } catch (final JSONException e) {
                    Log.e(TAG, "Json parsing error: " + e.getMessage());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(),
                                    "Json parsing error: " + e.getMessage(),
                                    Toast.LENGTH_LONG)
                                    .show();
                        }
                    });

                }
            } else {
                Log.e(TAG, "Couldn't get json from server.");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Couldn't get json from server. Check LogCat for possible errors!",
                                Toast.LENGTH_LONG)
                                .show();
                    }
                });

            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
            /**
             * Updating parsed JSON data into ListView
             * */
            ListAdapter adapter = new SimpleAdapter(
                    MainActivity.this, itemList,
                    R.layout.list_item, new String[]{"ModelCode", "ModelName"}, new int[]{R.id.ModelCode,
                    R.id.ModelName});

            lv.setAdapter(adapter);
        }

    }

    private class ModelClient {
    }
}

Search.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".BookListActivity">
    <item
        android:id="@+id/action_search"
        android:title="Search"
        android:icon="@android:drawable/ic_menu_search"
        app:showAsAction="always"
        app:actionViewClass="android.support.v7.widget.SearchView" />
</menu>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.jsonparser.MainActivity">

    <ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

</RelativeLayout>

list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="@dimen/activity_horizontal_margin">

    <TextView
        android:id="@+id/ModelName"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="2dip"
        android:paddingTop="6dip"
        android:textColor="@color/colorPrimaryDark"
        android:textSize="16sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/ModelCode"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="2dip"
        android:textColor="@color/colorAccent" />
</LinearLayout>
Kent Dalanon
  • 13
  • 1
  • 5
  • Can you be a bit more specific? Were do you stuck, what is your problem, what do you already did to try to fix it? – GAlexMES Jan 24 '17 at 06:47
  • I can see that you are using traditional way to bind JSON objects. Why don't you use [GSON](https://github.com/google/gson) or Jackson like libraries to bind your json string to object? – Chintan Rathod Jan 24 '17 at 06:53
  • http://stackoverflow.com/questions/27556623/creating-a-searchview-that-looks-like-the-material-design-guidelines – sivaBE35 Jan 24 '17 at 06:56
  • https://i.imgur.com/Z8FRtLc.png This part, especially the API part since the URL in my code doesn't have an API, it's directly JSON – Kent Dalanon Jan 24 '17 at 06:56
  • @Chintan Rathod can GSON do JSON search? How? – Kent Dalanon Jan 24 '17 at 06:59
  • It is not related to your question but it will remove your boilorplate code of `for` loop. Check [this tutorial](http://www.studytrails.com/java/json/java-google-json-parse-json-to-java/) – Chintan Rathod Jan 24 '17 at 07:03

2 Answers2

0

Create searchable configuration xml file inside res/xml/searchable.xml:

<?xml version="1.0" encoding="utf-8"?>

<searchable xmlns:android="http://schemas.android.com/apk/res/android"
        android:label="@string/app_name"
        android:hint="@string/search_hint" />

And also define this searchable configuration as meta-data in Manifest.xml like this:

<activity ... >
    ...
    <meta-data android:name="android.app.searchable"
            android:resource="@xml/searchable" />

</activity>

Create SearchActivity and define IntentFilters to it:

<activity android:name=".SearchResultsActivity" ... >
    ...
    <intent-filter>
        <action android:name="android.intent.action.SEARCH" />
    </intent-filter>
    ...
</activity>

This particular Activity will handle your search event.

You can follow this tutorial.

JorgeAmVF
  • 1,660
  • 3
  • 21
  • 32
Milind Mevada
  • 3,145
  • 1
  • 14
  • 22
  • In the case of the `SearchActivity` derived from a list `Adapter`, should I just copy and paste the `MainActivity` `Adapter` to the `SearchActivity`? The interface in this tutorial is not my problem, but how to present the result is what I'm not getting. – JorgeAmVF May 08 '19 at 10:44
0

I suggest you to use Material SearchView

dependencies {
    compile 'com.miguelcatalan:materialsearchview:1.4.0'
}

Must be last for right layering display

<FrameLayout
    android:id="@+id/toolbar_container"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@color/theme_primary" />

    <com.miguelcatalan.materialsearchview.MaterialSearchView
        android:id="@+id/search_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</FrameLayout>

https://github.com/MiguelCatalan/MaterialSearchView

enter image description here

Chintan Rathod
  • 25,864
  • 13
  • 83
  • 93
Aditya Vyas-Lakhan
  • 13,409
  • 16
  • 61
  • 96