简体   繁体   English

将数据从Json Google Places API解析到recyclerView时出现问题

[英]Problem in parsing data from Json Google Places API to recyclerView

I would like to show users a list of bar near by them, without map. 我想向用户显示他们附近的酒吧列表,没有地图。 I have tried by PlaceLikelihoods, it works fine but I can not put any restriction on the types of place found and it shows a map. 我已经尝试过PlaceLikelihoods,它可以正常工作,但是我不能对找到的地点类型施加任何限制,它可以显示地图。

So I searched by URL, but the Try / Catch always leads to the exception, the toast found there shows the good result but the list of recyclerview is not filled. 因此,我通过URL搜索,但“尝试/捕获”总是导致异常,在那里找到的吐司显示了很好的结果,但recyclerview的列表未填写。 I found a similar problem that said to move the notifyDataSetChanged(), I have done it. 我发现有一个类似的问题,据说已经完成了对notifyDataSetChanged()的移动。

I find APIs and parsing very complicated to master so it's probably a stupid mistake but it's been 2 weeks and I have not yet succeeded. 我发现掌握API和解析非常复杂,因此这可能是一个愚蠢的错误,但是已经过去了2周,但我还没有成功。 Thanks for reading. 谢谢阅读。

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();
        }
    }
}

} }

you are using hardcoded string 您正在使用硬编码的字符串

 JSONArray jArray = new JSONArray("results");

you have to use 你必须使用

JSONArray jArray = new JSONArray(result);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM