如何获得Arraylist <hashmap <string,string =“”>&gt;从AsyncTask到onPostExecute

时间:2016-11-26 05:03:22

标签: android android-asynctask

我正在尝试将storelist放入StoreList变量。但它没有用。 doInBackground方法工作正常但onPostexecute无效。

这是我的代码,

public class guest_main extends Fragment implements View.OnClickListener,GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {
    Location mCurrentLocation, mDestination;
    private GoogleApiClient mGoogleApiClient;
    private LocationRequest mLocationRequest;
    String currentLon, currentLat;
    private ListView mListView = null;
    private ListViewAdapter mAdapter = null;
    public ArrayList<HashMap<String, String>> StoreList;

    class BackgroundWorker3 extends AsyncTask<String, Void,ArrayList<HashMap<String, String>>>  {
        Context context;
        AlertDialog alertDialog;


        BackgroundWorker3(Context ctx) {
            context = ctx;
        }

        JSONArray store = null;
        ArrayList<HashMap<String, String>> storeList;

        protected ArrayList<HashMap<String, String>> doInBackground(String... params) {
            String type = params[0];
            storeList = new ArrayList<HashMap<String, String>>();
            if (type.equals("Select2")) {
                try {

                    String link = "...";
                    URL url = new URL(link);
                    URLConnection conn = url.openConnection();
                    conn.setDoOutput(true);
                    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
                    wr.flush();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
                    StringBuilder sb = new StringBuilder();
                    String json;
                    while ((json = reader.readLine()) != null) {
                        sb.append(json);
                    }
                    String s = sb.toString().trim();
                    JSONObject jsonObject = new JSONObject(s);
                    store = jsonObject.getJSONArray("result");
                    for (int i = 0; i < store.length(); i++) {
                        JSONObject c = store.getJSONObject(i);
                        String name = c.getString("name");
                        String tel = c.getString("tel");
                        String latitude = c.getString("latitude");
                        String longitude = c.getString("longitude");
                        HashMap<String, String> stores = new HashMap<String, String>();
                        stores.put("name", name);
                        stores.put("tel", tel);
                        stores.put("latitude", latitude);
                        stores.put("longitude", longitude);
                        storeList.add(stores);
                    }
                    return storeList;
                } catch (Exception e) {
                    return null;
                }

            }
            return storeList;
        }

        @Override
        protected void onPreExecute() {
            alertDialog = new AlertDialog.Builder(context).create();
            alertDialog.setTitle("Login Status");
        }

        @Override
        protected void onPostExecute(ArrayList<HashMap<String, String>> arrayList) {



            StoreList = arrayList;

        }
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.guest_main, container, false);
        StoreList = new ArrayList<HashMap<String, String>>();
        getData();
        buildGoogleApiClient();

        mListView = (ListView)v.findViewById(R.id.mList);
        mAdapter = new ListViewAdapter(getActivity());

       for(int i=0; i<StoreList.size(); i++){
           HashMap<String, String> each = StoreList.get(i);
           String name = each.get("name");
           String tel = each.get("tel");
           String lat = each.get("latitude");
           String lon = each.get("longitude");
           mDestination.setLatitude(Double.valueOf(lat).doubleValue());
           mDestination.setLongitude(Double.valueOf(lon).doubleValue());
           float distance = mCurrentLocation.distanceTo(mDestination);
           mAdapter.addItem(getResources().getDrawable(R.drawable.sin), name, tel,Float.toString(distance));
       }
        mListView.setAdapter(mAdapter);



        Button btn = (Button) v.findViewById(R.id.button1);
        btn.setOnClickListener(this);

        return v;
    }
    public void getData(){
        BackgroundWorker3 bk2 = new BackgroundWorker3(getActivity());

            bk2.execute("Select2");



    }


    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.button1:
                Intent intent = new Intent(getActivity().getApplicationContext(), gmenu_list.class);
                startActivity(intent);

        }
    }


    private class ViewHolder {
        public ImageView mIcon;

        public TextView mText;

        public TextView mDate;

        public TextView mDistance;
    }

    private class ListViewAdapter extends BaseAdapter {
        private Context mContext = null;
        private ArrayList<g_ListData> mListData = new ArrayList<g_ListData>();

        public ListViewAdapter(Context mContext) {
            super();
            this.mContext = mContext;
        }

        @Override
        public int getCount() {
            return mListData.size();
        }

        @Override
        public Object getItem(int position) {
            return mListData.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        public void addItem(Drawable icon, String mTitle, String mDate, String mDistance){
            g_ListData addInfo = null;
            addInfo = new g_ListData();
            addInfo.mIcon = icon;
            addInfo.mTitle = mTitle;
            addInfo.mDate = mDate;
            addInfo.mDistance = mDistance;

            mListData.add(addInfo);
        }

        public void remove(int position){
            mListData.remove(position);
            dataChange();
        }

        public void sort(){
            Collections.sort(mListData, g_ListData.ALPHA_COMPARATOR);
            dataChange();
        }

        public void dataChange(){
            mAdapter.notifyDataSetChanged();
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();

                LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = inflater.inflate(R.layout.gmenu_list_item, null);

                holder.mIcon = (ImageView) convertView.findViewById(R.id.mImage);
                holder.mText = (TextView) convertView.findViewById(R.id.mText);
                holder.mDate = (TextView) convertView.findViewById(R.id.mDate);
                holder.mDistance = (TextView)convertView.findViewById(R.id.mDistance);

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

            g_ListData mData = mListData.get(position);

            if (mData.mIcon != null) {
                holder.mIcon.setVisibility(View.VISIBLE);
                holder.mIcon.setImageDrawable(mData.mIcon);
            }else{
                holder.mIcon.setVisibility(View.GONE);
            }

            holder.mText.setText(mData.mTitle);
            holder.mDate.setText(mData.mDate);
            holder.mDate.setText(mData.mDistance);

            return convertView;
        }

    }

    @Override
    public void onConnected(Bundle bundle) {
        mLocationRequest = LocationRequest.create();
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setInterval(100000); // Update location every second
        try{
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);


            mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(
                    mGoogleApiClient);}catch (SecurityException e){
        }
        if (mCurrentLocation != null) {
            currentLat = String.valueOf(mCurrentLocation.getLatitude());
            currentLon = String.valueOf(mCurrentLocation.getLongitude());

        }

    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onLocationChanged(Location location) {
        currentLat = String.valueOf(location.getLatitude());
        currentLon = String.valueOf(location.getLongitude());
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }
    synchronized void buildGoogleApiClient(){
        mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }
    @Override
    public void onStart() {
        super.onStart();
        mGoogleApiClient.connect();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mGoogleApiClient.disconnect();
    }
}

1 个答案:

答案 0 :(得分:-1)

好的..问题出在你的情况下,Async任务在UI线程的单独线程上运行所以当你在getData方法中调用BackgroundWorker3时,UI线程不等待异步任务响应(separte线程)和StoreList有null值。所以你看到StoreList没有任何值,在listView中什么都不会显示。

将此代码写入onPostExecute方法而不是onCreate ..

@Override
protected void onPostExecute(ArrayList<HashMap<String, String>> arrayList) {



    StoreList = arrayList;
    mListView = (ListView)v.findViewById(R.id.mList);
   mAdapter = new ListViewAdapter(getActivity());

for(int i=0; i<StoreList.size(); i++){
   HashMap<String, String> each = StoreList.get(i);
   String name = each.get("name");
   String tel = each.get("tel");
   String lat = each.get("latitude");
   String lon = each.get("longitude");
   mDestination.setLatitude(Double.valueOf(lat).doubleValue());
   mDestination.setLongitude(Double.valueOf(lon).doubleValue());
   float distance = mCurrentLocation.distanceTo(mDestination);
   mAdapter.addItem(getResources().getDrawable(R.drawable.sin), name, tel,Float.toString(distance));
 }
mListView.setAdapter(mAdapter);

}

希望这会对你有所帮助。