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 中提供自动自动建议吗? 的相关文章

随机推荐

  • 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