2015-12-04 2 views
2

Я новичок .. Мне нужна ваша помощь с предложением для SearchView. Данные из maps.google.com/maps/api/geocode возвращаются и обрабатываются. Все выглядит нормально. Но почему в предложениях нет текста? Пожалуйста, помогите мне понять, что случилось ...SearchVIew: пустой список предложений

screenshot

JsonParser класс:

public class JsonParser { 

public List<HashMap<String, String>> parse(JSONObject jsonObject) { 

    try { 
     JSONArray jsonArray=(JSONArray)jsonObject.get("results"); 
     List<HashMap<String,String>> places = new ArrayList<>(); 
     for (int counter=0; counter<jsonArray.length(); counter++) { 
      HashMap hm=new HashMap<String,String>(); 
      hm.put("id", String.valueOf(counter)); 
      hm.put("description",jsonArray.getJSONObject(counter).getString("formatted_address")); 
      hm.put("lat",jsonArray.getJSONObject(counter).getJSONObject("geometry").getJSONObject("location").getString("lat")); 
      hm.put("lng", jsonArray.getJSONObject(counter).getJSONObject("geometry").getJSONObject("location").getString("lng")); 
      places.add(hm); 
     } 
     return places; 
    } 
    catch (JSONException jE) { 
     jE.printStackTrace(); 
     return null; 
    } 

} 

класс PlaceProvider:

public class PlaceProvider extends ContentProvider { 
public static final String AUTHORITY = "com.gvozditskiy.photospots.PlaceProvider"; 

public static final Uri SEARCH_URI = Uri.parse("content://"+AUTHORITY+"/search"); 

public static final Uri DETAILS_URI = Uri.parse("content://"+AUTHORITY+"/details"); 

private static final int SEARCH = 1; 
private static final int SUGGESTIONS = 2; 
private static final int DETAILS = 3; 

private static final UriMatcher mUriMatcher = buildUriMatcher(); 

private static UriMatcher buildUriMatcher() { 

    UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); 

    // URI for "Go" button 
    uriMatcher.addURI(AUTHORITY, "search", SEARCH); 

    // URI for suggestions in Search Dialog 
    uriMatcher.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY,SUGGESTIONS); 

    // URI for Details 
    uriMatcher.addURI(AUTHORITY, "details",DETAILS); 

    return uriMatcher; 
} 

@Override 
public boolean onCreate() { 
    return false; 
} 

@Nullable 
@Override 
public Cursor query(Uri uri, String[] strings, String s, String[] strings1, String s1) { 
    String url="http://maps.google.com/maps/api/geocode/json?address="+strings1[0].replace(" ","+") 
      .replace(",","+"); 
    Cursor c=null; 
    JsonParser jsonParser=new JsonParser(); 
    String jSonString; 
    List<HashMap<String, String>> list; 
    MatrixCursor matrixCursor; 
    switch (mUriMatcher.match(uri)) { 
     case SEARCH: 
      matrixCursor=new MatrixCursor(new String[]{"description","lat","lng"}); 
      try { 
       jSonString=loadFromNetwork(url); 
       list=jsonParser.parse(new JSONObject(jSonString)); 
       for (int i=0; i<list.size(); i++) { 
        HashMap<String, String> hashMap=list.get(i); 
        matrixCursor.addRow(new String[] {hashMap.get("description"),hashMap.get("lat"), hashMap.get("lng")}); 
       } 
      } 
      catch (Exception e) {e.printStackTrace();} 
      c=matrixCursor; 
      break; 

     case SUGGESTIONS: 
      matrixCursor=new MatrixCursor(new String[]{"_id", SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA}); 
      try { 
       jSonString=loadFromNetwork(url); 
       list=jsonParser.parse(new JSONObject(jSonString)); 
       for (int i=0; i<list.size(); i++) { 
        HashMap<String, String> hashMap=list.get(i); 
        matrixCursor.addRow(new String[] {Integer.toString(i) ,hashMap.get("description")}); 
       } 
      } 
      catch (Exception e) {e.printStackTrace();} 
      c=matrixCursor; 
      break; 

     case DETAILS: 
      matrixCursor=new MatrixCursor(new String[]{"description","lat","lng"}); 
      try { 
       jSonString=loadFromNetwork(url); 
       list=jsonParser.parse(new JSONObject(jSonString)); 
       for (int i=0; i<list.size(); i++) { 
        HashMap<String, String> hashMap=list.get(i); 
        matrixCursor.addRow(new String[] {hashMap.get("description"),hashMap.get("lat"), hashMap.get("lng")}); 
       } 
      } 
      catch (Exception e) {e.printStackTrace();} 
      c=matrixCursor; 
      break; 
    } 
    return c; 
} 

@Nullable 
@Override 
public String getType(Uri uri) { 
    return null; 
} 

@Nullable 
@Override 
public Uri insert(Uri uri, ContentValues contentValues) { 
    return null; 
} 

@Override 
public int delete(Uri uri, String s, String[] strings) { 
    return 0; 
} 

@Override 
public int update(Uri uri, ContentValues contentValues, String s, String[] strings) { 
    return 0; 
} 

private String loadFromNetwork(String urlString) throws IOException { 
    InputStream stream = null; 
    String str =""; 
    try { 
     stream = downloadUrl(urlString); 
     str = readIt(stream); 
    } finally { 
     if (stream != null) { 
      stream.close(); 
     } 
    } 
    return str; 
} 


private InputStream downloadUrl(String urlString) throws IOException { 
    URL url = new URL(urlString); 
    HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
    conn.setReadTimeout(10000 /* milliseconds */); 
    conn.setConnectTimeout(15000 /* milliseconds */); 
    conn.setRequestMethod("GET"); 
    conn.setDoInput(true); 
    conn.connect(); 
    InputStream stream = conn.getInputStream(); 
    return stream; 
} 

private String readIt(InputStream stream) throws IOException, UnsupportedEncodingException { 
    final BufferedReader rd = new BufferedReader(new InputStreamReader(stream, Charset.forName("UTF-8"))); 
    StringBuilder stringBuilder=new StringBuilder(); 
    int d; 
    while ((d = rd.read()) !=-1) { 
     stringBuilder.append((char)d); 
    } 
    return new String(stringBuilder.toString()); 
} 

MainActivity (только часть, которая работает с поиском):

public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> { 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     sharedPreferences = getSharedPreferences(APP_PREFFERENCES, Context.MODE_PRIVATE); 
     Toolbar toolbar = (Toolbar) findViewById(R.id.materialBar); 
     setSupportActionBar(toolbar); 
     getSupportActionBar().setDisplayHomeAsUpEnabled(true); 
     getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_menu); 
     setupMenuDrawer(); 
     FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); 
     fabHide(); 
     spotList = new ArrayList<Spot>(); 
     setUpMapIfNeeded(); 
     isCameraSetted = false; 
     spotMarker = null; 
     doUpdate=true; 
     handleIntent(getIntent()); 

    } 

@Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     getMenuInflater().inflate(R.menu.menu_main, menu); 
     // Get the SearchView and set the searchable configuration 
     SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); 
     SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView(); 
     searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName())); 

     return true; 
    } 

private void handleIntent(Intent intent){ 
     if (intent != null && intent.getAction() != null) { 
      if (intent.getAction().equals(Intent.ACTION_SEARCH)) { 
       doSearch(intent.getStringExtra(SearchManager.QUERY)); 
      } else if (intent.getAction().equals(Intent.ACTION_VIEW)) { 
       getPlace(intent.getStringExtra(SearchManager.EXTRA_DATA_KEY)); 
      } 
     } 
    } 

    @Override 
    protected void onNewIntent(Intent intent) { 
     super.onNewIntent(intent); 
     setIntent(intent); 
     handleIntent(intent); 
    } 

    private void doSearch(String query){ 
     Bundle data = new Bundle(); 
     data.putString("query", query); 
     getSupportLoaderManager().restartLoader(0, data, this); 
    } 

    private void getPlace(String query){ 
     Bundle data = new Bundle(); 
     data.putString("query", query); 
     getSupportLoaderManager().restartLoader(1, data, this); 
    } 

    @Override 
    public Loader<Cursor> onCreateLoader(int id, Bundle args) { 
     CursorLoader cLoader = null; 
     if(id==0) 
      cLoader = new CursorLoader(getBaseContext(), PlaceProvider.SEARCH_URI, null, null, new String[]{ args.getString("query") }, null); 
     else if(id==1) 
      cLoader = new CursorLoader(getBaseContext(), PlaceProvider.DETAILS_URI, null, null, new String[]{ args.getString("query") }, null); 
     return cLoader; 
    } 

    @Override 
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) { 
     LatLng placePos; 
     data.moveToFirst(); 
     placePos = new LatLng(Double.parseDouble(data.getString(1)), Double.parseDouble(data.getString(2))); 
     setCamera(sMap, false, placePos); 

    } 

    @Override 
    public void onLoaderReset(Loader<Cursor> loader) { 

    } 

} 
} 

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" 
     android:searchSuggestAuthority="com.gvozditskiy.photospots.PlaceProvider" 
     android:searchSuggestIntentAction="android.intent.action.VIEW" 
     android:searchSuggestSelection=" ?" 
     android:searchSuggestThreshold="2" > 

    </searchable> 

Меню:

<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=".ScrollingActivity"> 


    <item 
     android:id="@+id/pointslist_main_menu" 
     android:icon="@drawable/ic_view_list_white_24dp" 
     android:title="@string/drawer_item_spots" 
     app:showAsAction="always"/> 

    <item 
     android:id="@+id/action_search" 
     android:icon="@drawable/ic_action_action_search" 
     android:orderInCategory="100" 
     android:title="@string/action_search_main_menu" 
     app:showAsAction="always" 
     app:actionViewClass="android.support.v7.widget.SearchView"/> 
</menu> 
+0

Вам необходимо установить адаптер на вашем SearchView и обновить значения в пределах адаптера раз у вас есть данные. См. Http://stackoverflow.com/questions/26786179/searchview-filtering-and-set-suggestions –

+0

@SebastianRoth Я попытался сделать как в примере [link] (http://wptrafficanalyzer.in/blog/android-searchview- виджет-с Google-места-апи-используя-ActionBarSherlock-библиотека /). Как я понимаю, это другой способ (я ошибаюсь?). Теперь я заинтересован в поиске моей ошибки. Тогда я попытаюсь реализовать решение в вашей ссылке. –

ответ

1

Проблема решена путем замены:

в классе PlaceProvider:

case SUGGESTIONS: 
     matrixCursor=new MatrixCursor(new String[]{"_id", SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA}); 

в

case SUGGESTIONS: 
      matrixCursor=new MatrixCursor(new String[]{"_id",SearchManager.SUGGEST_COLUMN_TEXT_1}); 

в классе MainActivity:

private void handleIntent(Intent intent){ 
    if (intent != null && intent.getAction() != null) { 
     if (intent.getAction().equals(Intent.ACTION_SEARCH)) { 
      doSearch(intent.getStringExtra(SearchManager.QUERY)); 
     } else if (intent.getAction().equals(Intent.ACTION_VIEW)) { 
      getPlace(intent.getStringExtra(SearchManager.EXTRA_DATA_KEY)); 
     } 
    } 
} 

в

private void handleIntent(Intent intent){ 
    if(intent.getAction().equals(Intent.ACTION_SEARCH)){ 
     doSearch(intent.getStringExtra(SearchManager.QUERY)); 
    }else if(intent.getAction().equals(Intent.ACTION_VIEW)){ 
     getPlace(intent.getStringExtra(SearchManager.SUGGEST_COLUMN_TEXT_1)); 
    } 
}