当前位置: 首页 > 知识库问答 >
问题:

从 Web 服务获取的数据显示在列表视图中,然后根据列表中的项目对列表视图自定义适配器进行排序

钱劲
2023-03-14

在我的列表视图中有5个数据,但基于Km距离双值,按升序对完整列表视图进行排序。从Webservice获取的所有数据。在列表视图中显示数据正常工作,但只有最后一行数据显示在完整列表中如何解决?

package com.example;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import org.json.JSONArray;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.app.ActivityOptions;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.media.Rating;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;


public class Find_Stores_1_Distance_Based_Tabview1 extends Fragment implements OnClickListener {

    ListView listPage;
    Button Near_Me, Top_Service, Rating_Based, Add_ServiceCenter;
    View rootView;


    int[] images = {
            R.drawable.shop1,R.drawable.shop2,R.drawable.shop1,
            R.drawable.shop1,R.drawable.shop2,R.drawable.shop1,
            R.drawable.shop1,R.drawable.shop2,R.drawable.shop1}

    Rating rateme;

    float ratingValue = 2.0f;


    String ServiceModel = " Phone ";


    // for WebService Fetch from web to Find stores ..
            private static final String SOAP_ACTION = "************";
            private static final String NAMESPACE = "************";
            private static final String URL = "************";
            private static final String METHOD_NAME = "************";
            private String TAG2 = "************";
            public static String Status_Response_FindStores_Landing = "";


            // for WebService Fetch from web to Find stores ..
            private static final String SOAP_ACTION1 = ""************"";
            private static final String NAMESPACE1 = ""************"";
            private static final String URL1 = ""************"";
            private static final String METHOD_NAME1 = ""************"";
            private String TAG3 = ""************"";
            public static String Status_Res_FindStores_Showpage_Data = "";      



            public  String Center_id,Brand_name, ServiceCenterName,Address1,EMailId,ContactNumber,Pincode,Cityname,Latitude1,Longitude1;

            public  String Center_id2,Brand_name2, ServiceCenterName2,Address2,EMailId2,ContactNumber2,Pincode2,Cityname2;

            // flag for Internet connection status
                Boolean isInternetPresent = false;
                // Connection detector class
                InternetConnectionDetector cd1;


                // Progress Bar
                ProgressBar pg;

                private ProgressDialog progress;


                   String[] SERVICE_CENTERNAME,Full_ADDRESS,CENTER_ID;

                   String[] KM_DISTANCE_StringArray;

                   TextView CenterIDText;


                 public String CategoryStringItem,BrandStringItem,CityStringItem;
                 public TextView NotfoundText1; 
                 public Button ReloadButton1;

                public  String centerId_Service,LatitudeSingle_Service,LangitudeSingle_Service;





                public String Latittude_LogitutdeString;

                double latitude_Current, longitude_current;

            //  public Float distance;
                public double distance1;


                    GPSTracker gps;

                 boolean _areLecturesLoaded = false;

                 //For Creating Double array;
                 String[] LatitudeArray,LangitudeArray;



                 public static int StatusoutPutInteger1;

                 //For Ascending Order  Sort

                  private boolean mAscendingOrder[] = {true, true, true};
                    private ItemsListAdapter mAdapter;





    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        rootView = inflater.inflate(R.layout.find_stores_1_distancebased_tabview1,container, false);

        // creating connection Detector class for checking Internet Status
        cd1 = new InternetConnectionDetector(getActivity());

        // create class object
            gps = new GPSTracker(getActivity());


        // call the views with this layout
        listPage = (ListView) rootView.findViewById(R.id.listView123);

         mAdapter = new ItemsListAdapter();


      //  ((ListView) rootView.findViewById(R.id.listView123)).setAdapter(mAdapter); 

        listPage.setAdapter(mAdapter);
    //    fillShoppingList();

        return rootView;

    }

    public void onResume() 
    {
        try {
            super.onResume();


            // get Internet status
            isInternetPresent = cd1.isConnectingToInternet();
            // check for Internet status
            if (isInternetPresent) 
            {

                // check if GPS enabled     
                if(gps.canGetLocation()){

                     latitude_Current = gps.getLatitude();
                     longitude_current = gps.getLongitude();


                    // for data Fetch from web
                    AsyncCallWSfor_PRODUCT task = new AsyncCallWSfor_PRODUCT();
                    // Call execute
                    task.execute();

                }else{
                    // can't get location
                    // GPS or Network is not enabled
                    // Ask user to enable GPS/network in settings
                    gps.showSettingsAlert();
                }


            } 
            else
            {

                Toast.makeText(getActivity(),"Please Check Your Internet Connection ..!",Toast.LENGTH_SHORT).show();

            }


        } catch (Exception e)
        {
            e.printStackTrace();
            Log.i("Exception in Tab1 Onresume","Error");

        }

    }


    // for Product Web Sync 
    private class AsyncCallWSfor_PRODUCT extends AsyncTask<String, Void, Void> {
        @Override
        protected Void doInBackground(String... params) 
        {
            Log.i(TAG2, "doInBackground");
            try
            {
                getSignupdata1(CategoryStringItem,BrandStringItem,CityStringItem);

            } 
            catch (Exception e)
            {
            //  Toast.makeText(getActivity(),"error caught in do in background", Toast.LENGTH_SHORT).show();
                Log.i(TAG2, "Error in Find Background");
                e.printStackTrace();

            }
            return null;

            // return null;
        }

        @Override
        protected void onPostExecute(Void result)
        {
            //pg.setVisibility(View.INVISIBLE);

            // To dismiss the dialog
            progress.dismiss();

            Log.i(TAG2, "onPostExecute");

            try {

                    // Show items ascending

                    mAdapter.sortByPriceAsc();

                    listPage.setOnItemClickListener(new OnItemClickListener()
                    {
                        @Override public void onItemClick(AdapterView<?> arg0, View views,int position, long id)
                        { 

                            try {

                                // get Internet status
                                isInternetPresent = cd1.isConnectingToInternet();
                                // check for Internet status
                                if (isInternetPresent) 

                                        // for Service Center Show page Data Fetch from web
                                        AsyncCallWSfor_FETCHService_Center task = new AsyncCallWSfor_FETCHService_Center();
                                        // Call execute
                                        task.execute();     

                                } 
                                else
                                {

                                    Toast.makeText(getActivity(),"Please Check Your Internet Connection..!",Toast.LENGTH_SHORT).show();

                                }

                            } catch (Exception e)
                            {
                                e.printStackTrace();
                                Log.i("Exception in Tab1 OnItemClick","Error");

                            }

                        }
                    });



                }




            } catch (Exception e) {
                Log.i(TAG2, "Error in Product Insert");
                //Toast.makeText(getActivity(), "Error in sucess",Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }

        }

        @Override
        protected void onPreExecute()
        { 
            progress.setTitle("Progress");
            progress.setMessage("Please Wait Loading...");
            progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progress.setIndeterminate(true);
            progress.show();


        }

        @Override
        protected void onProgressUpdate(Void... values) {
            Log.i(TAG2, "onProgressUpdate");
        }

    }

    public void getSignupdata1(String Categoryitem,String Branditem, String CityLocation) 
    {
        // Create request
        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

        PropertyInfo pi3 = new PropertyInfo();
        pi3.setName("Categ");
        pi3.setValue(Categoryitem);// get the string that is to be sent to the webservice
        pi3.setType(String.class);
        request.addProperty(pi3);

        PropertyInfo pi4 = new PropertyInfo();
        pi4.setName("Band");
        pi4.setValue(Branditem);// get the string that is to be sent to the webservice
        pi4.setType(String.class);
        request.addProperty(pi4);

        PropertyInfo pi5= new PropertyInfo();
        pi5.setName("City");
        pi5.setValue(CityLocation);// get the string that is to be sent to the webservice
        pi5.setType(String.class);
        request.addProperty(pi5);

        // Create envelope
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.dotNet = true;
        // Set output SOAP object
        envelope.setOutputSoapObject(request);
        // Create HTTP call object
        HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

        try {
            // Invole web service
            androidHttpTransport.call(SOAP_ACTION, envelope);
            // Get the response
            SoapPrimitive response = (SoapPrimitive) envelope.getResponse();




            if ((response.toString()).contains("{")) 
            {
                // JSONArray jr = new JSONArray(response);
                SoapObject rep = (SoapObject) envelope.bodyIn;
                JSONArray jr = new JSONArray(rep.getPropertyAsString(0));
                for (int i = 0; i < jr.length(); i++)
                {
                    JSONObject jb = (JSONObject) jr.get(i);

                       Center_id = jb.getString("CenterId");
                       Brand_name = jb.getString("Brand");
                       ServiceCenterName = jb.getString("Center");
                       Address1 = jb.getString("Add");
                       EMailId = jb.getString("mail");
                       ContactNumber = jb.getString("Contact");
                       Pincode = jb.getString("PinCode");
                       Cityname = jb.getString("City");
                       Latitude1=jb.getString("latitude");
                       Longitude1=jb.getString("longitude");

                       double latitude_Doublevalue = Double.parseDouble(Latitude1);
                       double longitude_Doublevalue = Double.parseDouble(Longitude1);


                       try
                       {

                        Location locationA = new Location("point A");
                        locationA.setLatitude(latitude_Current);
                        locationA.setLongitude(longitude_current);
                        Location locationB = new Location("point B");
                        locationB.setLatitude(latitude_Doublevalue);
                        locationB.setLongitude(longitude_Doublevalue);
                //      distance = locationA.distanceTo(locationB)/1000;//Distance in Kilometers



                        distance1 = locationA.distanceTo(locationB)/1000;



                         Log.i("Service_CenterNameStringOutput","Out "+ServiceCenterName);
                         Log.i("AddressStringOutput","Out "+Address1);
                         Log.i("DistanceStringOutput","Out "+distance1);


                       }
                       catch(Exception ex)
                       {
                           ex.printStackTrace();
                           Log.i(TAG2, "Error in Distance Calculate");

                       }

                       getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {



                                fillShoppingList(Address1,ServiceCenterName,distance1);


                            }
                        });  

                     //  Log.i("CenterIdssss", Center_id);

                }



            } 
            else
            {
                Status_Response_FindStores_Landing = response.toString();
            }

        } catch (Exception e) {
            Log.i(TAG2, "Error in Signup1 catch");
            e.printStackTrace();
        }

    }



    //GPS Enabler
         public void showSettingsAlert() {
                AlertDialog.Builder alertDialog = new AlertDialog.Builder(
                        getActivity());
                alertDialog.setTitle("Settings");
                alertDialog.setMessage("Enable Location Provider! Go to settings menu?");
                alertDialog.setPositiveButton("Settings",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                Intent intent = new Intent(
                                        Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                getActivity().startActivity(intent);
                            }
                        });
                alertDialog.setNegativeButton("Cancel",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                            }
                        });
                alertDialog.show();

            }






         private void fillShoppingList(String address12, String serviceCenterName3, double distance12string  )
            {


                SortAscendingClass item = new SortAscendingClass();
                item.setAddressArray(address12);
                item.setCmpy_NameArray(serviceCenterName3);
                item.setDistancekmArray(distance12string);

                mAdapter.addItem(item);
                //mAdapter.sortByPriceAsc();

            }



            /** Adapter for the shopping list items */
            private class ItemsListAdapter extends BaseAdapter {

                private LayoutInflater vi;
                private ArrayList<SortAscendingClass> shoppingList = new ArrayList<SortAscendingClass>();

                public ItemsListAdapter() 
                {

                      vi = (LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                }

                /** Add white line */
                public void addItem(SortAscendingClass item) {
                    shoppingList.add(item);
                    notifyDataSetChanged();
                }



                /** Sort shopping list by price ascending */
                public void sortByPriceAsc() {
                    Comparator<SortAscendingClass> comparator = new Comparator<SortAscendingClass>() {

                        @Override
                        public int compare(SortAscendingClass object1, SortAscendingClass object2) {
                            return Double.compare(object1.getDistancekmArray(), object2.getDistancekmArray());
                        }
                    };
                    Collections.sort(shoppingList, comparator);
                    notifyDataSetChanged();
                }




                @Override
                public View getView(int position, View convertView, ViewGroup parent) {
                    ViewHolder holder = null;
                    if (convertView == null) {
                        holder = new ViewHolder();
                        convertView = vi.inflate(R.layout.findstores_service_center_tabview1_2_3_listview, null);



                        holder.myImage = (ImageView) convertView.findViewById(R.id.imageView1);
                        holder.ServcieCenterFullname = (TextView) convertView.findViewById(R.id.textView1);
                        holder.AddressName = (TextView) convertView.findViewById(R.id.textView2);
                        holder.ratingtext = (RatingBar)convertView.findViewById(R.id.ratingBarinTabs);
                        holder.myDistance = (TextView) convertView.findViewById(R.id.Distance);
                        holder.SErvice_Available = (TextView) convertView.findViewById(R.id.serviceCategory);

                        /*holder.CenterIDText=(TextView)convertView.findViewById(R.id.CenterId_xml);
                        holder.LatitudeText=(TextView)convertView.findViewById(R.id.latitude_xml);
                        holder.LangitudeText=(TextView)convertView.findViewById(R.id.langitude_xml);*/


                        convertView.setTag(holder);
                    }
                    else {
                        holder = (ViewHolder) convertView.getTag();
                    }


                        holder.myImage.setImageResource(images[position]);
                        holder.ServcieCenterFullname.setText(String.valueOf(shoppingList.get(position).getCmpy_NameArray()));
                        holder.AddressName.setText(String.valueOf(shoppingList.get(position).getAddressArray()));
                        holder.ratingtext.setRating(ratingValue); // to set rating value
                        holder.myDistance.setText(String.valueOf(shoppingList.get(position).getDistancekmArray()+" Km"));
                        holder.SErvice_Available.setText(ServiceModel);




                    return convertView;
                }

                @Override
                public int getCount() {

                    return shoppingList.size();
                }

                @Override
                public Object getItem(int position) {

                    return shoppingList.get(position);
                }

                @Override
                public long getItemId(int position) {

                    return position;
                }

                /** Helper class acting as a holder of the information for each row */
                private class ViewHolder {
                    /*public TextView name;
                    public TextView price;
                    public TextView quantity;*/

                        public ImageView myImage;
                        public TextView ServcieCenterFullname;
                        public TextView AddressName ;
                        public RatingBar ratingtext ;
                        public TextView myDistance;
                        public TextView SErvice_Available;
                        public TextView CenterIDText;
                        public TextView LatitudeText;
                        public TextView LangitudeText;

                }
            }


}

共有3个答案

淳于坚壁
2023-03-14

使用< code>ArrayAdapter,按整数对与< code>adapter关联的数组中的元素进行排序,并将< code>adapter链接到您的listView。

柳英豪
2023-03-14

您可以对支持listview的适配器进行排序,ListView将自动排序。

欧阳声
2023-03-14

您还可以使用Collections和ArrayList按以下方式进行排序

Collections.sort(YourArrayList);
 类似资料:
  • 我试图使用文本视图来显示从列表视图中选择的联系人。列表视图包含用户从加载到列表视图中的Android电话簿中选择的联系人。文本视图将只显示列表视图中的最后一项,即使用户选择了另一个不是列表视图中最后一个联系人的联系人。 即使在我的日志打印中,我可以看到我选择了哪个联系人,但当我试图将其打印到另一个窗口中的文本视图时,它仍然默认为最后一个联系人。 添加调制解调器。JAVA 主要活动。JAVA

  • 问题内容: 我有一个数据库SQLite,然后使用SimpleCursorAdapter,将值显示到列表视图中。但是,我想重新排列列表视图项,并在顶部显示ID#1,然后显示ID号2,依此类推。问题是,我无法掌握根据以下内容重新分配列表视图项的概念在内容提供商提供的某些ID号上。如果您知道,请分享。谢谢。 问题答案: 如果正确使用SQLite,则在查询数据库时应该能够执行“按ID排序”。 如果不是这种

  • 我正在尝试为我的列表视图制作一个自定义适配器,但我在同一行上不断得到一个 RessourceNotFoundException。 首先,这是我的适配器类代码: 这是视图的xml,包含listview: 以及带有上述列表视图的项目布局的xml文件: 这是在我的活动中设置适配器的代码(扩展活动) 我遇到的错误是: 12661-12661/com.mobileplatformexam E/Android

  • 问题内容: 我有以下清单 我想根据其子列表的长度对列表进行排序。结果应为: 问题答案: 使用和中可用的参数。它指定一个参数的功能,该参数用于从每个列表元素中提取比较键

  • 我有一个带有按钮的视图和一个列表视图,由包含bindView()和newView()的光标适配器支持,用于自定义视图。列表的每一行都包含一个Text和一个复选框。每个视图的数据来自数据库。我正在光标适配器构造函数中传递我的数据库适配器。当复选框被选中或取消选中时,我用它来更新数据库(效果很好)。当然,我对光标运行“重新查询”并view.refreshDrawableState())。这是个好主意吗