Israyane Nayara
Israyane Nayara

Reputation: 49

CheckBox ListView Mysql

I am three days trying to solve this problem with my filter using checkbox and a ListView.

In this code I select the checkboxes the first time and they are listed correctly with the IDs of each selected category and review the IDs for another Activity called NovaActivity. OK? So far so good.

The problem is the following when I re-open the Filters Activity to make a new same unchecking checkbox with the already listed filters it keeps going to NovaAcitivty even though they are unmarked.

EX:  1st filter selects 1 and 2;

When I send it to another it goes the 1,2;

 2nd filter I select 1 and uncheck checkbox 2;

When I send it to another it goes the 1,1,2;

How do I solve this?

NOTE: important the second time so said that I open the Filters activity the already selected checkboxes are already premarked because I write them to my remote MySQL database and I retrieve them.

If I was not very clear can ask questions at will, thank you any help already.

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;

    }

}

Upvotes: 0

Views: 59

Answers (1)

Udit
Udit

Reputation: 1037

Use Set instead of ArrayList:

public static Set<String> selectedCategories = new HashSet<>();

This will ensure that your selectedCategories has no duplicates.

Upvotes: 1

Related Questions