2017-01-24 75 views
0

我的目標是在我的應用程序中有一個搜索欄,但它還沒有完全實用。搜索欄在那裏,但它沒有功能。在Android中搜索JSON

我跟着this教程,但我卡住了。任何幫助將不勝感激。

這裏是我的代碼:

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> 
+0

你能更具體一點嗎?你是否卡住了,你的問題是什麼,你已經做了什麼來嘗試修復它? – GAlexMES

+0

我可以看到你使用傳統的方式來綁定JSON對象。你爲什麼不使用[GSON](https://github.com/google/gson)或Jackson類庫來將你的json字符串綁定到對象? –

+0

http://stackoverflow.com/questions/27556623/creating-a-searchview-that-looks-like-the-material-design-guidelines – siva35

回答

0

創建可搜索的XML配置文件中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" /> 

而且,也Menifest.xml 定義該搜索的配置meta data像這樣

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

</activity> 

創建SearchActivity並定義IntentFilters

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

這個特殊的活動將處理您的搜索事件。

您可以按照this tutorial

0

我建議你使用材料搜索查看

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

必須是最後的正確分層顯示

<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