user3552460
user3552460

Reputation: 27

JSONArray,JsonObjectRequest and Google Place API

I followed this tutorial to create Android application which populates an AutoCompleteTextView with Google Places Autocomplete api, but it's just not working. It doesn't show any Exception or crash anything. I noticed that it doesn't get into the For-loop (where i wrote //--???----) but i can't figure out why.

Update: i try to print the response object and it says to me:

{"error_message":"This API project is not authorized to use this API. Please ensure this API is activated in the Google Developers Console: https:\/\/console.developers.google.com\/apis\/api\/places_backend?project=_","predictions":[],"status":"REQUEST_DENIED"}

This is the code:

LookingForActivity.java:

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;

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

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.TextView;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;

/**
 * The Looking-for-a-deliver activity
 */
public class LookingForActivity extends AppCompatActivity {
    String url;
    private static final String TAG_RESULT = "predictions";
    JSONObject json;

    AutoCompleteTextView auto_tv;
    ArrayList<String> names;
    ArrayAdapter<String> adapter;
    String browserKey = "AIzaSyBeUg81xPA5e8XUqjoAHcoEPLe3bpYSprg";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_looking_for);
        auto_tv = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
        auto_tv.setThreshold(0);

        names = new ArrayList<String>();

        auto_tv.addTextChangedListener(new TextWatcher() {

            public void afterTextChanged(Editable s) {

            }

            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {

                if (s.toString().length() <= 3) {
                    names = new ArrayList<String>();
                    updateList(s.toString());
                }

            }
        });

    }

    public void updateList(String place) {
        String input = "";

        try {
            input = "input=" + URLEncoder.encode(place, "utf-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }

        String output = "json";
        String parameter = input + "&types=geocode&sensor=true&key="
                + browserKey;

        url = "https://maps.googleapis.com/maps/api/place/autocomplete/"
                + output + "?" + parameter;

        JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET, url,
                null, new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {

                try {

                    JSONArray ja = response.getJSONArray(TAG_RESULT);

                    for (int i = 0; i < ja.length(); i++) {
                        //--???----
                        JSONObject c = ja.getJSONObject(i);
                        String description = c.getString("description");
                        Log.d("description", description);
                        names.add(description);
                    }

                    adapter = new ArrayAdapter<String>(
                            getApplicationContext(),
                            android.R.layout.simple_list_item_1, names) {
                        @Override
                        public View getView(int position,
                                            View convertView, ViewGroup parent) {
                            View view = super.getView(position,
                                    convertView, parent);
                            TextView text = (TextView) view
                                    .findViewById(android.R.id.text1);
                            text.setTextColor(Color.BLACK);
                            return view;
                        }
                    };
                    auto_tv.setAdapter(adapter);
                    adapter.notifyDataSetChanged();
                } catch (Exception e) {
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }
        });
        MyApplication.getInstance().addToReqQueue(jsonObjReq, "jreq");
    }

}

MyApplication.java:

import android.app.Application;
import android.text.TextUtils;
import android.util.Log;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;



public class MyApplication extends Application{
    private RequestQueue mRequestQueue;
    private static MyApplication mInstance;
    public static final String TAG = MyApplication.class
            .getSimpleName();
    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
    }
    public static synchronized MyApplication getInstance() {
        return mInstance;
    }
    public RequestQueue getReqQueue() {
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }

        return mRequestQueue;
    }
    public <T> void addToReqQueue(Request<T> req, String tag) {
        req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
        getReqQueue().add(req);
    }
    public <T> void addToReqQueue(Request<T> req) {
        req.setTag(TAG);
        getReqQueue().add(req);
    }
    public void cancelPendingReq(Object tag) {
        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(tag);
        }
    }
}

Upvotes: 0

Views: 393

Answers (2)

SripadRaj
SripadRaj

Reputation: 1735

The response of google says that, the api you're calling is not authorized for your api key. Please check if the required api has been enabled in your google developer console. If not please enable the required API. In your case, enable the Places API. Happy coding. :)

Upvotes: 1

Harshal Pathak
Harshal Pathak

Reputation: 787

Please ensure that you have added android:name="<your package name>.MyApplication" this line in application tag of manifest file

Upvotes: 0

Related Questions