2016-11-26 7 views
-3

Ich versuche, Storelist in StoreList-Variable zu setzen. Aber es funktioniert nicht. doInBackground Methode funktioniert perfekt, aber onPostexecute funktioniert nicht.Wie bekomme ich Arraylist <HashMap <String, String >> von AsyncTask bis onPostExecute

Hier ist mein Code,

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(); 
    } 
} 

Antwort

-1

Ok..The Problem in Ihrem Fall ist, dass die Async Aufgabe von UI-Thread auf separaten Thread läuft also, wenn Sie anrufen BackgroundWorker3 in getData Methode dann Thread UI nicht Warten auf asynchrone Aufgabenantwort (separater Thread) und StoreList haben einen Nullwert. Sie sehen also, StoreList hat keinen Wert und in ListView wird nichts angezeigt.

schreiben Sie diesen Code in OnPostExecute Methode nicht in 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); 

} 

Hope this Ihnen helfen.

+0

Ich habe meine onPostExecute geändert, wie du es mir gesagt hast, aber jetzt hört es auf, wenn diese UI angezeigt wird und meine hashmap auf der Listview immer noch nicht angezeigt wird ... – capstone

+0

Wer hat meine Antwort beantwortet..Kann mir sagen, wie das nicht ist relevante Antwort. –

Verwandte Themen