Problem with checkbox and listview

0

How to make the checkbox click if it is 1 and uncheck if there is 0 in a listview?

public class AdminAcces extends ActionBarActivity {

    // Progress Dialog
    private ProgressDialog pDialog;

    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();

    ArrayList<HashMap<String, String>> userlist;


    // url to get all products list
    private static String url_all_empresas = "http://192.168.0.101/dtbd/get_all_user.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_PRODUCTS = "Usuario";
    private static final String TAG_DNI = "dni";
    private static final String TAG_NOMBRE = "nombre";
    private static final String TAG_Apellido = "apellido";
    private static final String TAG_ESTADO = "estado";

    // products JSONArray
    JSONArray products = null;

    ListView lista;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.admin_acces);


        // Hashmap para el ListView
        userlist = new ArrayList<HashMap<String, String>>();

        // Cargar los productos en el Background Thread
        new LoadAllProducts().execute();
        lista = (ListView) findViewById(R.id.ListaUsuarios);

        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);

    }//fin onCreate


class LoadAllProducts extends AsyncTask<String, String, String> {

    /**
     * Antes de empezar el background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(AdminAcces.this);
        pDialog.setMessage("Cargando Usuarios. Por favor espere...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    /**
     * obteniendo todos los productos
     * */
    protected String doInBackground(String... args) {
        // Building Parameters
        List params = new ArrayList();
        // getting JSON string from URL
        JSONObject json = jParser.makeHttpRequest(url_all_empresas, "GET", params);

        // Check your log cat for JSON reponse
        Log.d("All Products: ", json.toString());

        try {
            // Checking for SUCCESS TAG
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // products found
                // Getting Array of Products
                products = json.getJSONArray(TAG_PRODUCTS);

                // looping through All Products
                //Log.i("ramiro", "produtos.length" + products.length());
                for (int i = 0; i < products.length(); i++) {
                    JSONObject c = products.getJSONObject(i);

                    // Storing each json item in variable
                    String dni = c.getString(TAG_DNI);
                    String nombre = c.getString(TAG_NOMBRE);
                    String apellido = c.getString(TAG_Apellido);
                    String estado = c.getString(TAG_ESTADO);

                    // creating new HashMap
                    HashMap map = new HashMap();

                    // adding each child node to HashMap key => value
                    map.put(TAG_DNI, dni);
                    map.put(TAG_NOMBRE, nombre);
                    map.put(TAG_Apellido, apellido);
                    map.put(TAG_ESTADO,estado);

                    userlist.add(map);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after getting all products
        pDialog.dismiss();

        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            public void run() {
                /**
                 * Updating parsed JSON data into ListView
                 * */
                ListAdapter adapter = new SimpleAdapter(
                        AdminAcces.this,
                        userlist,
                        R.layout.vista_usuarios,
                        new String[] {
                                TAG_DNI,
                                TAG_NOMBRE,
                                TAG_Apellido,
                                TAG_ESTADO,
                        },
                        new int[] {
                                R.id.vistu_dni,
                                R.id.vistu_nombre,
                                R.id.vistu_apellido,
                                R.id.checkBox,
                        });
                lista.setAdapter(adapter);
            }
        });
    }
}
}

Vista_Usuarios.xml

<TextView
    android:id="@+id/vistu_dni"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    android:padding="10dp"
    android:paddingBottom="2dip"
    android:text="nombre"
    android:textColor="#333"
    android:textSize="12dp"
    android:textStyle="bold" />

<TextView
    android:id="@+id/vistu_nombre"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    android:layout_weight="0.01"
    android:padding="10dp"
    android:paddingBottom="2dip"
    android:text="nombre"
    android:textColor="#333"
    android:textSize="12dp"
    android:textStyle="bold" />


<TextView
    android:id="@+id/vistu_apellido"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    android:layout_weight="0.03"
    android:padding="10dp"
    android:paddingBottom="2dip"
    android:text="nombre"
    android:textColor="#333"
    android:textSize="12dp"
    android:textStyle="bold" />

<CheckBox
    android:id="@+id/checkBox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

adminacces.xml

<ListView
    android:id="@+id/ListaUsuarios"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="#fff"
    android:dividerHeight="3dp" />

When executing the 1 and the 0 write the text attribute of the checkbox and what is disabled is that it is marked if it is 1, but I do not know how to do this. I have tried several ways but they all throw me error. How do I do this?

    
asked by Yoel Mendoza 26.09.2017 в 23:21
source

1 answer

0

Well I recommend you do the following.

First, keep in mind that a CheckBox receives values booleanos to be marked, or not. When passing a String , the property that marks the CheckBox is not modified, if not the property that modifies the text of CheckBox . For your checkBox to be marked or not, you have to pass it Boolean values, not String type.

Knowing that, you have to modify the HashMap of your ArrayList to also accept values booleanos . This is achieved by making the values that your HasMap receive of type Object .

ArrayList<HashMap<String, Object>> userlist;

Now, you have to create a boolean variable that is assigned the value true if you get a 1 of the json and if you get a 0, you assign the value false (that's achieved with a conditional). This variable is the one that you will pass as a parameter to HasMap map .

// Con 'c.getString(TAG_ESTADO).equals("1")' evalúas el valor obtenido del
// json, si este es igual a 1, a la variable se le asigna el valor true, si
// es diferente a 1, se le asigna el valor false. 
boolean estado = c.getString(TAG_ESTADO).equals("1");

HasMap map = new HasMap();
...
map.put(TAG_ESTADO, estado);

Remember that by defining the value of HasMap of your ArrayList as type Object , it can receive values of any type, including String and booleanos .

Well, in your code it would look like this.

...

// Al ser de tipo Object el valor que recibe el HasMap
// este puede ser de cualquier tipo de dato
ArrayList<HashMap<String, Object>> userlist;

...

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.admin_acces);


    // Hashmap para el ListView
    userlist = new ArrayList<HashMap<String, String>>();

    ...

}//fin onCreate


class LoadAllProducts extends AsyncTask<String, String, String> {

    ...

    /**
     * obteniendo todos los productos
     * */
    protected String doInBackground(String... args) {

        ...

        try {

            ...

            if (success == 1) {

                ...

                for (int i = 0; i < products.length(); i++) {
                    JSONObject c = products.getJSONObject(i);

                    // Storing each json item in variable
                    String dni = c.getString(TAG_DNI);
                    String nombre = c.getString(TAG_NOMBRE);
                    String apellido = c.getString(TAG_Apellido);

                    // Con 'c.getString(TAG_ESTADO).equals("1")' evaluas el valor obtenido del
                    // json, si este es igual a 1, a la variable se le asigna el valor true, si
                    // es diferente a 1, se le asigna el valor false.
                    boolean estado = c.getString(TAG_ESTADO),equals("1");

                    // creating new HashMap
                    HashMap map = new HashMap();

                    // adding each child node to HashMap key => value
                    map.put(TAG_DNI, dni);
                    map.put(TAG_NOMBRE, nombre);
                    map.put(TAG_Apellido, apellido);
                    map.put(TAG_ESTADO,estado);

                    userlist.add(map);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    ...

}
    
answered by 27.09.2017 / 01:49
source