Я три дня пытаюсь решить эту проблему с помощью моего фильтра, используя флажок и ListView.
В этом коде я впервые устанавливаю флажки, и они правильно отображаются в списке с идентификаторами каждой выбранной категории и просматривают идентификаторы для другого действия, называемого NovaActivity. ОК? Пока все хорошо.
Проблема заключается в следующем, когда я снова открываю действие «Фильтры», чтобы установить новый флажок для снятия отметки с уже перечисленными фильтрами, которые он продолжает отправлять в NovaAcitivty, даже если они не отмечены.
EX:
1-й фильтр выбирает 1 и 2;
Когда я отправляю это другому, оно идет 1,2;
2-й фильтр Я выбираю 1 и снимаю флажок 2;
Когда я отправляю это другому, оно идет 1,1,2;
Как мне решить эту проблему?
ПРИМЕЧАНИЕ: важно, чтобы во второй раз было сказано, что я открываю действие Filters, уже выбранные флажки уже отмечены, потому что я записываю их в свою удаленную базу данных MySQL и извлекаю их.
Если мне было не очень ясно, можете задавать вопросы по желанию, спасибо, что уже помогли.
public class MainActivity extends AppCompatActivity {
Context context;
ArrayList<Category> array_list;
FavouriteCategoriesJsonParser categoryJsonParser;
String categoriesCsv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
new asyncTask_getCategories().execute();
}
public static class CategoryAdapter extends ArrayAdapter<Category> {
private final List<Category> list;
public CategoryAdapter(Context context, int resource, List<Category> list) {
super(context, resource, list);
this.list = list;
}
static class ViewHolder {
protected TextView categoryName;
protected CheckBox categoryCheckBox;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
LayoutInflater inflator = LayoutInflater.from(getContext());
convertView = inflator.inflate(R.layout.row_category, null);
viewHolder = new ViewHolder();
viewHolder.categoryName = (TextView) convertView.findViewById(R.id.row_categoryname_textview);
viewHolder.categoryCheckBox = (CheckBox) convertView.findViewById(R.id.row_category_checkbox);
viewHolder.categoryCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int getPosition = (Integer) buttonView.getTag();
list.get(getPosition).setSelected(buttonView.isChecked());
if (buttonView.isChecked()) {
if (!FavouriteCategoriesJsonParser.selectedCategories.contains(String.valueOf(list.get(getPosition).getCateogry_id()))) {
FavouriteCategoriesJsonParser.selectedCategories.add(String.valueOf(list.get(getPosition).getCateogry_id()));
Log.i("ISIS_back"," "+"ADICONOU "+String.valueOf(list.get(getPosition).getCateogry_id()));
}
} else {
if (FavouriteCategoriesJsonParser.selectedCategories.contains(String.valueOf(list.get(getPosition).getCateogry_id()))) {
FavouriteCategoriesJsonParser.selectedCategories.remove(String.valueOf(list.get(getPosition).getCateogry_id()));
Log.i("ISIS_back"," "+"REMOVEU "+String.valueOf(list.get(getPosition).getCateogry_id()));
}
}
}
});
convertView.setTag(viewHolder);
convertView.setTag(R.id.row_categoryname_textview, viewHolder.categoryName);
convertView.setTag(R.id.row_category_checkbox, viewHolder.categoryCheckBox);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.categoryCheckBox.setTag(position);
viewHolder.categoryName.setText(list.get(position).getCategory_Name());
viewHolder.categoryCheckBox.setChecked(list.get(position).isSelected());
return convertView;
}
}
public static class FavouriteCategoriesJsonParser {
public static ArrayList<String> selectedCategories = new ArrayList<>();
public ArrayList<Category> getParsedCategories() {
String JsonFavouriteCategories = "";
ArrayList<Category> MyArraylist = new ArrayList<>();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("https://pensoupediu.000webhostapp.com/api/filtro/getFavouriteCategories.php?id_usuario=1");
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
JsonFavouriteCategories = EntityUtils.toString(httpResponse.getEntity());
JSONArray jsonArray = new JSONArray(JsonFavouriteCategories);
for (int i = 0; i < jsonArray.length(); i++) {
Category genres = new Category();
JSONObject MyJsonObject = jsonArray.getJSONObject(i);
genres.setCateogry_id(Integer.parseInt(MyJsonObject.getString("id")));
genres.setCategory_Name(MyJsonObject.getString("nome_cat"));
genres.setSelected(Boolean.parseBoolean(MyJsonObject.getString("selected")));
MyArraylist.add(genres);
if (MyJsonObject.getString("selected").equals("true")) {
selectedCategories.add(MyJsonObject.getString("id"));
}
}
} catch (Exception e) {
e.printStackTrace();
}
return MyArraylist;
}
}
public class asyncTask_getCategories extends AsyncTask<Void, Void, Void> {
ProgressDialog dialog = new ProgressDialog(context);
@Override
protected void onPreExecute() {
dialog.setTitle("");
dialog.setMessage("Carregando...");
dialog.show();
array_list = new ArrayList<>();
categoryJsonParser = new FavouriteCategoriesJsonParser();
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... params) {
array_list = categoryJsonParser.getParsedCategories();
Log.i("ISIS"," "+array_list);
return null;
}
@Override
protected void onPostExecute(Void s) {
ListView mListViewBooks = (ListView) findViewById(R.id.category_listView);
final CategoryAdapter categoryAdapter = new CategoryAdapter(context, R.layout.row_category, array_list);
mListViewBooks.setAdapter(categoryAdapter);
Button button = (Button) findViewById(R.id.selectCategoryButton);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
categoriesCsv = FavouriteCategoriesJsonParser.selectedCategories.toString();
categoriesCsv = categoriesCsv.substring(1, categoriesCsv.length() - 1);
if (categoriesCsv.length() > 0) {
new asyncTask_insertUpdatefavouriteCategories().execute();
} else {
Toast.makeText(context, "Por favor, selecione um filtro.", Toast.LENGTH_SHORT).show();
}
}
});
super.onPostExecute(s);
dialog.dismiss();
}
public class asyncTask_insertUpdatefavouriteCategories extends AsyncTask<Void, Void, Void> {
String response;
@Override
protected Void doInBackground(Void... params) {
response = insertUpdateCall(categoriesCsv);
return null;
}
@Override
protected void onPostExecute(Void s) {
Toast.makeText(context, categoriesCsv, Toast.LENGTH_LONG).show();
Intent intent = new Intent(context, NovaActivity.class);
intent.putExtra("filtros", response);
startActivity(intent);
super.onPostExecute(s);
}
}
}
public static String insertUpdateCall(String categoriesCsv) {
String response = "";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("https://pensoupediu.000webhostapp.com/api/filtro/insertUpdateFavouriteCategories.php");
try {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id_usuario", "1"));
nameValuePairs.add(new BasicNameValuePair("favouriteCategories", categoriesCsv));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
response = EntityUtils.toString(httpResponse.getEntity());
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
}