11

API verileriyle dolu bir dizim var ve bu dizinin öğelerini göstermek için genişletilebilir bir görünümüm var, şimdi ne yapmaya çalıştığım kullanıcı tıklattığında bir öğe üzerinde, o öğenin kimliğini bir diziye kaydeder, bu yüzden kullanıcı 2 öğeyi seçerse dizimdeki 2 Ids'ı seçerim, şu anda olan şey şu: Bu, öğelerin yalnızca birini seçmemin bir önemi yok onları ve dizimin içine sakla.Birden çok seçenekli bir çok seçenekle genişletilebilirListView Seçilen öğeyi bir diziye kaydetme

public class MainActivity extends Fragment { 

    private ExpandListAdapter ExpAdapter; 
    private ExpandableListView ExpandList; 
    private Button notificar; 
    private Context context; 
    MainActivity mContext; 
    private Button footer; 
    private double RaioEscola; 
    private CircleOptions mCircle; 
    GPSTracker tracker; 
    private Location location; 
    private Integer IdEscola; 

    public MainActivity() { 
    } 

    public MainActivity(Context context) { 
     this.context = context; 
    } 

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

     final View rootView = inflater.inflate(R.layout.expand, container, false); 

     ExpandList = (ExpandableListView) rootView.findViewById(R.id.exp_list); 
     notificar = (Button) rootView.findViewById(R.id.btnGetMoreResults); 

     new asyncTask(MainActivity.this).execute(); 

     return rootView; 
    } 

    private class asyncTask extends AsyncTask<String, Void, Void> { 

     private ProgressDialog pd; 

     public asyncTask(MainActivity context) { 

      mContext = context; 
      pd = new ProgressDialog(getActivity()); 
      pd.setTitle("Por Favor Espere ..."); 
      pd.setMessage("Enviando ..."); 
      if (!pd.isShowing()) { 
       pd.show(); 
      } 
     } 


     @Override 
     protected Void doInBackground(final String... params) { 

      try { 

       String[] resposta = new WebService().get("filhos"); 

       if (resposta[0].equals("200")) { 

        JSONObject mJSONObject = new JSONObject(resposta[1]); 
        JSONArray dados = mJSONObject.getJSONArray("data"); 

        /* cria o array que vai receber os dados da api */ 
        final ArrayList<Escolas> mArrayList = new ArrayList<Escolas>(); 

        /* percorre o array, adicionando cada linha encontrada em um ArrayList */ 
        for (int i = 0; i < dados.length(); i++) { 

         JSONObject item = dados.getJSONObject(i); 

         Escolas mEscolas = new Escolas(); 

         mEscolas.setId_escola(item.optInt("id_escola")); 
         mEscolas.setCnpj(item.getString("cnpj")); 
         mEscolas.setRazao_social(item.getString("razao_social")); 
         mEscolas.setNome_fantasia(item.getString("nome_fantasia")); 
         mEscolas.setDistancia(Float.valueOf(item.getString("distancia"))); 
         mEscolas.setLogradouro(item.optString("logradouro")); 
         mEscolas.setNumero(item.optString("numero")); 
         mEscolas.setBairro(item.getString("bairro")); 
         mEscolas.setComplemento(item.getString("complemento")); 
         mEscolas.setCep(item.getString("cep")); 
         mEscolas.setCidade(item.getString("cidade")); 
         mEscolas.setEstado(item.getString("estado")); 
         mEscolas.setLatitude(Float.parseFloat(item.getString("latitude"))); 
         mEscolas.setLongitude(Float.parseFloat(item.getString("longitude"))); 

         RaioEscola = Double.parseDouble(String.valueOf(mEscolas.getDistancia())); 
         IdEscola = mEscolas.getId_escola(); 


         JSONObject alunos = item.optJSONObject("alunos"); 

         JSONArray data = alunos.getJSONArray("data"); 

         if (data != null) { 

          ArrayList<Filhos> arrayalunos = new ArrayList<Filhos>(); 

          for (int a = 0; a < data.length(); a++) { 

           Filhos mFilhos = new Filhos(); 

           JSONObject clientes = data.getJSONObject(a); 

           mFilhos.setId_aluno(clientes.optInt("id_aluno")); 
           mFilhos.setNome(clientes.optString("nome")); 
           mFilhos.setSobrenome(clientes.optString("sobrenome")); 
           mFilhos.setFoto(clientes.optString("foto")); 
           mFilhos.setModalidade_de_ensino(clientes.optString("modalidade_de_ensino")); 
           mFilhos.setObservacoes(clientes.optString("observacoes")); 

           arrayalunos.add(mFilhos); 
          } 

          mEscolas.setalunos(arrayalunos); 
         } 

         /* popula o array de viagens */ 
         mArrayList.add(mEscolas); 

         ExpAdapter = new ExpandListAdapter(getActivity(), mArrayList); 

         getActivity().runOnUiThread(new Runnable() { 

          @Override 
          public void run() { 

           ExpandList.setAdapter(ExpAdapter); 
           ExpAdapter.notifyDataSetChanged(); 

           ExpAdapter.setChoiceMode(ExpandListAdapter.CHOICE_MODE_MULTIPLE); 

           ExpandList.setOnChildClickListener(new ExpandableListView.OnChildClickListener() { 

            @Override 
            public boolean onChildClick(final ExpandableListView parent, View v, final int groupPosition, final int childPosition, final long id) { 

             ExpAdapter.setClicked(groupPosition, childPosition); 
             final int index = parent.getFlatListPosition(ExpandableListView.getPackedPositionForChild(groupPosition, childPosition)); 
             parent.setItemChecked(index, true); 
             parent.setSelectedChild(groupPosition, childPosition, true); 
             parent.getChildAt(index); 

             notificar.setOnClickListener(new View.OnClickListener() { 

              @Override 
              public void onClick(View v) { 

               class update extends TimerTask { 

                public void run() { 

                 try { 

                  getActivity().runOnUiThread(new Runnable() { 

                   @Override 
                   public void run() { 

                    final float latitude = mArrayList.get(groupPosition).getLatitude(); 
                    final float longitude = mArrayList.get(groupPosition).getLongitude(); 

                    LatLng latLng = new LatLng(latitude, longitude); 
                    drawMarkerWithCircle(latLng); 

                    GPSTracker gps = new GPSTracker(getActivity()); 

                    double latitudegps = gps.getLatitude(); 
                    double longitudegps = gps.getLongitude(); 

                    float[] distance = new float[2]; 

                    Location.distanceBetween(mCircle.getCenter().latitude, mCircle.getCenter().longitude, latitudegps, longitudegps, distance); 
                    if (distance[0] > mCircle.getRadius()) { 
                     Toast.makeText(getActivity(), "Outside", Toast.LENGTH_LONG).show(); 
                    } 
                    else { 
                     Toast.makeText(getActivity(), "Inside", Toast.LENGTH_LONG).show(); 
                     AlertRest mAlertRest = new AlertRest(); 
                     try { 

                      List<Integer> myIdList = new ArrayList<Integer>(); 

                      for (int i = 0; i < mArrayList.get(groupPosition).getalunos().size(); i++) { 

                       Integer Idalunos = mArrayList.get(groupPosition).getalunos().get(i).getId_aluno(); 

                       myIdList.add(Idalunos); 
                      } 

                      mAlertRest.getNotificacao(1, mArrayList.get(groupPosition).getId_escola(), String.valueOf(myIdList), latitudegps, longitudegps); 

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

               Timer timer = new Timer(); 
               timer.schedule(new update(), 0, 15000); 
              } 

              private void drawMarkerWithCircle(LatLng position) { 
               mCircle = new CircleOptions().center(position).radius(RaioEscola); 
              } 
             }); 

             return false; 
            } 
           }); 
          } 
         }); 
        } 

        /* retorna um array de objetos */ 

       } 
       else { 
        throw new Exception("[" + resposta[0] + "] ERRO: " + resposta[1]); 
       } 

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

      return null; 
     } 

     @Override 
     protected void onPostExecute(Void cursor) { 
      if (pd.isShowing()) { 
       pd.dismiss(); 
      } 
     } 
    } 
} 

AlertRest: Sen adaptör başlatılıyor için ve aynı zamanda myIdList doldurmak için mArrayList değişken kullanıyorsanız

public class AlertRest extends WebService { 


    private String recurso = "notificacoes"; 
    private String[] resposta; 
    private AlertModelo mAlertModelo; 


    public AlertModelo getNotificacao(Integer id_usuario, String token, Integer id_escola, String ids_aluno, Double latitude, Double longitude) throws Exception { 


     /* dispara a requisição para a API retornar os dados do "recurso" necessário */ 
     resposta = new WebService().postToken(recurso, token, "{\"id_usuario\":" + id_usuario + "," + "\"id_escola\":" + id_escola + "," + "\"ids_aluno\":\"" + ids_aluno + "\"," + "\"latitude\":" + latitude + "," + "\"longitude\":" + longitude + "}"); 

     JSONObject mJSONObject = new JSONObject(resposta[1]); 

     if (resposta[1].equals("201")) { 

      mAlertModelo = new AlertModelo(); 
      mAlertModelo.setId_usuario(mJSONObject.getInt(String.valueOf(id_usuario))); 
      mAlertModelo.setId_escola(mJSONObject.getInt(String.valueOf(id_escola))); 
      mAlertModelo.setIds_aluno(mJSONObject.getInt(String.valueOf(ids_aluno))); 
      mAlertModelo.setLatitude(mJSONObject.getDouble(String.valueOf(latitude))); 
      mAlertModelo.setLongitude(mJSONObject.getDouble(String.valueOf(longitude))); 

     } 
     return mAlertModelo; 
    } 

} 
+0

Doğru biçimlendirilmiş kod gönderdiyseniz yardımcı olur. Şu anda, iç içe geçmiş bir kod devasa bir küre gibi görünüyor. –

+0

@JaySoyer orada, tüm parçacığı – AND4011002849

+1

@ JaySoyer I, biçimlendirmeyi düzeltmek için kodu düzenledi, ama gerçekten iç içe geçmiş kodun dev bir globudur, bunu düzeltmek ve nesneleri kullanmak için tek yoldur. WARpoluido, bazı refactoring'leri düşünmek isteyebilirsiniz, kodu temizleyerek altta yatan probleminizi ortaya çıkarmanıza yardımcı olabilir. –

cevap

2

kod nedeniyle birkaç iç içe döngüler ve çalışan görevler için takip etmek zordur. Neyse, aşağıdaki kod uygulama listesindeki tüm (seçilmemiş) öğelerini kaydetmek neden olan şüpheli:

for (int i = 0; i < mArrayList.get(groupPosition).getalunos().size(); i++) { 
    Integer Idalunos = mArrayList.get(groupPosition).getalunos().get(i).getId_aluno(); 

    myIdList.add(Idalunos); 
} 

Not: Yineleme Yapmak tüm liste üzerinden bir şüpheli. Listede belirli bir öğe veya öğe seçmelidir.

Bu nedenle, başka bir ilgili kodlar, kod düzeltmesini belirlememize yardımcı olabilir. Burada da bir hata varsa emin değilim.

parent.setItemChecked(index, true); 
parent.setSelectedChild(groupPosition, childPosition, true); 
parent.getChildAt(index); 

Not: Bu kodlar iyi olabilir. Anahtar kod, bence, dizini. ExpandableListView ile çok aşina değilim. Değişken endeksi, Idalunos doğru öğeyi almak için kullanılır

Integer Idalunos = mArrayList.get(groupPosition).getalunos().get(index).getId_aluno(); 
... 
myIdList.add(Idalunos); 

Bildirimi:

Son olarak, kod düzeltme önerdi.

2

. Elbette myIdList, adaptörünüzün tam listesini içerecektir.

GÜNCELLEME

sizin MainActivity sınıfın alanı olarak myIdList tanımlamak ve onCreateView yönteminde bunu başlatmak için daha iyi olurdu. tıklamada

sadece değer katmayan - Eğer bu değer listesinde allready olup olmadığını kontrol etmelidir:

if(myIdList.contains(Idalunos)) { 
    myIdList.remove(Idalunos); 
} else { 
    myIdList.add(Idalunos); 
} 
+0

Daha fazla ayrıntıyla nasıl çözeceğimi gösterebilir misin? Teşekkürler – AND4011002849

+0

İlk başta, seçilen öğelerin 'myIdList' içinde içerdiğinden emin miyim? – Ircover

+0

Evet, haklısınız – AND4011002849

İlgili konular