setOnItemClickListener send post data

1

Hello, excuse my previous questions and delete them to avoid generating spam since they were not well posed.

This time I try to capture the data from a listview and send them via post. I'm using a class I found on the web called httpParser

public class HttpParse {

String FinalHttpData = "";
String Result ;
BufferedWriter bufferedWriter ;
OutputStream outputStream ;
BufferedReader bufferedReader ;
StringBuilder stringBuilder = new StringBuilder();
URL url;

public String postRequest(HashMap<String, String> Data, String HttpUrlHolder) {

    try {
        url = new URL(HttpUrlHolder);

        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

        httpURLConnection.setReadTimeout(14000);

        httpURLConnection.setConnectTimeout(14000);

        httpURLConnection.setRequestMethod("POST");

        httpURLConnection.setDoInput(true);

        httpURLConnection.setDoOutput(true);

        outputStream = httpURLConnection.getOutputStream();

        bufferedWriter = new BufferedWriter(

                new OutputStreamWriter(outputStream, "UTF-8"));

        bufferedWriter.write(FinalDataParse(Data));

        bufferedWriter.flush();

        bufferedWriter.close();

        outputStream.close();

        if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {

            bufferedReader = new BufferedReader(
                    new InputStreamReader(
                            httpURLConnection.getInputStream()
                    )
            );
            FinalHttpData = bufferedReader.readLine();
        }
        else {
            FinalHttpData = "Something Went Wrong";
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return FinalHttpData;
}

public String FinalDataParse(HashMap<String,String> hashMap2) throws UnsupportedEncodingException {

    for(Map.Entry<String,String> map_entry : hashMap2.entrySet()){

        stringBuilder.append("&");

        stringBuilder.append(URLEncoder.encode(map_entry.getKey(), "UTF-8"));

        stringBuilder.append("=");

        stringBuilder.append(URLEncoder.encode(map_entry.getValue(), "UTF-8"));

    }

    Result = stringBuilder.toString();

    return Result ;
}

}

I'm trying it this way,

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


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

    new LoadAllProducts().execute();
    lista = (ListView) findViewById(R.id.ListaUsuarios);

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

     lista.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

    **lista.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
            hashMap.equals(userlist.get(position));<----------??????
           new update().execute();
        }
    });**
}//fin onCreate

class update extends AsyncTask<String, String, String> {
    @Override

    protected void onPreExecute() {
        super.onPreExecute();

        progressDialog = ProgressDialog.show(AdminAcces.this, "Cargando Datos", null, true, true);
    }

    protected String doInBackground(String... params) {


        **finalResult = httpParse.postRequest(??????, url_all_update);**

        return finalResult;
    }
}

that function (httpparse.postRequest) only administers a hashmap list and this has me entangled I do not know how to convert the object that returns me setonclicklistener in hashpmap. Has someone done something similar? or do you have a suggestion on how to approach this case?

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




    /**
     * 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);
            }
        });




    }
}

}

    
asked by Yoel Mendoza 29.09.2017 в 03:37
source

1 answer

0

userlist.get(position) should return a HashMap<String,Object> :

HashMap<String,Object> map = userlist.get(position);

Now, the method postRequest expects a map of type HashMap<String,String> , so the 2 types are incompatible.

You have to cast (convert) the map to HashMap<String,Object> to HashMap<String,String> :

lista.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
            HashMap<String, String> map = (HashMap<String,String>) userlist.get(position));
           // ya puedes enviarle la variable map al metodo postRequest
          postRequest(map, null);
        }
    });

The code can be simplified since java can infer the type:

 //...
  HashMap map = userlist.get(position));
  postRequest(map, null);
    
answered by 29.09.2017 / 05:32
source