Google Places API未在RecyclerView中显示

时间:2017-10-14 07:08:18

标签: android json android-recyclerview hashmap google-places-api

我做了一个简单的项目,旨在获取附近餐馆的数据,并用它填充RecyclerView。但是,当我使用我的代码运行应用程序时,没有任何显示。 logcat没有显示任何错误,应用程序也没有崩溃。下面显示的是代码和logcat。非常感谢你的帮助。非常感谢你。 (顺便说一句,我从这个问题的示例代码中省略了api键。)

MainActivity.java

package com.example.matts.placessample;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

public class MainActivity extends AppCompatActivity {

    public static ArrayList<HashMap<String, String>> placeList = new ArrayList<>();
    public static HashMap<String, String> place = new HashMap<>();

    private PlacesAdapter mAdapter;
    private RecyclerView mRecyclerView;
    private LinearLayoutManager mLayoutManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mRecyclerView = findViewById(R.id.recyclerView);

        mRecyclerView.setHasFixedSize(true);

        mLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(mLayoutManager);

        mAdapter = new PlacesAdapter(this, placeList);
        mRecyclerView.setAdapter(mAdapter);

        new GetPlaces().execute();
    }

    private class GetPlaces extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute () {
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground (Void... arg0) {
            HttpHandler sh = new HttpHandler();

            String url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=14.5649806,120.9934743&radius=500&type=restaurant&key=INSERT_API_KEY";
            String jsonString = sh.makeServiceCall(url);
            String TAG = "Hello";

            if (jsonString != null) {
                try {
                    JSONObject jsonObject = new JSONObject(jsonString);
                    JSONArray places = jsonObject.getJSONArray("results");

                    for (int i = 0; i < places.length(); i++) {
                        JSONObject p = places.getJSONObject(i);

                        String name = p.getString("name");
                        String vicinity = p.getString("vicinity");

                        place.put("name", name);
                        place.put("vicinity", vicinity);

                        placeList.add(place);
                    }

                } catch (final JSONException e) {
                    Log.e(TAG, "Json parsing error: " + e.getMessage());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(),
                                    "Json parsing error: " + e.getMessage(),
                                    Toast.LENGTH_LONG).show();
                        }
                    });
                }

            } else {
                Log.e(TAG, "Couldn't get json from server.");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Couldn't get json from server. Check LogCat for possible errors!",
                                Toast.LENGTH_LONG).show();
                    }
                });
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
        }
    }
}

Adapter.java

package com.example.matts.placessample;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.HashMap;

import static com.example.matts.placessample.MainActivity.place;
import static com.example.matts.placessample.MainActivity.placeList;

class PlacesAdapter extends RecyclerView.Adapter<PlacesAdapter.PlaceViewHolder>{

    private static ArrayList<HashMap<String, String>> mPlaceList;
    private Context mContext;
    private LayoutInflater inflater;

    PlacesAdapter(Context context, ArrayList<HashMap<String, String>> list) {
        mContext = context;
        inflater= LayoutInflater.from(context);
        mPlaceList = list;
    }

    static class PlaceViewHolder extends RecyclerView.ViewHolder {
        private TextView name;
        private TextView vicinity;

        PlaceViewHolder(View itemView) {
            super(itemView);
            name = itemView.findViewById(R.id.name);
            vicinity = itemView.findViewById(R.id.vicinity);
        }
    }

    @Override
    public PlaceViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemsView = LayoutInflater
                .from(parent.getContext())
                .inflate(R.layout.list_item, parent, false);

        return new PlaceViewHolder(itemsView);
    }

    @Override
    public void onBindViewHolder(PlaceViewHolder holder, int position) {
        holder.name.setText(place.get("name"));
        holder.vicinity.setText(place.get("vicinity"));
    }

    @Override
    public int getItemCount() {
        return placeList.size();
    }
}

logcat的

10-14 15:04:55.276 21207-21207/? I/art: Late-enabling -Xcheck:jni
10-14 15:04:55.292 21207-21214/? E/art: Failed sending reply to debugger: Broken pipe
10-14 15:04:55.292 21207-21214/? I/art: Debugger is no longer active
10-14 15:04:55.292 21207-21214/? I/art: Starting a blocking GC Instrumentation
10-14 15:04:55.438 21207-21207/? W/System: ClassLoader referenced unknown path: /data/app/com.example.matts.placessample-2/lib/arm64
10-14 15:04:55.449 21207-21207/? I/InstantRun: starting instant run server: is main process
10-14 15:04:55.452 21207-21207/? V/Monotype: SetAppTypeFace- try to flip, app = com.example.matts.placessample
10-14 15:04:55.454 21207-21207/? V/Monotype:     Typeface getFontPathFlipFont - systemFont = default#default
10-14 15:04:55.518 21207-21207/? W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
10-14 15:04:55.526 21207-21207/? V/Monotype: SetAppTypeFace- try to flip, app = com.example.matts.placessample
10-14 15:04:55.527 21207-21207/? V/Monotype:     Typeface getFontPathFlipFont - systemFont = default#default
10-14 15:04:55.555 21207-21207/? V/BoostFramework: mAcquireFunc method = public int com.qualcomm.qti.Performance.perfLockAcquire(int,int[])
10-14 15:04:55.555 21207-21207/? V/BoostFramework: mReleaseFunc method = public int com.qualcomm.qti.Performance.perfLockRelease()
10-14 15:04:55.555 21207-21207/? V/BoostFramework: mAcquireTouchFunc method = public int com.qualcomm.qti.Performance.perfLockAcquireTouch(android.view.MotionEvent,android.util.DisplayMetrics,int,int[])
10-14 15:04:55.555 21207-21207/? V/BoostFramework: mIOPStart method = public int com.qualcomm.qti.Performance.perfIOPrefetchStart(int,java.lang.String)
10-14 15:04:55.555 21207-21207/? V/BoostFramework: mIOPStop method = public int com.qualcomm.qti.Performance.perfIOPrefetchStop()
10-14 15:04:55.557 21207-21207/? V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@f9a388e
10-14 15:04:55.557 21207-21207/? V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@db988af
10-14 15:04:55.657 21207-21207/? V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@2bdea7
10-14 15:04:55.657 21207-21207/? V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@caedf54
10-14 15:04:55.684 21207-21223/? D/NetworkSecurityConfig: No Network Security Config specified, using platform default
10-14 15:04:55.749 21207-21225/? I/Adreno: QUALCOMM build                   : dfab96b, I762e720a6a
                                           Build Date                       : 01/31/17
                                           OpenGL ES Shader Compiler Version: XE031.09.00.04
                                           Local Branch                     : 
                                           Remote Branch                    : 
                                           Remote Branch                    : 
                                           Reconstruct Branch               : 
10-14 15:04:55.754 21207-21225/? I/OpenGLRenderer: Initialized EGL, version 1.4
10-14 15:04:55.754 21207-21225/? D/OpenGLRenderer: Swap behavior 1
10-14 15:04:55.786 21207-21207/? W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
10-14 15:04:56.865 21207-21207/com.example.matts.placessample V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance@1b40a67

1 个答案:

答案 0 :(得分:0)

获取新数据后需要通知您的适配器。 最简单的方法是将default提取到字段,然后在mAdapter调用onPostExecute

当然,只有当您从API获得正确答案时,它才会起作用。