Android:在 Android Place Api 中提供自动自动建议吗?

2024-01-23

我对 Android Google 地图非常陌生,我编写了以下程序,用于在 Android 中显示自动建议,当我在“自动完成”文本框中键入文本时,它将输入到 url,但输出未显示在程序中.请看一次并让我知道我在哪里犯了错误。

   ExampleApp.java
package com.example.exampleapp;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;

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

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater.Filter;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;

import android.widget.Filterable;
import android.widget.Toast;

public class ExampleApp extends Activity implements OnItemClickListener{

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        AutoCompleteTextView autoCompView = (AutoCompleteTextView) findViewById(R.id.autocomplete);
        autoCompView.setAdapter(new PlacesAutoCompleteAdapter(this, R.layout.list_item));
    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        // TODO Auto-generated method stub
        String str = (String) arg0.getItemAtPosition(arg2);
        Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
    }


}
class PlacesAutoCompleteAdapter extends ArrayAdapter<String> implements Filterable {
    private ArrayList<String> resultList;

    public PlacesAutoCompleteAdapter(Context context, int textViewResourceId) {
        super(context, textViewResourceId);
    }
    private static final String PLACES_API_BASE = "https://maps.googleapis.com/maps/api/place";
    private static final String TYPE_AUTOCOMPLETE = "/autocomplete";
    private static final String OUT_JSON = "/json";

    private static final String API_KEY = "";
    @Override
    public int getCount() {
        return resultList.size();
    }

    @Override
    public String getItem(int index) {
        return resultList.get(index);
    }

    @Override
    public android.widget.Filter getFilter() {
        Filter filter = new Filter() {
            protected FilterResults performFiltering(CharSequence constraint) {
                FilterResults filterResults = new FilterResults();
                if (constraint != null) {
                    // Retrieve the autocomplete results.
                    resultList = autocomplete(constraint.toString());

                    // Assign the data to the FilterResults
                 //   filterResults.values = resultList;
                  //  filterResults.count = resultList.size();
                }
                return filterResults;
            }

            private ArrayList<String> autocomplete(String input) {
                ArrayList<String> resultList = null;

                HttpURLConnection conn = null;
                StringBuilder jsonResults = new StringBuilder();
                try {
                    StringBuilder sb = new StringBuilder(PLACES_API_BASE + TYPE_AUTOCOMPLETE + OUT_JSON);
                    sb.append("?sensor=false&key=" + API_KEY);
                    sb.append("&components=country:uk");
                    sb.append("&input=" + URLEncoder.encode(input, "utf8"));

                    URL url = new URL(sb.toString());
                    conn = (HttpURLConnection) url.openConnection();
                    InputStreamReader in = new InputStreamReader(conn.getInputStream());

                    // Load the results into a StringBuilder
                    int read;
                    char[] buff = new char[1024];
                    while ((read = in.read(buff)) != -1) {
                        jsonResults.append(buff, 0, read);
                    }
                } catch (MalformedURLException e) {
                   // Log.e(LOG_TAG, "Error processing Places API URL", e);
                    return resultList;
                } catch (IOException e) {
                    //Log.e(LOG_TAG, "Error connecting to Places API", e);
                    return resultList;
                } finally {
                    if (conn != null) {
                        conn.disconnect();
                    }
                }

                try {
                    // Create a JSON object hierarchy from the results
                    JSONObject jsonObj = new JSONObject(jsonResults.toString());
                    JSONArray predsJsonArray = jsonObj.getJSONArray("predictions");

                    // Extract the Place descriptions from the results
                    resultList = new ArrayList<String>(predsJsonArray.length());
                    for (int i = 0; i < predsJsonArray.length(); i++) {
                        resultList.add(predsJsonArray.getJSONObject(i).getString("description"));
                    }
                } catch (JSONException e) {
                   // Log.e(LOG_TAG, "Cannot process JSON results", e);
                }

                return resultList;
            }
            protected void publishResults(CharSequence constraint, FilterResults results) {
                if (results != null) {
                    notifyDataSetChanged();
                }
                else {
                    notifyDataSetInvalidated();
                }
            }

            @Override
            public boolean onLoadClass(Class arg0) {
                // TODO Auto-generated method stub
                return false;
            }};
        return (android.widget.Filter) filter;
    }
}

FilterResults.java

package com.example.exampleapp;

import java.util.ArrayList;

public class FilterResults {

    protected ArrayList<String> values;
    protected int count;

}


i write the above code but the application closed .please see once and let me know where i am doing mistake in the above code ?
Thanks in Advance..........

这是我遇到类似问题时使用的代码片段。我给你一个建议,不要将整个代码放在单个 java 文件中。为您在代码中使用的每个不同任务创建单独的方法/类。它将帮助您更轻松地追踪它。

这是我的 PlacesAutoCompleteAdapter.java 文件。

package com.inukshk.adapter;

import java.util.ArrayList;

import android.content.Context;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.Filterable;

import com.inukshk.CreateInukshk.CreateInukshk;

public class PlacesAutoCompleteAdapter extends ArrayAdapter<String> implements
        Filterable {
    private ArrayList<String> resultList;

    public PlacesAutoCompleteAdapter(Context context, int textViewResourceId) {
        super(context, textViewResourceId);
    }

    @Override
    public int getCount() {
        return resultList.size();
    }

    @Override
    public String getItem(int index) {
        return resultList.get(index);
    }

    @Override
    public Filter getFilter() {
        Filter filter = new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                FilterResults filterResults = new FilterResults();
                if (constraint != null) {
                    // Retrieve the autocomplete results.

                    resultList = CreateInukshk.autocomplete(constraint
                            .toString());

                    // Assign the data to the FilterResults
                    filterResults.values = resultList;
                    filterResults.count = resultList.size();
                }
                return filterResults;
            }

            @Override
            protected void publishResults(CharSequence constraint,
                    FilterResults results) {
                if (results != null && results.count > 0) {
                    notifyDataSetChanged();
                } else {
                    notifyDataSetInvalidated();
                }
            }
        };
        return filter;
    }
}

这是您必须在活动的 OnCreate() 内执行的操作。

autoCompView = (AutoCompleteTextView) findViewById(R.id.editloc);
        autoCompView.setAdapter(new PlacesAutoCompleteAdapter(this,
                R.layout.list_item));

这是我在应用程序中使用的静态字符串。

private static final String PLACES_API_BASE = "https://maps.googleapis.com/maps/api/place";
    private static final String TYPE_AUTOCOMPLETE = "/autocomplete";
    private static final String OUT_JSON = "/json";
    private static final String API_KEY = "YOUR API KEY";

最后,这是您将在适配器中使用的方法。

public static ArrayList<String> autocomplete(String input) {

        ArrayList<String> resultList = null;

        HttpURLConnection conn = null;
        StringBuilder jsonResults = new StringBuilder();
        try {
            StringBuilder sb = new StringBuilder(PLACES_API_BASE
                    + TYPE_AUTOCOMPLETE + OUT_JSON);
            sb.append("?sensor=false&key=" + API_KEY);
            // sb.append("&components=country:uk");
            sb.append("&input=" + URLEncoder.encode(input, "utf8"));

            URL url = new URL(sb.toString());
            conn = (HttpURLConnection) url.openConnection();
            InputStreamReader in = new InputStreamReader(conn.getInputStream());

            // Load the results into a StringBuilder
            int read;
            char[] buff = new char[1024];
            while ((read = in.read(buff)) != -1) {
                jsonResults.append(buff, 0, read);
            }
        } catch (MalformedURLException e) {
            Log.e(TAG, "Error processing Places API URL", e);
            return resultList;
        } catch (IOException e) {
            Log.e(TAG, "Error connecting to Places API", e);
            return resultList;
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }

        try {
            // Create a JSON object hierarchy from the results
            JSONObject jsonObj = new JSONObject(jsonResults.toString());
            JSONArray predsJsonArray = jsonObj.getJSONArray("predictions");

            // Extract the Place descriptions from the results
            resultList = new ArrayList<String>(predsJsonArray.length());
            for (int i = 0; i < predsJsonArray.length(); i++) {
                resultList.add(predsJsonArray.getJSONObject(i).getString(
                        "description"));
            }

        } catch (JSONException e) {
            Log.e(TAG, "Cannot process JSON results", e);
        }

        return resultList;
    }

EDITED :

我猜您已指定 list_item.xml 如下。

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content" android:layout_height="wrap_content" />

试试看。希望它会对您有所帮助。

UPDATE :

You have to manually attach the debugger while the emulator says "Waiting for debugger to attach". In Netbean's menu bar, click "Debug", then "Attach Debugger...". You have to select your package from the "Process" drop down list, and then click "Attach". That should do it.
This works in Netbeans 7 anyway.

或者你也可以尝试下面的东西。

You have two choices: connect a debugger, or kill the process.

Looking at your logcat, you have at least two different desktop applications that are trying to connect to each application process, which is where the "Ignoring second debugger" messages are coming from.

This would happen if you were, say, running Eclipse with the ADT plugin, and the stand-alone DDMS at the same time. I don't know what you're running or what the netbeans plugin does, but I would start by figuring out if you have two different things fighting for control.

EDITED: HOW TO GET TEXT OF AutoCompleteTextView

只需编写此代码片段即可。

autoCompView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                    long arg3) {
                // TODO Auto-generated method stub
                YOURTEXT = autoCompView.getText().toString();
                //new AsyncGetAutoPlace().execute(autoCompView.getText()
                //      .toString().trim());
            }
        });
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Android:在 Android Place Api 中提供自动自动建议吗? 的相关文章

  • Sqlite数据库生命周期?关闭应用程序后它会被删除吗?

    我正在遵循一个简单的教程 该教程创建一个从 SQLiteOpenHelper 扩展的类 并创建一个包含一个表和 5 行的数据库 好的 但我需要更多地了解 android Sqlite 数据库 例如 如果应用程序关闭或手机关机会发生什么 数据
  • Android - 从资产中解析巨大(超大)JSON 文件的最佳方法

    我正在尝试从资产文件夹中解析一些巨大的 JSON 文件 我如何加载并添加到 RecyclerView 我想知道解析这种大文件 大约 6MB 的最佳方法是什么 以及您是否知道可以帮助我处理此文件的良好 API 我建议您使用GSON lib h
  • 无法获取log.d或输出Robolectrict + gradle

    有没有人能够将 System out 或 Log d 跟踪从 robolectric 测试输出到 gradle 控制台 我在用Robolectric Gradle 测试插件 https github com robolectric robo
  • 谷歌坐标认证

    当我尝试连接到 Google 坐标时 总是出现异常GoogleAuthException 我拥有 Google 地图协调中心许可证 我确实使用我的包应用程序名称和 SHA1 在 google 控制台中创建了我的客户端 ID 我将权限添加到清
  • 如何在android中获取Camera2 API的当前曝光

    In android hardware Camera旧的 我使用下面的代码获取当前曝光并获取它Camera Camera Parameters param mCamera getParameters currentExposure para
  • 是否可以将数组或对象添加到 Android 上的 SharedPreferences

    我有一个ArrayList具有名称和图标指针的对象 我想将其保存在SharedPreferences 我能怎么做 注意 我不想使用数据库 无论 API 级别如何 请检查SharedPreferences 中的字符串数组和对象数组 http
  • java.lang.NoClassDefFoundError:org.apache.batik.dom.svg.SVGDOMImplementation

    我在链接到我的 Android LibGDX 项目的 Apache Batik 库时遇到了奇怪的问题 但让我们从头开始 在 IntelliJ Idea 中我有一个项目 其中包含三个模块 Main Android 和 Desktop 我强调的
  • 找不到处理意图 com.instagram.share.ADD_TO_STORY 的活动

    在我们的 React Native 应用程序中 我们试图让用户根据视图 组件中的选择直接将特定图像共享到提要或故事 当我们尝试直接使用 com instagram share ADD TO FEED 进行共享时 它以一致的方式完美运行 但是
  • Android 模拟器插件无法初始化后端 EGL 显示

    我在 Cloudbees 上设置了 Jenkins 作业 并且可以在那里成功签出并编译我的 Android 项目 现在我想在 android 模拟器中运行一些 JUnit 测试并添加 Android 模拟器插件 我将 显示模拟器窗口 选项设
  • Android 中 Kotlin 协程的正确使用方式

    我正在尝试使用异步更新适配器内的列表 我可以看到有太多的样板 这是使用 Kotlin 协程的正确方法吗 这个可以进一步优化吗 fun loadListOfMediaInAsync async CommonPool try Long runn
  • 在 java 类和 android 活动之间传输时音频不清晰

    我有一个android活动 它连接到一个java类并以套接字的形式向它发送数据包 该类接收声音数据包并将它们扔到 PC 扬声器 该代码运行良好 但在 PC 扬声器中播放声音时会出现持续的抖动 中断 安卓活动 public class Sen
  • 使用 Android 发送 HTTP Post 请求

    我一直在尝试从 SO 和其他网站上的大量示例中学习 但我无法弄清楚为什么我编写的示例不起作用 我正在构建一个小型概念验证应用程序 它可以识别语音并将其 文本 作为 POST 请求发送到 node js 服务器 我已确认语音识别有效 并且服务
  • 控制Android的前置LED灯

    我试图在用户按下某个按钮时在前面的 LED 上实现 1 秒红色闪烁 但我很难找到有关如何访问和使用前置 LED 的文档 教程甚至代码示例 我的意思是位于 自拍 相机和触摸屏附近的 LED 我已经看到了使用手电筒和相机类 已弃用 的示例 但我
  • 发布android后更改应用内购买项目的价格

    在 Google Play 上发布后 是否可以更改应用内购买商品的价格 我假设该应用程序也已发布 完整的在线文档位于http developer android com http developer android com也http sup
  • 字符串数组文本格式化

    我有这个字符串 String text Address 1 Street nr 45 Address 2 Street nr 67 Address 3 Street nr 56 n Phone number 000000000 稍后将被使用
  • 我的设备突然没有显示在“Android 设备选择器”中

    我正在使用我的三星 Galaxy3 设备来测试过去两个月的应用程序 它运行良好 但从今天早上开始 当我将设备连接到系统时 它突然没有显示在 Android 设备选择器 窗口中 我检查过 USB 调试模式仅在我的设备中处于选中状态 谁能猜出问
  • 在activity_main.xml中注释

    我是安卓新手 据我所知 XML 中的注释与 HTML 中的注释相同 使用 形式 我想在 Android 项目的 Activity main xml 配置文件中写一些注释 但它给了我错误 值得注意的是 我使用的是 Eclipse 但目前 我直
  • 如何在Xamarin中删除ViewTreeObserver?

    假设我需要获取并设置视图的高度 在 Android 中 众所周知 只有在绘制视图之后才能获取视图高度 如果您使用 Java 有很多答案 最著名的方法之一如下 取自这个答案 https stackoverflow com a 24035591
  • 将 Intent 包装在 LabeledIntent 中以用于显示目的

    要求 我的应用程序中有一个 共享 按钮 我需要通过 Facebook 分享 我需要选择是否安装原生 Facebook 应用程序 我们的决定是 如果未安装该应用程序 则将用户发送到 facebook com 进行分享 当前状态 我可以检测何时
  • 强制 Listview 不重复使用视图(复选框)

    我做了一个定制Listview 没有覆盖getView 方法 Listview 中的每个项目都具有以下布局 联系布局 xml

随机推荐

  • hsc2hs:使用 Haskell 改变 C 结构

    我正在尝试编写一个与 C 通信的 Haskell 程序 最终通过 GHC iOS 用于 iOS 我希望它将一个字符串从 C 传递到 Haskell 让 Haskell 处理它 然后通过 hsc2s 将一些数据类型从 Haskell 返回到
  • 如何在 Mahout 0.9 中实现 SlopeOne 推荐器?

    我是 Mahout 新手 正在尝试使用 0 5 版本的 Mahout in Action 早期的例子之一要求使用斜率一推荐器 Mahout 0 9 中还包含此推荐器吗 我查看了文档 但找不到它 也许它已经改名了 感谢您的帮助 Mahout
  • 当表没有行时,将表的可见性设置为 false(在报告服务中)

    如果表没有行 有没有办法将表的可见性设置为 false 我想在 Reporting Services 中隐藏没有行的表 将 NoRows 设置为 在这种情况下是不够的 因为仍然为表格留有空间 并且表格的某些格式仍然可见 我正在使用 Micr
  • 在 Python 中 - 解析响应 xml 并查找特定文本值

    我是 python 新手 在使用 xml 和 python 时遇到特别困难 我遇到的情况是这样的 我正在尝试计算一个单词在 xml 文档中出现的次数 很简单 但是 xml 文档是来自服务器的响应 是否可以在不写入文件的情况下执行此操作 尝试
  • Ansible,将字典合并为一次

    我有这个示例 yaml 文件 haproxy yml rules aa PHP53 url php53 1 aa my example com PHP55 url php55 1 aa my example com PHP56 url ph
  • 根据请求参数有条件地使用中间件express

    我正在尝试根据请求查询参数决定要使用的中间件 在主模块中我有这样的东西 app use function req res if req query something pass req res to middleware a else pa
  • 使用 __getattr__ 和 __setattr__ 功能实现类似字典的对象

    我正在尝试实施一个dict类似对象 可以访问 修改 getattr and setattr 为了方便我的用户使用 该类还实现了一些其他简单的功能 Using 这个答案 https stackoverflow com questions 33
  • 非灵活环境应用程序的自定义运行时?

    我不认为我的 gae python 应用程序具有灵活的环境 因为我多年前创建了它 现在我想尝试创建一个具有不同于 python 的运行时的模块 并使 python 应用程序与新的运行时 自定义运行时或其他运行时一起运行 也许混合 PHP 和
  • 将 IQueryable 类型转换为 Linq to Entities 中的接口

    我的泛型类中有以下方法 This is the class declaration public abstract class BaseService
  • Google Cloud 端点和 JWT

    我有一个基于 Google Cloud Endpoints 的 API 我想使用 JWT Json Web Tokens 进行授权 我可以为每个包含令牌的请求设置授权标头 并且它可以正常工作 我知道 Endpoints 使用此标头进行 Oa
  • MaterialComponents.TextInputLayout.OutlinedBox 它无法正常工作 boxBackgroundColor

    我用的是材料 我将使用 TextInputLayout 的颜色作为背景 但类似于下面的颜色 提示背景未更改 我使用了样式并想进行更改 但没有成功 在布局本身中 我尝试再次应用更改 如何解决这个问题 NOTE 的背景标签用户名图片中没有透明的
  • 访问故事板内的视图

    如何在代码中访问从对象浏览器拖到情节提要中的另一个视图中的视图 例如 我创建了一个 UIView 并将其分配给 ViewController 类 然后我将地图视图拖到该视图中 现在我需要开始在代码中操作该地图视图 我如何访问它 我尝试过 s
  • UWP 模板 10 和服务依赖注入 (MVVM),而非 WPF

    我花了两个多星期的时间搜索 google bing stackoverflow 和 msdn 文档 试图找出如何为我正在开发的移动应用程序进行正确的依赖项注入 需要明确的是 我每天都在网络应用程序中进行 DI 我不需要关于什么 谁以及为什么
  • 使用安全模式=“TransportWithMessageCredential”测试WCF服务wsHttpBinding

    我尝试使用soapUI进行测试 但是在启用安全性时它不支持wsHttpBinding 使用 wsHttpBinding 时 soapUI 确实可以工作 但安全性为零 我们还尝试了 WCF Storm 它确实有效 我们可以加载我们的客户端配置
  • 跨节点项目共享通用打字稿代码

    假设我有以下项目结构 webapps ProjectA SomeClass ts 包 json ProjectB SomeClass ts 包 json Common LoggingClass ts 包 json 公共 LoggingCla
  • 如何在 Visual Studio (2010) 中突出显示 C(而不是 C++)语法?

    我正在和朋友一起用 C 语言做一些小练习 出于习惯 我一直使用较新语言的关键字 例如 bool new 我花了一段时间才意识到这是问题所在 因为 VS 不断将它们突出显示为关键字 即使它们不在 C 中 我确保所有文件都是 c 并将项目属性设
  • C# 中的队列和等待句柄

    我的应用程序中使用以下代码已有多年 但从未发现其中出现问题 while PendingOrders Count gt 0 WaitHandle WaitAny CommandEventArr 1 lock PendingOrders if
  • jquery .click 被多次调用

    我在 jQuery 尝试设置 div 的 click 方法时得到了意想不到的结果 请参见这个jsfiddle http jsfiddle net fkMf9 请务必打开控制台窗口 单击该单词几次并观察控制台输出 click 函数在只应调用一
  • PHP 计数函数与关联数组

    有人可以向我解释一下 count 函数如何处理如下所示的数组吗 我的想法是下面的代码输出 4 因为那里有 4 个元素 a array 1 gt A 1 gt B C 2 gt D echo count a count完全按照您的预期工作 例
  • Android:在 Android Place Api 中提供自动自动建议吗?

    我对 Android Google 地图非常陌生 我编写了以下程序 用于在 Android 中显示自动建议 当我在 自动完成 文本框中键入文本时 它将输入到 url 但输出未显示在程序中 请看一次并让我知道我在哪里犯了错误 ExampleA