Friday 19 May 2017

Send object with volley

I have a daubt that is confusing me, i am working with android/nodejs/postgreSQL, and i was able to send http requests to the server and store the information.

But i was doing that without the considering good practices, that is to have a model associate with the user.

So basicy i get the data from the register form do a simple params.put with the form information and send the data with key/value information.

But now i want to have a User Model and pass the user model trought that params.put and do the same stuff.

Is this considering a good practice?, or should i just forget the User model and do the stuff like this?

here is what i am doing at the moment:

 public void register(View view) {

        //get form data
        final String username = usernameTxt.getText().toString();
        String password = passwordTxt.getText().toString();
        String email = emailTxt.getText().toString();
        Log.d("email",String.valueOf(isValidEmail(email)));

        if (!isValidEmail(email)) {
            emailTxt.setError("Invalid Email");
        }

        //inicialize a map with pair key value
        final Map<String, String> params = new HashMap<String, String>();

        // Add form fields to the map
        params.put("username", username);
        params.put("email", email);
        params.put("password", password);

        /**
         * Efetua um pedido ao servidor
         *
         * @param URl    url do servidor a aceder
         * @param JSONObject objeto json a ser retornado através do access point
         *
         */
        JsonObjectRequest request = new JsonObjectRequest(URL, new JSONObject(params),
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        //TODO verificar o status code da resposta apenas deverá registar login caso seja 200
                        //verifica
                        Log.d("response",response.toString());
                        Intent i = new Intent(Register.this,Login.class);
                        i.putExtra("username",username);
                        startActivity(i);
                        finish();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                String body;
                //get response body and parse with appropriate encoding
                if(error.networkResponse.data!=null) {
                    String statusCode = String.valueOf(error.networkResponse.statusCode);
                    try {
                        body = new String(error.networkResponse.data,"UTF-8");
                        JSONObject jsonObj = new JSONObject(body);
                        Log.d("body",String.valueOf(jsonObj.get("message")));
                        showToast(String.valueOf(jsonObj.get("message")));
                    } catch (UnsupportedEncodingException e) {
                        showToast("You need to connect to the internet!");
                    } catch (JSONException e) {
                        Log.d("json:","problems decoding jsonObj");
                    }
                }
                //do stuff with the body...
            }


        });

        request.setRetryPolicy(new DefaultRetryPolicy(60000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

queue.add(request); // adiciona a request à queue pronta a ser executada

}



via Cris dois

No comments:

Post a Comment