java - 将数据从 Json Google Places API 解析到 recyclerView 时出现问题
问题描述
我想向用户显示他们附近的酒吧列表,没有地图。我已经尝试过 PlaceLikelihoods,它工作正常,但我不能对找到的地点类型施加任何限制,它会显示地图。
所以我通过 URL 搜索,但是 Try / Catch 总是导致异常,在那里找到的 toast 显示了很好的结果,但是 recyclerview 的列表没有填满。我发现了一个类似的问题,说要移动 notifyDataSetChanged(),我已经做到了。
我发现要掌握 API 和解析非常复杂,所以这可能是一个愚蠢的错误,但已经 2 周了,我还没有成功。谢谢阅读。
public class TestMap extends AppCompatActivity {
// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private LocListAdapter mAdapter;
private EmptyStateRecyclerView mLocRecView;
private ArrayList<LocListUser> data;
private double longitudeUser;
private double latitudeUser;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loc);
data = new ArrayList<>();
mAdapter = new LocListAdapter(data, TestMap.this);
mLocRecView = findViewById(R.id.locRecView);
mLocRecView.setItemAnimator(new DefaultItemAnimator());
mLocRecView.setLayoutManager(new LinearLayoutManager(TestMap.this));
mLocRecView.setHasFixedSize(true);
//data.clear();
mLocRecView.setAdapter(mAdapter);
mLocRecView.clearStateDisplays();
longitudeUser = getIntent().getDoubleExtra("long", 151.2106085);
latitudeUser = getIntent().getDoubleExtra("lat", -33.8523341);
new AsyncFetch().execute();
}
private class AsyncFetch extends AsyncTask<String, String, String> {
ProgressDialog pdLoading = new ProgressDialog(TestMap.this);
HttpURLConnection conn;
URL url = null;
@Override
protected void onPreExecute() {
super.onPreExecute();
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
@Override
protected String doInBackground(String... params) {
try {
StringBuilder sb;
sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
sb.append("location=").append(latitudeUser).append(",").append(longitudeUser);
sb.append("&radius=5000");
sb.append("&types=" + "bar");
sb.append("&key=API_KEY");
url = new URL(String.valueOf(sb));
} catch (MalformedURLException e) {
e.printStackTrace();
return e.toString();
}
try {
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("GET");
conn.setDoOutput(true);
} catch (IOException e1) {
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
if (response_code == HttpURLConnection.HTTP_OK) {
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return ("unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
@Override
protected void onPostExecute(String result) {
pdLoading.dismiss();
try {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
LocListUser locList = new LocListUser();
locList.setAddress(json_data.getString("vicinity"));
locList.setId(json_data.getString("reference"));
locList.setName(json_data.getString("place_name"));
locList.setLat(json_data.getJSONObject("geometry").getJSONObject("location").getString("lat"));
locList.setLon(json_data.getJSONObject("geometry").getJSONObject("location").getString("lng"));
locList.setType(json_data.getString("types"));
locList.setLatUser(latitudeUser);
locList.setLonUser(longitudeUser);
data.add(locList);
mAdapter.notifyDataSetChanged();
}
//mAdapter.notifyDataSetChanged();
mLocRecView.invokeState(EmptyStateRecyclerView.STATE_OK);
} catch (JSONException e) { //e.toString()
e.printStackTrace();
}
}
}
}
解决方案
您正在使用硬编码字符串
JSONArray jArray = new JSONArray("results");
你必须使用
JSONArray jArray = new JSONArray(result);
推荐阅读
- python - 如何在 python 中将下载为 .webm 的 Youtube 视频转换为 .mp3(在代码本身内)
- android-studio - bringing back android studio's main menu
- javascript - 如何在纯 JavaScript 中创建项目组件/模块?
- typeorm - 查询生成器中的调用函数
- angular6 - 单击角度 7 中的按钮时取消 http 请求
- python - Tkinter 在绑定到时双重打印字符
- ruby-on-rails - URL 参数被转换为看似乱码的字符
- web-scraping - 带有 rvest 的 xpath 失败,返回一个空列表
- javascript - 使用 Jest Enzyme 测试 React Reducer
- lambda - JavaAssist 在 ASM 中是否有类似 visitInvokeDynamicInsn 的东西