android-json生成的listview onClick仅显示最后一项

android-json生成的listview onClick仅显示最后一项,android,json,google-maps,listview,onclick,Android,Json,Google Maps,Listview,Onclick,我有一张地图,上面显示了来自web的json文件中的标记。 我从同一个文件中创建了一个搜索列表视图。 我想做的是在点击任何结果地图后缩放与该结果关联的标记。 但现在,当我点击任何结果时,它只会放大一个标记,这是我的json文件中的最后一项 这是我的密码: public class MapAcWithMarker extends FragmentActivity implements OnMapReadyCallback { static fina

我有一张地图,上面显示了来自web的json文件中的标记。 我从同一个文件中创建了一个搜索列表视图。 我想做的是在点击任何结果地图后缩放与该结果关联的标记。 但现在,当我点击任何结果时,它只会放大一个标记,这是我的json文件中的最后一项

这是我的密码:

    public class MapAcWithMarker extends FragmentActivity
            implements OnMapReadyCallback {

        static final LatLng TEHRAN = new LatLng(35.697291, 51.392378);
        private GoogleMap mMap;
        public ArrayList<Locations> locationsList;
        public ListView listView;
        private View parentView;
        public DataAdapter adapter;
        ArrayList<Locations> arrayListTemp=new ArrayList<>();
        EditText inputSearch;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main_recyc);
            // Obtain the SupportMapFragment and get notified when the map is ready to be used.
            final SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.map);
            mapFragment.getMapAsync(this);
            //  AsyncTaskGetMarker asyncTaskGetMareker= new AsyncTaskGetMarker();
            new AsyncTaskGetMarker().execute();

            locationsList = new ArrayList<>();
            parentView = findViewById(R.id.parentLayout);
            inputSearch = (EditText) findViewById(R.id.inputSearch);
            listView = (ListView) findViewById(R.id.listView);
            listView.setVisibility(View.INVISIBLE);


            inputSearch.setOnKeyListener(new View.OnKeyListener() {
                @Override
                public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
                    if(keyCode== KeyEvent.KEYCODE_DEL){
                        listView.setVisibility(View.GONE);
                    }


                    return true;
                }
            });

            inputSearch.addTextChangedListener(new TextWatcher() {

                @Override
                public void onTextChanged(CharSequence cs, int arg1, int arg2, int count) {

                    listView.setVisibility(View.VISIBLE);

                    if(count==0){
                        listView.setVisibility(View.INVISIBLE);

                    }
                    String searchString= inputSearch.getText()
                            .toString().toLowerCase(Locale.getDefault());
                    int realText= searchString.length();
                    arrayListTemp.clear();
                    for (int i =0 ; i <locationsList.size(); i++){
                        try {
                            String pname= locationsList.get(i).getPname()
                                    .toString();

                            String bicycleno= locationsList.get(i).getBicycleno()
                                    .toString();

                            if(realText<=pname.length() && realText<= bicycleno.length())

                                if (searchString.equalsIgnoreCase(pname.substring(0,
                                        realText)) ||
                                        searchString.equalsIgnoreCase(bicycleno.substring(0, realText))

                                        ) {

                                    arrayListTemp.add(locationsList.get(i));

                                } else {
                                    adapter.notifyDataSetChanged();
                                }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
 Log.d("@w2w2w2w","arrayListTemp size is "+arrayListTemp.size());
  adapter = new DataAdapter(MapAcWithMarker.this, arrayListTemp);
  listView.setAdapter(adapter);
                }

                @Override
                public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                                              int arg3) {
                }



                @Override
                public void afterTextChanged(Editable arg0) {


                }
            });
            RequestInterface api = JsonClient.getApiService();

            /**
             * Calling JSON
             */
            Call<StopList> call = api.getJSON();

            /**
             * Enqueue Callback will be call when get response...
             */
            call.enqueue(new Callback<StopList>() {
                @Override
                public void onResponse(Call<StopList> call, Response<StopList> response) {
                    //Dismiss Dialog
                    //  dialog.dismiss();

                    if (response.isSuccessful()) {
                        /**
                         * Got Successfully
                         */
                        locationsList = response.body().getLocations();

                        /**
                         * Binding that List to Adapter
                         */
                        adapter = new DataAdapter(MapAcWithMarker.this,
                                locationsList);
                        listView.setAdapter(adapter);

                    } else {
                        Toast.makeText(getApplicationContext(), "wrong", Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onFailure(Call<StopList> call, Throwable t) {
                    Toast.makeText(getApplicationContext(), "wrong", Toast.LENGTH_SHORT).show();
                }
            });

        }




        @Override
        public void onMapReady(GoogleMap googleMap) {
            mMap = googleMap;
            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(TEHRAN, 10));

            new AsyncTaskGetMarker().execute();
        }




        class AsyncTaskGetMarker extends
                AsyncTask<String, String, JSONArray> {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
            }

            @Override
            protected JSONArray doInBackground(String... params) {

                String json = null;
                JSONArray jsonarray = null;
                HttpURLConnection conn = null;
                BufferedReader reader = null;
                try {

                    URL url = new URL("https://api.myjson.com/bins/1879ab.json");
                    conn = (HttpsURLConnection) url.openConnection();
                    conn.connect();
                    InputStream in = new BufferedInputStream(conn.getInputStream());
                    reader = new BufferedReader
                            (new InputStreamReader(in));

                    StringBuilder builder = new StringBuilder();
                    String line = null;
                    while((line = reader.readLine()) != null) {
                        builder.append(line);
                    }
                    reader.close();
                    String response = builder.toString();
                    JSONObject jsonObject = new JSONObject(response);
                    jsonarray = jsonObject.getJSONArray("stops");
                    // jsonarray = new JSONArray(response);

                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                return jsonarray;
            }


           protected void onPostExecute(final JSONArray jsonarray) {
            try {
                final SparseArray<LatLng> positions =
                        new SparseArray<>();
                mMap.clear();
                for (int i = 0; i < jsonarray.length(); i++) {
                    JSONObject obj = jsonarray.getJSONObject(i);

                    String name = obj.getString("name");
                    String pname = obj.getString("pname");
                    String bicycleno = obj.getString("bicycleno");

                    Double lat = obj.getDouble("lat");
                    Double lang = obj.getDouble("lang");
                    final LatLng position = new LatLng(lat, lang);

                    String title = "name: " + name;
                    mMap.addMarker(new MarkerOptions()
                            .position(position).title(title));

                    positions.put(i, position);

}
                    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                            if (positions.get(position) != null)
                                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(positions.get(position), 15));

                        }
                    });


            } catch (JSONException e) {
                e.printStackTrace();
            }
            }



        }

    }
公共类MapAcWithMarker扩展了碎片活动
在MapreadyCallback上实现{
静态最终车床=新车床(35.697291,51.392378);
私有谷歌地图;
公共阵列列表位置列表;
公共列表视图列表视图;
私有视图parentView;
公共数据适配器;
ArrayList arrayListTemp=新的ArrayList();
编辑文本输入搜索;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u main\u recyc);
//获取SupportMapFragment,并在地图准备好使用时收到通知。
最终SupportMapFragment mapFragment=(SupportMapFragment)getSupportFragmentManager()
.findFragmentById(R.id.map);
getMapAsync(这个);
//AsyncTaskGetMarker asyncTaskGetMareker=新建AsyncTaskGetMarker();
新建AsyncTaskGetMarker().execute();
locationsList=新的ArrayList();
parentView=findviewbyd(R.id.parentLayout);
inputSearch=(EditText)findViewById(R.id.inputSearch);
listView=(listView)findViewById(R.id.listView);
setVisibility(View.INVISIBLE);
inputSearch.setOnKeyListener(新视图.OnKeyListener(){
@凌驾
公共布尔onKey(视图、int-keyCode、KeyEvent-KeyEvent){
if(keyCode==KeyEvent.keyCode_DEL){
setVisibility(View.GONE);
}
返回true;
}
});
inputSearch.addTextChangedListener(新的TextWatcher(){
@凌驾
public void onTextChanged(字符序列cs、int arg1、int arg2、int count){
setVisibility(View.VISIBLE);
如果(计数=0){
setVisibility(View.INVISIBLE);
}
String searchString=inputSearch.getText()
.toString().toLowerCase(Locale.getDefault());
int realText=searchString.length();
arrayListTemp.clear();

对于(int i=0;i内部
onPostExecute
您有:

position = new LatLng(lat, lang);
String title = "name: " + name;

mMap.addMarker(new MarkerOptions()
                        .position(position).title(title));
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(position,15));
                    }
                });
编辑:还有这些

lat = obj.getDouble("lat");
lang = obj.getDouble("lang");
仅在
for
内部
onPostExecute

Double lat = obj.getDouble("lat");
Double lang = obj.getDouble("lang");
您应该在
MapAcWithMarker
类(顶部)中删除这些声明

下一次编辑:

postExecute方法的完整代码

protected void onPostExecute(final JSONArray jsonarray) {
    try{
        final SparseArray<LatLng> positions = new SparseArray<>();
        mMap.clear();
        for (int i = 0; i < jsonarray.length(); i++) {
            JSONObject obj = jsonarray.getJSONObject(i);

            String name = obj.getString("name");
            String pname = obj.getString("pname");
            String bicycleno = obj.getString("bicycleno");

            Double lat = obj.getDouble("lat");
            Double lang = obj.getDouble("lang");

            final LatLng position = new LatLng(lat, lang);
            String title = "name: " + name;

            mMap.addMarker(new MarkerOptions()
                    .position(position).title(title));

            positions.put(i, position);
        }

        // set once, outside for loop
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                if(positions.get(position)!=null)
                    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(positions.get(position),15));
            }
        });
    } catch (JSONException e) {
        e.printStackTrace();
    }
}
应在
for
循环外部创建一次适配器。在循环之后但在启动之前检查
arrayListTemp
是否有更多项

for (int i =0 ; i <locationsList.size(); i++){
    ...
}

Log.d("@w2w2w2w","arrayListTemp size is "+arrayListTemp.size());
adapter = new DataAdapter(MapAcWithMarker.this, arrayListTemp);
listView.setAdapter(adapter);

for(int i=0;i我将final
LatLng position=new LatLng(lat,lang);
放在onPostExecute方法中。但它不起作用用当前代码编辑您的问题,我们将看到下一步:)
lat=obj.getDouble(“lat”);
lang=obj.getDouble(“lang”);
仍然是全局声明的,最后一个值存储在本地创建的所有不同的
LatLng位置中。两行都应该有
前缀,只有“local”我删除了全局值,并在方法中声明了
。查看我上次的编辑,你认为在代码中还有更多的事情要做。。。
protected void onPostExecute(final JSONArray jsonarray) {
    try{
        final SparseArray<LatLng> positions = new SparseArray<>();
        mMap.clear();
        for (int i = 0; i < jsonarray.length(); i++) {
            JSONObject obj = jsonarray.getJSONObject(i);

            String name = obj.getString("name");
            String pname = obj.getString("pname");
            String bicycleno = obj.getString("bicycleno");

            Double lat = obj.getDouble("lat");
            Double lang = obj.getDouble("lang");

            final LatLng position = new LatLng(lat, lang);
            String title = "name: " + name;

            mMap.addMarker(new MarkerOptions()
                    .position(position).title(title));

            positions.put(i, position);
        }

        // set once, outside for loop
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                if(positions.get(position)!=null)
                    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(positions.get(position),15));
            }
        });
    } catch (JSONException e) {
        e.printStackTrace();
    }
}
for (int i =0 ; i <locationsList.size(); i++){
    ...
    adapter = new DataAdapter(MapAcWithMarker.this, arrayListTemp);
    listView.setAdapter(adapter);
    ...
}
for (int i =0 ; i <locationsList.size(); i++){
    ...
}

Log.d("@w2w2w2w","arrayListTemp size is "+arrayListTemp.size());
adapter = new DataAdapter(MapAcWithMarker.this, arrayListTemp);
listView.setAdapter(adapter);