从服务器检索数据时应用程序变得非常缓慢

时间:2019-07-01 06:35:26

标签: android performance android-asynctask android-volley data-retrieval

我正在使用以下代码使用Volley库从服务器获取数据。如果没有互联网,该应用程序在不检索数据时可以快速,流畅地运行。但是,随着Internet的打开,该应用程序会变得缓慢,因为它会从服务器获取数据并将其显示在ListView中。是因为数据检索吗?请帮我解决这个问题。

以下是使用的代码:

private void  callgetTaskUrlApi() {
    StringRequest stringRequest = new StringRequest(Request.Method.POST, getTaskUrl,
        new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                arrayList.clear();
                try {
                    JSONObject jo = new JSONObject(response);
                    JSONArray ja = jo.getJSONArray("dataObj");
                    int length=ja.length();

                    for(int i=0; i<length; i++){
                        JSONObject temp = ja.getJSONObject(i);
                        nameC= temp.getString("name");
                        checkId=temp.getString("clientEid");
                        clientName=temp.getString("client");
                        candidateFatherName=temp.getString("fatherName");
                        clientProcess=temp.getString("otherId");
                        dueDate=temp.getString("deadline");
                        JSONArray jsaDate = temp.getJSONArray("updateDetails");
                        for(int k=0; k<jsaDate.length(); k++){
                            JSONObject jo1 = jsaDate.getJSONObject(k);
                            sentDate = jo1.getString("date");
                        }
                        JSONArray ja1 = temp.getJSONArray("address");
                        for(int j=0; j<ja1.length(); j++){
                            JSONObject jo1 = ja1.getJSONObject(j);
                            landmark=jo1.getString("landmark");
                            district= jo1.getString("district");
                            userAddrss=jo1.getString("full");
                            Geocoder coder = new Geocoder(getActivity());
                            List<Address> address1=null;
                            List<Address> addresses = null;
                            try {
                                address1 = coder.getFromLocationName(district, 5);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            if (address1 == null) {
                                Toast.makeText(getActivity(), "Fetching Location,Please wait", Toast.LENGTH_SHORT).show();
                                progressBar.setVisibility(View.INVISIBLE);
                                return;
                            }
                            final Address location11 = address1.get(0);
                            location11.getLatitude();
                            location11.getLongitude();
                            if (checkPermission()) {
                                LocationManager locationManager=(LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);
                                Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                                Location location1 = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                                Location location2 = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);

                                if (location != null) {
                                    latti = location.getLatitude();
                                    longi = location.getLongitude();
                                } else if (location1 != null) {
                                    latti = location1.getLatitude();
                                    longi = location1.getLongitude();
                                } else if (location2 != null) {
                                    latti = location2.getLatitude();
                                    longi = location2.getLongitude();
                                }
                                coder = new Geocoder(getActivity(), Locale.getDefault());

                                try {
                                    addresses = coder.getFromLocation(latti, longi, 1);
                                    if (addresses != null && addresses.size() > 0) {
                                        String address = addresses.get(0).getAddressLine(0);
                                         area = addresses.get(0).getLocality();
                                        String city = addresses.get(0).getAdminArea();
                                        String county = addresses.get(0).getCountryName();
                                        String postal_code = addresses.get(0).getPostalCode();
                                        fullAddress=address+","+area+","+city+","+county+","+postal_code;
                                    }
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                            LatLng source = new LatLng(latti, longi);
                            LatLng destination = new LatLng(location11.getLatitude(), location11.getLongitude());
                            double dis= SphericalUtil.computeDistanceBetween(source,destination);
                            dis/=1000;
                            arrayList.add(new DataModel(nameC,userAddrss,landmark,checkId,Math.floor(dis*100)/100,clientName,candidateFatherName,clientProcess,sentDate,dueDate));
                        }
                    }
                    ..
                    ..

                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        progressBar.setVisibility(View.INVISIBLE);
                        Toast.makeText(getActivity(),error.toString(),Toast.LENGTH_LONG ).show();
                    }
                })
                {
                    @Override
                    protected Map<String, String> getParams() {
                        Map<String,String> map = new HashMap<String,String>();
                        return map;
                    }
                };
        RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
        requestQueue.add(stringRequest);
}

DataholderAdapter.java

public class DataHolderAdapter extends ArrayAdapter {    
        private ArrayList<DataModel> dataSet;
        Context mContext;
        static ProgressDialog progressDialog;
        // View lookup cache
        private static class ViewHolder {
             TextView txtName;
            TextView txtAddress;
            TextView txtLandmark;
            TextView getDirection;
            TextView shortDistance;
        }

        public DataHolderAdapter(ArrayList<DataModel> data, Context context) {
            super(context, R.layout.listview_show, data);
            this.dataSet = data;
            this.mContext=context;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            DataModel dataModel = (DataModel) getItem(position);
            final ViewHolder viewHolder; // view lookup cache stored in tag

            final View result;
            if (convertView == null) {
                viewHolder = new ViewHolder();
                LayoutInflater inflater = LayoutInflater.from(getContext());
                convertView = inflater.inflate(R.layout.listview_show, parent, false);
                viewHolder.txtName = (TextView) convertView.findViewById(R.id.name);
                viewHolder.txtAddress = (TextView) convertView.findViewById(R.id.address);
                viewHolder.txtLandmark = (TextView) convertView.findViewById(R.id.Landmark);
                viewHolder.getDirection=(TextView) convertView.findViewById(R.id.getDirections);
                viewHolder.shortDistance=convertView.findViewById(R.id.shortestDistance);
                progressDialog=new ProgressDialog(getContext());
                viewHolder.getDirection.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        progressDialog.setMessage("Opening maps...");
                        progressDialog.show();
                        Intent i = new Intent(getContext(), MapsActivity.class);
                        i.putExtra("destination",viewHolder.txtAddress.getText().toString());
                        i.putExtra("DataHolder","dataholder");
                        getContext().startActivity(i);
                    }
                });
                result=convertView;
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
                result=convertView;
            }
            viewHolder.txtName.setText(dataModel.getName());
            viewHolder.txtAddress.setText(dataModel.getAddress());
            viewHolder.txtLandmark.setText(Html.fromHtml("<strong>Landmark: </strong>"+dataModel.getLandmark()));
                viewHolder.shortDistance.setText(dataModel.getShortDistance() + " kms");
                //viewHolder.shortDistance.setBackgroundResource(R.attr.bgHighlight);
             return convertView;
       }
    }

我收到的消息:

I/Choreographer: Skipped 167 frames!  The application may be doing 
too much work on its main thread.
D/Dialog: mIsSamsungBasicInteraction = false

1 个答案:

答案 0 :(得分:3)

Geocoder.getFromLocationName正在阻止您的UI线程。来自文档

  

查询将被阻止,并且将通过网络查找获得返回的值。结果是最佳猜测,不能保证是有意义或正确的。从与主UI线程分开的线程中调用此方法可能会很有用。

有关更多信息,请访问此url