{"id":1828,"date":"2022-08-30T15:19:47","date_gmt":"2022-08-30T15:19:47","guid":{"rendered":"https:\/\/unknownerror.org\/index.php\/2013\/12\/02\/google-distance-matrix-with-autocomplete-on-android-collection-of-common-programming-errors\/"},"modified":"2022-08-30T15:19:47","modified_gmt":"2022-08-30T15:19:47","slug":"google-distance-matrix-with-autocomplete-on-android-collection-of-common-programming-errors","status":"publish","type":"post","link":"https:\/\/unknownerror.org\/index.php\/2022\/08\/30\/google-distance-matrix-with-autocomplete-on-android-collection-of-common-programming-errors\/","title":{"rendered":"google distance matrix with autocomplete on android-Collection of common programming errors"},"content":{"rendered":"<p>I am trying to do what the header is saying, which is to create an app with google distance matrix with autocomplete on android. So far, with my research and studying on the books myself, it is very difficult to come up with the code and I finally reach out here. So far I have gone to<\/p>\n<p>https:\/\/developers.google.com\/maps\/documentation\/distancematrix\/#Introduction<\/p>\n<p>and google directions document<\/p>\n<p>http:\/\/www.claytical.com\/blog\/android-dynamic-autocompletion-using-google-places-api http:\/\/www.stackoverflow.com\/questions\/9142885\/geocoder-autocomplete-in-android http:\/\/www.stackoverflow.com\/questions\/6456090\/android-google-map-finding-distance\/6456161#6456161<\/p>\n<p>All these links have not really helped me understand it and I do understand the concept of Requesting to the API address and it returning the JSON and I have to &#8220;Parse&#8221; the JSON and extract the necessary information, which is the distance in my case. but what I do not get is how I can create an autocomplete that has suggestion from the google maps distance matrix and also how I can send the origin and destination accordingly. It is really frustrating and this is what I have from the Claytical.com.<\/p>\n<p>Here&#8217;s the main.java<\/p>\n<pre><code>package com.example.autocomplete;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.net.URL;\nimport java.net.URLConnection;\nimport java.net.URLEncoder;\nimport java.util.ArrayList;\n\nimport org.json.JSONArray;\nimport org.json.JSONException;\nimport org.json.JSONObject;\n\nimport android.app.Activity;\nimport android.content.Context;\nimport android.os.AsyncTask;\nimport android.os.Bundle;\nimport android.text.Editable;\nimport android.text.TextWatcher;\nimport android.util.Log;\nimport android.widget.ArrayAdapter;\nimport android.widget.AutoCompleteTextView;\n\npublic class Main extends Activity {\n    \/** Called when the activity is first created. *\/\npublic ArrayAdapter adapter;\npublic AutoCompleteTextView textview;\npublic Object s;\n\nclass GetPlaces extends AsyncTask\n{\npublic ArrayAdapter adapter;\npublic AutoCompleteTextView textview;\nObject s;\n\n\n@Override\n           \/\/ three dots is java for an array of strings\nprotected ArrayList doInBackground(String... args)\n{\n\nLog.d(\"gottaGo\", \"doInBackground\");\n\nArrayList predictionsArr = new ArrayList();\n\ntry\n{\n\n\n\n        URL googlePlaces = new URL(\n        \/\/ URLEncoder.encode(url,\"UTF-8\");\n                \"https:\/\/maps.googleapis.com\/maps\/api\/place\/autocomplete\/json?input=\"+ URLEncoder.encode(s.toString(), \"UTF-8\") +\"&amp;types=geocode&amp;language=en&amp;sensor=true&amp;key=\");\n        URLConnection tc = googlePlaces.openConnection();\n        BufferedReader in = new BufferedReader(new InputStreamReader(\n                tc.getInputStream()));\n\n        String line;\n        StringBuffer sb = new StringBuffer();\n                        \/\/take Google's legible JSON and turn it into one big string.\n        while ((line = in.readLine()) != null) {\n        sb.append(line);\n        }\n                        \/\/turn that string into a JSON object\n        JSONObject predictions = new JSONObject(sb.toString()); \n                       \/\/now get the JSON array that's inside that object            \n        JSONArray ja = new JSONArray(predictions.getString(\"predictions\"));\n\n            for (int i = 0; i &lt; ja.length(); i++) {\n                JSONObject jo = (JSONObject) ja.get(i);\n                                \/\/add each entry to our array\n                predictionsArr.add(jo.getString(\"description\"));\n            }\n} catch (IOException e)\n{\n\nLog.e(\"YourApp\", \"GetPlaces : doInBackground\", e);\n\n} catch (JSONException e)\n{\n\nLog.e(\"YourApp\", \"GetPlaces : doInBackground\", e);\n\n}\n\nreturn predictionsArr;\n\n}\n\n\/\/then our post\n\n@Override\nprotected void onPostExecute(ArrayList result)\n{\n\nLog.d(\"YourApp\", \"onPostExecute : \" + result.size());\n\/\/update the adapter\nArrayAdapter adapter = new ArrayAdapter(getBaseContext(),                 R.layout.item_list);\nadapter.setNotifyOnChange(true);\n\n\/\/attach the adapter to textview\ntextview.setAdapter(adapter);\n\nfor (String string : result)\n{\n\nLog.d(\"YourApp\", \"onPostExecute : result = \" + string);\nadapter.add(string);\nadapter.notifyDataSetChanged();\n\n}\n\nLog.d(\"YourApp\", \"onPostExecute : autoCompleteAdapter\" + adapter.getCount());\n\n}\n\nprivate Context getBaseContext() {\n\/\/ TODO Auto-generated method stub\nreturn null;\n}\n\n}\n\n@Override\npublic void onCreate(Bundle savedInstanceState) {\n    super.onCreate(savedInstanceState);\n    setContentView(R.layout.main);\n    final ArrayAdapter adapter = new ArrayAdapter(this,R.layout.item_list);\n    final AutoCompleteTextView textView = (AutoCompleteTextView)\n            findViewById(R.id.autoCompleteTextView1);\n    adapter.setNotifyOnChange(true);\n    textView.setAdapter(adapter);\n     textView.addTextChangedListener(new TextWatcher() {\n\npublic void onTextChanged(CharSequence s, int start, int before, int count) {\nif (count%3 == 1) {\nadapter.clear();\n            GetPlaces task = new GetPlaces();\n                    \/\/now pass the argument in the textview to the task\n                            task.execute(textView.getText().toString());\n    }\n}\n\npublic void beforeTextChanged(CharSequence s, int start, int count,\nint after) {\n\/\/ TODO Auto-generated method stub\n\n}\n\npublic void afterTextChanged(Editable s) {\n\n}\n});\n\n\n\n\n\n\n}\n}\n<\/code><\/pre>\n<p>and my main.xml<\/p>\n<pre><code>\n\n\n\n    \n\n<\/code><\/pre>\n<p>Lastly, here&#8217;s LOGCAT as requested.<\/p>\n<pre><code>05-14 17:41:38.163: E\/Trace(1390): error opening trace file: No such file or directory (2)\n05-14 17:41:39.323: D\/gralloc_goldfish(1390): Emulator without GPU emulation detected.\n05-14 17:41:45.284: D\/gottaGo(1390): doInBackground\n05-14 17:41:45.296: W\/dalvikvm(1390): threadid=11: thread exiting with uncaught exception (group=0x40a13300)\n05-14 17:41:45.314: E\/AndroidRuntime(1390): FATAL EXCEPTION: AsyncTask #1\n05-14 17:41:45.314: E\/AndroidRuntime(1390): java.lang.RuntimeException: An error occured while executing doInBackground()\n05-14 17:41:45.314: E\/AndroidRuntime(1390):     at android.os.AsyncTask$3.done(AsyncTask.java:299)\n05-14 17:41:45.314: E\/AndroidRuntime(1390):     at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)\n05-14 17:41:45.314: E\/AndroidRuntime(1390):     at java.util.concurrent.FutureTask.setException(FutureTask.java:124)\n05-14 17:41:45.314: E\/AndroidRuntime(1390):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)\n05-14 17:41:45.314: E\/AndroidRuntime(1390):     at java.util.concurrent.FutureTask.run(FutureTask.java:137)\n05-14 17:41:45.314: E\/AndroidRuntime(1390):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)\n05-14 17:41:45.314: E\/AndroidRuntime(1390):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)\n05-14 17:41:45.314: E\/AndroidRuntime(1390):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)\n05-14 17:41:45.314: E\/AndroidRuntime(1390):     at java.lang.Thread.run(Thread.java:856)\n05-14 17:41:45.314: E\/AndroidRuntime(1390): Caused by: java.lang.NullPointerException\n05-14 17:41:45.314: E\/AndroidRuntime(1390):     at com.example.autocomplete.Main$GetPlaces.doInBackground(Main.java:54)\n05-14 17:41:45.314: E\/AndroidRuntime(1390):     at com.example.autocomplete.Main$GetPlaces.doInBackground(Main.java:1)\n05-14 17:41:45.314: E\/AndroidRuntime(1390):     at android.os.AsyncTask$2.call(AsyncTask.java:287)\n05-14 17:41:45.314: E\/AndroidRuntime(1390):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)\n05-14 17:41:45.314: E\/AndroidRuntime(1390):     ... 5 more\n05-14 17:41:47.584: I\/Choreographer(1390): Skipped 31 frames!  The application may be doing too much work on its main thread.\n05-14 17:41:47.904: I\/Process(1390): Sending signal. PID: 1390 SIG: 9\n<\/code><\/pre>\n<p>It launches just fine and it brings up the auto complete textview but as soon as I type a letter, it crashes. Thanks for reading this far and Thank you in advance for your help!<\/p>\n<ol>\n<li>\n<p>OK first thing is that your URL is malformed:<\/p>\n<pre><code>https:\/\/maps.googleapis.com\/maps\/api\/place\/autocomplete\/json?input=\" + URLEncoder.encode(s.toString(), \"UTF-8\") + \"&amp;types=geocode&amp;language=en&amp;sensor=true&amp;key=\n<\/code><\/pre>\n<p>You need to replace with your API key for it to work. Next thing is how you form your JSON array. You need to replace<\/p>\n<pre><code>JSONArray ja = new JSONArray(predictions.getString(\"predictions\"));\n<\/code><\/pre>\n<p>with<\/p>\n<pre><code>JSONArray ja = new JSONArray(predictions.getJSONArray(\"predictions\"));\n<\/code><\/pre>\n<p>Next in your loop, replace<\/p>\n<pre><code>JSONObject jo = (JSONObject) ja.get(i);\n<\/code><\/pre>\n<p>with<\/p>\n<pre><code>JSONObject jo = ja.getJSONObject(i);\n<\/code><\/pre>\n<p>Try this and let me know how it goes.<\/p>\n<\/li>\n<\/ol>\n<p id=\"rop\"><small>Originally posted 2013-12-02 20:56:21. <\/small><\/p>","protected":false},"excerpt":{"rendered":"<p>I am trying to do what the header is saying, which is to create an app with google distance matrix with autocomplete on android. So far, with my research and studying on the books myself, it is very difficult to come up with the code and I finally reach out here. So far I have [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-1828","post","type-post","status-publish","format-standard","hentry","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/1828","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/comments?post=1828"}],"version-history":[{"count":0,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/1828\/revisions"}],"wp:attachment":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/media?parent=1828"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/categories?post=1828"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/tags?post=1828"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}