具有多项选择的 ExpandableListView 将所选项目保存到数组中
Posted
技术标签:
【中文标题】具有多项选择的 ExpandableListView 将所选项目保存到数组中【英文标题】:ExpandableListView with multiple choice save selected item into an array 【发布时间】:2015-07-26 05:18:33 【问题描述】:我有一个填充了 API 数据的数组,并且我有一个可展开的列表视图来显示该数组的项目,现在我要做的是当用户单击一个项目时,它会保存该项目的 ID到一个数组中,所以如果用户选择 2 个项目,我想要 2 个 Id 在我的数组中,现在发生的是:无论我是否只选择其中一个项目,它都会获取所有项目并将其保存在我的数组中。
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();
警报休息:
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;
【问题讨论】:
如果您发布格式正确的代码会有所帮助。现在,它看起来像是一大堆嵌套代码。 @JaySoyer 那里,整个片段 @JaySoyer 我编辑了代码来修复格式,但它确实是一大堆嵌套代码,修复它的唯一方法是重构和使用对象。 WARpoluido,您可能需要考虑一些重构,它可以通过清理代码帮助您发现潜在问题。 请格式化代码,以便何时可以更好地帮助您。 到目前为止您的调试进展如何?有什么进展吗? 【参考方案1】:由于嵌套循环和正在运行的任务很少,代码难以遵循。 无论如何,我怀疑下面的代码会导致您的应用保存列表中的所有(未选择)项目:
for (int i = 0; i < mArrayList.get(groupPosition).getalunos().size(); i++)
Integer Idalunos = mArrayList.get(groupPosition).getalunos().get(i).getId_aluno();
myIdList.add(Idalunos);
注意:遍历整个列表是可疑的。它应该选择列表中的某个或多个项目。
所以...另一组相关代码可以帮助我们确定代码修复。我不确定这里是否也有错误。
parent.setItemChecked(index, true);
parent.setSelectedChild(groupPosition, childPosition, true);
parent.getChildAt(index);
注意:这些代码可能没问题。我认为关键代码是index。我对 ExpandableListView 不太熟悉。
最后,建议的代码修复:
Integer Idalunos = mArrayList.get(groupPosition).getalunos().get(index).getId_aluno();
...
myIdList.add(Idalunos);
注意变量 index 用于获取正确的项目 Idalunos。
【讨论】:
【参考方案2】:您正在使用mArrayList
变量来初始化适配器并同时填充myIdList
。当然myIdList
将包含您的适配器的完整列表。
更新
最好将myIdList
定义为MainActivity
类的字段并在onCreateView
方法中对其进行初始化。
点击时不只是添加值 - 你应该检查这个值是否已经在列表中:
if(myIdList.contains(Idalunos))
myIdList.remove(Idalunos);
else
myIdList.add(Idalunos);
【讨论】:
起初 - 我是不是在myIdList
中包含所选项目?
好的。对于什么AlertRest
类和什么getNotificacao
方法?
我已经更新了问题,AlertRest 类是发布通知以上是关于具有多项选择的 ExpandableListView 将所选项目保存到数组中的主要内容,如果未能解决你的问题,请参考以下文章
具有多项选择的 ExpandableListView 将所选项目保存到数组中