Как использовать плавающий поиск с представлением списка, загруженного JSON? - PullRequest
0 голосов
/ 01 июня 2018

Я загружаю представление списка, используя json, это нормально работает. Теперь я хочу добавить плавающее представление поиска в этот список. Я не знаю, как использовать его для исправления и как реализовать мою собственную функцию поиска.мне.это мой код в основной деятельности:

public class MainActivity extends AppCompatActivity  {
    private String TAG = MainActivity.class.getSimpleName();
    private ProgressDialog pDialog;
    private ListView lv;
    EditText textView;
    Spinner s;
    // Search EditText
    EditText inputSearch;
FloatingSearchView mSearchView;
    // URL to get contacts JSON
//    private static String url ="http://10.3.216.241/WorkServIndus.nsf/ListeClient.xsp/ListeClient";
    private static String url ="http://myadress/WorkServIndus.nsf/ListeClient.xsp/ListeClient";
    ArrayList<HashMap<String, String>> contactList;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        contactList = new ArrayList<>();
        lv = (ListView) findViewById(R.id.list);
    //  s=(Spinner)findViewById(R.id.spinner);
       new GetContacts().execute();
    }



    /**
     * Async task class to get json by making HTTP call
     */
    private class GetContacts 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 contacts = new JSONArray(jsonStr);


                        // looping through All Contacts
                        for (int i = 0; i < contacts.length(); i++) {
                            JSONObject c = contacts.getJSONObject(i);
                            //  return new JSONObject(json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1));
                            String test=c.getString("ServiFournisseur");
                            String name = c.getString("universalID");
                            final  String localite=c.getString("Localite");

    HashMap<String, String> contact = new HashMap<>();

    // adding each child node to HashMap key => value

    contact.put("universalID", name);
    contact.put("ServiFournisseur", test);
    // contact.put("Localite", localite);
    //  contact.put("ServiFournisseur", lt_name);
    // contact.put("location", location);

    // adding contact to contact list
    contactList.add(contact);






                           // String lt_name = c.getString("ServiFournisseur");
                            // String location = c.getString("location");
                            //    return new JSONObject(jsonStr.substring(jsonStr.indexOf("{"), jsonObj.lastIndexOf("}") + 1));
                            // tmp hash map for single contact

                        }
                    } 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();
                ListAdapter adapter = new SimpleAdapter(
                        MainActivity.this, contactList,
                        R.layout.list_item, new String[]{"universalID","ServiFournisseur"
                }, new int[]{R.id.name,R.id.email
                       });
                lv.setAdapter(adapter);

            }

    }

это мой класс для подключения:

public class HttpHandler
{
    private static final String TAG = HttpHandler.class.getSimpleName();

    public HttpHandler() {
    }

    public String makeServiceCall(String reqUrl) {
        String response = null;
        try {
            URL url = new URL(reqUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            // read the response
            InputStream in = new BufferedInputStream(conn.getInputStream());
            response = convertStreamToString(in);
        } catch (MalformedURLException e) {
            Log.e(TAG, "MalformedURLException: " + e.getMessage());
        } catch (ProtocolException e) {
            Log.e(TAG, "ProtocolException: " + e.getMessage());
        } catch (IOException e) {
            Log.e(TAG, "IOException: " + e.getMessage());
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
        return response;
    }

    private String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line).append('\n');
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

это основной макет:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="tn.servi.mytest.MainActivity">
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >

        <com.arlib.floatingsearchview.FloatingSearchView
            android:id="@+id/floating_search_view"
            android:layout_width="wrap_content"
            android:layout_height="66dp"
            app:floatingSearch_close_search_on_keyboard_dismiss="true"
            app:floatingSearch_leftActionMode="showHamburger"
            app:floatingSearch_searchBarMarginLeft="@dimen/search_view_inset"
            app:floatingSearch_searchBarMarginRight="@dimen/search_view_inset"
            app:floatingSearch_searchBarMarginTop="@dimen/search_view_inset"
            app:floatingSearch_searchHint="Search..."
            app:floatingSearch_showSearchKey="false"
            app:floatingSearch_suggestionsListAnimDuration="250" />

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

    </LinearLayout>

</android.support.constraint.ConstraintLayout>

list_item.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    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">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="213dp"
            android:orientation="vertical"
            android:paddingLeft="24dp"
            android:paddingRight="24dp"
            android:paddingTop="56dp"
            tools:layout_editor_absoluteX="0dp"
            tools:layout_editor_absoluteY="16dp"
            tools:ignore="MissingConstraints">

                <TextView
                    android:id="@+id/name"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="8dp"
                    android:layout_marginTop="8dp"
                    android:textColor="@color/colorPrimaryDark"
                    android:textSize="16sp"
                    android:textStyle="bold" />

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="8dp"
                    android:layout_marginTop="8dp" />

                <TextView

                    android:id="@+id/email"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:paddingBottom="2dip"
                    android:textColor="@color/colorAccent" />

        </LinearLayout>
</android.support.constraint.ConstraintLayout>

1 Ответ

0 голосов
/ 01 июня 2018
mSearchView.setOnQueryChangeListener(new FloatingSearchView.OnQueryChangeListener() {
              @Override
              public void onSearchTextChanged(String oldQuery, final String newQuery) {

                  //get suggestions based on newQuery

                  //pass them on to the search view
                  mSearchView.swapSuggestions(newSuggestions);
              }
          });
...