【问题标题】:Problem in parsing data from Json Google Places API to recyclerView将数据从 Json Google Places API 解析到 recyclerView 时出现问题
【发布时间】:2019-07-15 11:09:37
【问题描述】:

我想向用户显示他们附近的酒吧列表,没有地图。我已经尝试过 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();
        }
    }
}

}

【问题讨论】:

  • 问题或错误?
  • 对不起,我不明白区别,我不知道。
  • 你遇到了什么异常?
  • #noob,错误,类型与 Jsonarray 不匹配。
  • 我对比了几个教程,似乎是对的我不明白问题出在哪里。

标签: java android json parsing google-places-api


【解决方案1】:

您正在使用硬编码字符串

 JSONArray jArray = new JSONArray("results");

你必须使用

JSONArray jArray = new JSONArray(result);

【讨论】:

  • 我再次输入结果(我在测试期间更改了它),我有相同的不匹配异常并且没有可见数据。所以我只是在我的错误上添加了一个错误-',谢谢,其他错误的任何想法?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-17
  • 1970-01-01
  • 1970-01-01
  • 2023-03-16
相关资源
最近更新 更多