gpt4 book ai didi

android - 具有多项选择的 ExpandableListView 将所选项目保存到数组中

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:47:26 26 4
gpt4 key购买 nike

我有一个充满 API 数据的数组,我有一个可扩展 ListView 来显示该数组的项目,现在我要做的是当用户点击一个项目时它会保存该项目的 ID到一个数组中,所以如果用户在我的数组中选择我想要的 2 个 ID 的 2 个项目,现在发生的是:无论我是否只选择其中一个项目,它都会获取所有项目并将其保存在我的数组中。

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

}

最佳答案

由于嵌套循环和运行任务很少,代码很难理解。无论如何,我怀疑下面的代码导致您的应用程序保存列表中的所有(未选择的)项目:

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。

关于android - 具有多项选择的 ExpandableListView 将所选项目保存到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30239903/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com