Java ArrayAdapter不';我不能留着它';s值

Java ArrayAdapter不';我不能留着它';s值,java,android,collections,android-arrayadapter,Java,Android,Collections,Android Arrayadapter,我遇到了一个问题,我知道问题出在哪里,但我不明白的是为什么它有时有效,有时无效。这就是我想做的 我有一个Android应用程序,它显示一个谷歌地图视图,在这个地图视图的顶部有一个自动完成的文本视图。我从Google(json格式)获得值,我可以在这个自动完成文本视图中显示它们。这种方法一直有效。现在,当我按下从谷歌获得的一个选项时,我想放大到那个位置。这在大多数情况下都有效 因此,当我按下地址Elfde时,我从谷歌得到5个选项/预测。然后我显示这些选项。其中一个选择是比利时的Elfde Lini

我遇到了一个问题,我知道问题出在哪里,但我不明白的是为什么它有时有效,有时无效。这就是我想做的

我有一个Android应用程序,它显示一个谷歌地图视图,在这个地图视图的顶部有一个自动完成的文本视图。我从Google(json格式)获得值,我可以在这个自动完成文本视图中显示它们。这种方法一直有效。现在,当我按下从谷歌获得的一个选项时,我想放大到那个位置。这在大多数情况下都有效

因此,当我按下地址Elfde时,我从谷歌得到5个选项/预测。然后我显示这些选项。其中一个选择是比利时的Elfde Liniestrat。谷歌地图视图将缩放到该位置。如果我键入不莱梅,然后选择德国不莱梅,它将缩放到该位置。但当我输入Peer并选择Peer时,我在ArrayAdapter中得到一个indexOutOfBounds异常

现在代码是:

当我的自动完成文本视图中的文本发生更改时,我使用以下代码:

public void onTextChanged(CharSequence s, int start, int before,
                int count) {
            if (count % 3 == 1){                    
                // Get the places and pass the argument in the TextView to the task.
                GetPlaces task = new GetPlaces();
                task.execute(_txtFindLocation.getText().toString());
            }
        }       
_txtFindLocation.setOnItemClickListener(new OnItemClickListener(){
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            // Hide the keyboard.
            InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(_txtFindLocation.getWindowToken(), 0);

            Log.v("Take a look on variables", "item: " + String.valueOf(arg2) + ", AdapterView: " + arg0.getCount() + ", _strArrayAdapter: " + _strArrayAdapter.getCount());

            // Move to specified location.
            moveToLocation(arg0.getItemAtPosition(arg2).toString());

                    // Clear the adapter, to decrease the size.
            _strArrayAdapter.clear();
        }
    });
单击某个项目时,我使用以下代码:

public void onTextChanged(CharSequence s, int start, int before,
                int count) {
            if (count % 3 == 1){                    
                // Get the places and pass the argument in the TextView to the task.
                GetPlaces task = new GetPlaces();
                task.execute(_txtFindLocation.getText().toString());
            }
        }       
_txtFindLocation.setOnItemClickListener(new OnItemClickListener(){
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            // Hide the keyboard.
            InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(_txtFindLocation.getWindowToken(), 0);

            Log.v("Take a look on variables", "item: " + String.valueOf(arg2) + ", AdapterView: " + arg0.getCount() + ", _strArrayAdapter: " + _strArrayAdapter.getCount());

            // Move to specified location.
            moveToLocation(arg0.getItemAtPosition(arg2).toString());

                    // Clear the adapter, to decrease the size.
            _strArrayAdapter.clear();
        }
    });
\u txtFindLocation.setOnItemClickListener(新的OnItemClickListener(){
公共链接(AdapterView arg0、视图arg1、内部arg2、,
长arg3){
//隐藏键盘。
InputMethodManager InputMethodManager=(InputMethodManager)getSystemService(Context.INPUT\u方法\u服务);
inputMethodManager.hideSoftInputFromWindow(_txtFindLocation.getWindowToken(),0);
Log.v(“查看变量”,“项:“+String.valueOf(arg2)+”,AdapterView:“+arg0.getCount()+”,_strArrayAdapter:”+_strArrayAdapter.getCount());
//移动到指定的位置。
moveToLocation(arg0.getItemAtPosition(arg2.toString());
//清除适配器,以减小尺寸。
_strArrayAdapter.clear();
}
});
这里是indexOutOfBoundsException发生的地方。 对于比利时Elfde LINIESTRAT的输入和选择:arg2=0,arg0.getCount()=5,_StrarrayaAdapter(以arg0作为源链接)=5 对于德国不莱梅的输入和选择:arg2=3,arg0.getCount()=5,_StrarrayaAdapter=5 对于Peer的输入和选择,比利时(抛出错误的地方):arg2=0,arg0.getCount()=0,_StrarrayaAdapter=0

因此,这里是抛出错误的地方。此函数将填充_strArrayAdapter:

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

    @Override
    protected ArrayList<String> doInBackground(String... params) {
        ArrayList<String> myPredictions = new ArrayList<String>();
        Log.d("Search places", "params: " + params[0].toString());
        try{
            URL myURL = new URL("https://maps.googleapis.com/maps/api/place/autocomplete/json?input="
                    + URLEncoder.encode(params[0], "UTF-8")
                    + "&types=geocode&language=en&sensor=true&key=API_KEY");
            URLConnection myURLConnection = myURL.openConnection();         
            BufferedReader myBufferReader = new BufferedReader(new InputStreamReader(myURLConnection.getInputStream()));

            String strLine;
            StringBuffer strBuffer = new StringBuffer();
            // Take Google's legible JSON and turn it into on big String.
            while((strLine = myBufferReader.readLine()) != null){
                strBuffer.append(strLine);
            }

            // Turn String into a JSON Object.
            JSONObject jsonPredictionsObject = new JSONObject(strBuffer.toString());
            // Get a JSON Array that is inside the JSON Object.
            JSONArray jsonPredictionsArray = new JSONArray(jsonPredictionsObject.getString("predictions"));

            for (int i = 0; i < jsonPredictionsArray.length(); i++){
                jsonPredictionsObject = (JSONObject) jsonPredictionsArray.get(i);
                myPredictions.add(jsonPredictionsObject.getString("description"));
            }
        }
        catch (IOException e){
            Log.e("Search places", "GetPlaces: doInBackGround", e);
        }
        catch (JSONException e){
            Log.e("Search places", "GetPlaces: doInBackGround", e);
        }

        return myPredictions;
    }

    protected void onPostExecute(ArrayList<String> result){
        Log.d("YourApp", "onPostExecute: " + result.size());

        // Update the adapter.
        _strArrayAdapter = new ArrayAdapter<String>(getBaseContext(), R.layout.activity_list_item);
        _strArrayAdapter.setNotifyOnChange(true);

        // Attach the adapter to the TextView.
        _txtFindLocation.setAdapter(_strArrayAdapter);

        for (String text : result){
            Log.d("Search places", "onPostExecute: result = " + text);

            _strArrayAdapter.add(text);
        }

            _strArrayAdapter.clear();

        Log.d("Search places", "onPostExecute: autoCompleteAdapter " + _strArrayAdapter.getCount());
    }
私有类GetPlaces扩展异步任务{
@凌驾
受保护的ArrayList doInBackground(字符串…参数){
ArrayList myPredictions=新的ArrayList();
Log.d(“搜索位置”,“参数:+params[0].toString());
试一试{
URL myURL=新URL(“https://maps.googleapis.com/maps/api/place/autocomplete/json?input="
+URLEncoder.encode(参数[0],“UTF-8”)
+“&types=geocode&language=en&sensor=true&key=API_key”);
URLConnection myURLConnection=myURL.openConnection();
BufferedReader myBufferReader=new BufferedReader(new InputStreamReader(myURLConnection.getInputStream());
弦斯特林;
StringBuffer strBuffer=新的StringBuffer();
//以谷歌易读的JSON为例,将其转换为大字符串。
而((strLine=myBufferReader.readLine())!=null){
strBuffer.append(strLine);
}
//将字符串转换为JSON对象。
JSONObject jsonPredictionsObject=新的JSONObject(strBuffer.toString());
//获取JSON对象内部的JSON数组。
JSONArray jsonPredictionsArray=新的JSONArray(jsonPredictionsObject.getString(“预测”);
对于(int i=0;i
对于所有三个测试用例,最后一个Log.d(“搜索位置”、“onPostExecute:autoCompleteAdapter”+_StrarrayaAdapter.getCount())的值为5

因此_strArrayAdapter在所有情况下都会被填充,但在某些情况下,当我选择一个项目时,_strArrayAdapter的值设置为0,因此它不会被填充

为什么会这样

出于善意, 马丁哈克斯


编辑多亏了回复,我重新访问了我的代码(上面),现在它工作得很好。

问题似乎出在您的
onTextChanged
函数中的以下代码片段中。顺便问一句,为什么在
lengthOfModifiedText%3==1时清除数组

if (count % 3 == 1){
                _strArrayAdapter.clear();
当您输入
“Peer”
时,您的数组将被清除(无元素)。
每当您输入长度为
L的文本时,其中L%3==1
,您的
strArrayAdapter
将根据您的代码被清除。

当结果的字符数为x时,您似乎正在清除结果*
protected void onPostExecute(ArrayList<String> result){
    Log.d("YourApp", "onPostExecute: " + result.size());

    // Update the adapter.
    _strArrayAdapter = new ArrayAdapter<String>(getBaseContext(), R.layout.activity_list_item);

    for (String text : result){
        Log.d("Search places", "onPostExecute: result = " + text);

        temp.add(text);
        _strArrayAdapter.add(text);
    }


    // Attach the adapter to the TextView.
    _txtFindLocation.setAdapter(_strArrayAdapter);

    Log.d("Search places", "onPostExecute: autoCompleteAdapter " + _strArrayAdapter.getCount());
}