我用AutcompleteTextView创建了简单的Activity。我正在尝试使用google geocode api从输入字符串中获取地址。我在日志中获取地址,但无法在自动完成视图中获取它们:/我做错了什么?
public class SearchFragment extends Fragment implements OnClickListener {
private ListView mListView;
private Button mSearchButton;
private AutoCompleteTextView mSearchView;
private ArrayAdapter<String> mArrayAdapter;
@Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_search, container,
false);
mSearchButton = (Button) rootView
.findViewById(R.id.fragment_search_button);
mSearchButton.setOnClickListener(this);
mListView = (ListView) rootView.findViewById(R.id.fragment_search_list);
mSearchView = (AutoCompleteTextView) rootView.findViewById(R.id.fragment_search_input);
mArrayAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1);
mArrayAdapter.setNotifyOnChange(true);
mSearchView.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
mArrayAdapter.clear();
new FetchAutocompleteSuggestions().execute(buildSearchableUrl(s.toString()));
}
@Override
public void afterTextChanged(Editable s) {
}
});
return rootView;
}
private String buildSearchableUrl(String insert){
String result = "";
insert = insert.replace(" ", "+");
String intro = "http://maps.googleapis.com/maps/api/geocode/json?address=";
String outro = "&sensor=true&components=country:sk";
result = intro + insert + outro;
return result;
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.fragment_search_button:
new FetchAutocompleteSuggestions().execute(buildSearchableUrl(mSearchView.getText().toString()));
break;
default:
break;
}
}
private class FetchAutocompleteSuggestions extends AsyncTask<String, String, ArrayAdapter<String>>{
private JSONParser jsonParser;
@Override
protected ArrayAdapter<String> doInBackground(String... params) {
jsonParser = new JSONParser();
String mPreparedUrl = params[0];
JSONObject jobj = jsonParser.getJSONFromUrl(mPreparedUrl, null);
Log.i("", mPreparedUrl);
try{
JSONArray array = jobj.getJSONArray("results");
for (int i = 0; i < array.length(); i++) {
JSONObject childObject = array.getJSONObject(i);
String pom = childObject.getString("formatted_address");
Log.d("", pom);
mArrayAdapter.add(pom);
}
} catch (Exception e){
Log.e(e.toString(), "Chyba");
}
return mArrayAdapter;
}
@Override
protected void onPostExecute(ArrayAdapter<String> result) {
mSearchView.setAdapter(result);
}
}
}