我是新手.. 我需要你的帮助,关于SearchView的建议。从maps.google.com/maps/api/geocode接收和解析数据。一切看起来都很好。但为什么建议中没有文本呢?请帮我理解问题出在哪里...
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>