0

Tengo un problema, necesito que al momento de dar clic en guardar se envíe la url de la imagen que subí a cloudinary,la imagen si se sube pero no se por que me regresa null, el código en si no regresa error, en este log Log.d("Ruta en botón guardar",String.valueOf(ruta)); me doy cuenta que manda null cualquier ayuda seria genial muchas gracias

public class edit_profile_activity extends AppCompatActivity 
{
    private static int RESULT_LOAD_IMG = 1;
    String imgDecodableString;
    Button btngudar;
    Map uploadResult;
String ruta;
    Uri selectedImage;
    Map config = new HashMap();
    ImageView imgView;

    Button bu=null, guardar;


    EditText editName, editEmail, editLastName, editNick, showDate;
    TextView txtNameTop, txtNickTop;
    RadioButton rbMale,rbFemale;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_profile);

        //bu = (Button) findViewById(R.id.btnLogout);
        guardar = (Button) findViewById(R.id.btnguardar);
        rbMale = (RadioButton) findViewById(R.id.rbMale);
        rbFemale = (RadioButton) findViewById(R.id.rbFemale);

        config.put("cloud_name", "*********");
        config.put("api_key", "1234567890abcde");
        config.put("api_secret","123456789012345678901234567");

        new PlifRequestBase(edit_profile_activity.this) {

            @Override
            public JsonObject onHttpOk(JsonObject response) throws JSONException {
                JsonObject data;
                data = response;

                //En esta parte se declaran los botones, textos y campos de texto con las respectivas variables
                rbMale = (RadioButton) findViewById(R.id.rbMale);
                rbFemale = (RadioButton) findViewById(R.id.rbFemale);

                editLastName = (EditText) findViewById(R.id.editapellido);
                editEmail = (EditText) findViewById(R.id.editcorreo);
                editName = (EditText) findViewById(R.id.editnombre);
                editNick = (EditText) findViewById(R.id.editnick);
                showDate = (EditText) findViewById(R.id.showDate);


                txtNameTop = (TextView) findViewById(R.id.txtNombreA);
                txtNickTop = (TextView) findViewById(R.id.nickname);

                //se toman los valores desde el JsonObject
                final String name = data.get("first_name").getAsString();
                final String lastName = data.get("last_name").getAsString();
                final String emailUser = data.get("email").getAsString();
                //final String nick= data.get("nick").getAsString();
                //final String nick= data.get("nick").toString();
                //final String nick= String.valueOf(data.get("nick").getAsString().equals(""));
                final String nick = data.get("nick") != JsonNull.INSTANCE ? data.get("nick").getAsString() : null;
                final int sex = data.get("sex").getAsInt();

                //se ponen en los respectivos textos y edit text lo consultado
                edit_profile_activity.this.runOnUiThread(new Runnable() {
                    public void run() {
                        txtNameTop.setText(name + " " + lastName);
                        //txtNickTop.setText(nick);
                        editName.setText(name);
                        editEmail.setText(emailUser);
                        editLastName.setText(lastName);
                        if (nick == null)
                        {
                            editNick.setText("");

                        }
                        if(nick != "false") {
                            editNick.setText(nick);
                        }
                        //    showDate.setText(birthDate);
                    }
                });

                Log.d("Nombre", name + " " + lastName);
                Log.d("Correo", emailUser);


                return data;
            }

            @Override
            public void onHttpCreate(JsonObject response) throws JSONException {

            }

            @Override
            public void onHttpUnprocessableEntity(JsonObject response) throws JSONException {
                this.cancel(true);
                final String error = response.get("errors").toString();
                edit_profile_activity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(edit_profile_activity.this.getApplicationContext(), error, Toast.LENGTH_LONG).show();
                    }
                });
            }
        }.execute("user/profile", "GET");

        //------------------------------------------------------------------------------------------------------------------

        //se hacen los cambios en la api a partir de la accion del boton guardar
        guardar.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                Thread thread = new Thread(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        try
                        {
                            Cloudinary cloudinary = new Cloudinary(config);
                            uploadResult =  cloudinary.uploader().upload(imgDecodableString, ObjectUtils.emptyMap());
                            ruta = String.valueOf(uploadResult.get("url"));
                            Log.d("Ruta",String.valueOf(ruta));
                            Log.d("RESULTADOS",String.valueOf(uploadResult));
                            Log.d("URL",String.valueOf(uploadResult.get("url")));

                        } catch (Exception e)
                        {
                            e.printStackTrace();
                        }
                    }
                });
                thread.start();

                Log.d("Ruta en boton guardar",String.valueOf(ruta));

                String setName = editName.getText().toString();
                String setEmail= editEmail.getText().toString();
                String setLastName= editLastName.getText().toString();
                String setNick = editNick.getText().toString();
                String setBirthDate= showDate.getText().toString();

                Toast.makeText(edit_profile_activity.this, "Se ha guardado correctamente", Toast.LENGTH_SHORT).show();

                if (setNick == null)
                {
                    editNick.setText("nickname");

                }
                if(setNick != "")
                {
                    editNick.setText("");
                }

                int sex = 0;

                if (rbMale.isChecked())
                {
                    sex=1;
                }
                else if (rbFemale.isChecked())
                {
                    sex=2;
                }else
                {
                    sex=3;
                }

                new PlifRequestBase(edit_profile_activity.this){

                    @Override
                    public JsonObject onHttpOk(JsonObject response) throws JSONException {
                        JsonObject data;
                        data = response;
                        if (response.equals(200)){
                            Toast.makeText(edit_profile_activity.this, "Se ha guardado correctamente", Toast.LENGTH_SHORT).show();
                        }
                        return data;
                    }

                    @Override
                    public void onHttpCreate(JsonObject response) throws JSONException {


                        try {
                            Toast.makeText(edit_profile_activity.this, "Se ha guardado correctamente", Toast.LENGTH_SHORT).show();
                        } catch (IllegalStateException e) {

                        }
                    }

                    @Override
                    public void onHttpUnprocessableEntity(JsonObject response) throws JSONException {
                        this.cancel(true);
                        final String error = response.get("errors").toString();
                        edit_profile_activity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(edit_profile_activity.this.getApplicationContext(), error, Toast.LENGTH_LONG).show();
                            }

                        });

                    }

                }.execute("user/profile","PUT","user",
                        "email", setEmail,
                        "first_name", setName,
                        "last_name", setLastName,
                        "nick", setNick,
                        "birthdate", setBirthDate,
                        "sex", String.valueOf(sex),
                        "current_avatar", String.valueOf(ruta)
                );

                Log.d("Envía:", setBirthDate);
                Log.d("Sexo", String.valueOf(sex));

                    new PlifRequestBase(edit_profile_activity.this) {

                    @Override
                    public JsonObject onHttpOk(JsonObject response) throws JSONException {
                        JsonObject data;
                        data = response;

                        //En esta parte se declaran los botones, textos y campos de texto con las respectivas variables
                        rbMale = (RadioButton) findViewById(R.id.rbMale);
                        rbFemale = (RadioButton) findViewById(R.id.rbFemale);

                        editLastName = (EditText) findViewById(R.id.editapellido);
                        editEmail = (EditText) findViewById(R.id.editcorreo);
                        editName = (EditText) findViewById(R.id.editnombre);
                        editNick = (EditText) findViewById(R.id.editnick);

                        txtNameTop = (TextView) findViewById(R.id.txtNombreA);
                        txtNickTop = (TextView) findViewById(R.id.nickname);

                        //se toman los valores desde el JsonObject
                        final String name = data.get("first_name").getAsString();
                        final String last_name = data.get("last_name").getAsString();
                        final String email_user = data.get("email").getAsString();
                        //final String nick= data.get("nick").toString();
                        //final String nick= String.valueOf(data.get("nick").getAsString().equals(""));
                        final String nick = data.get("nick") != JsonNull.INSTANCE ? data.get("nick").getAsString() : null;
                        final int sex = data.get("sex").getAsInt();

                        //se ponen en los respectivos textos y edit text lo consultado
                        edit_profile_activity.this.runOnUiThread(new Runnable() {
                            public void run() {
                                txtNameTop.setText(name + " " + last_name);
                                //txtNickTop.setText(nick);
                                editName.setText(name);
                                editEmail.setText(email_user);
                                editLastName.setText(last_name);
                                if (nick == null)
                                {
                                    editNick.setText("");

                                }
                                if(nick != "false") {
                                    editNick.setText(nick);
                                }
                            }
                        });

                        Log.d("Nombre", name + " " + last_name);
                        Log.d("Correo", email_user);


                        return data;
                    }

                    @Override
                    public void onHttpCreate(JsonObject response) throws JSONException {

                    }

                    @Override
                    public void onHttpUnprocessableEntity(JsonObject response) throws JSONException {
                        this.cancel(true);
                        final String error = response.get("errors").toString();
                        edit_profile_activity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(edit_profile_activity.this.getApplicationContext(), error, Toast.LENGTH_LONG).show();
                            }
                        });
                    }
                }.execute("user/profile", "GET");


            }
        });

    }


    public void logout(View view){
        SharedPreferences sharedpreferences = getSharedPreferences("PlifMx", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedpreferences.edit();
        editor.clear();
        editor.commit();
        Intent intent = new Intent(edit_profile_activity.this,MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
        finish();
    }


    public void loadImagefromGallery(View view) {
        // Create intent to Open Image applications like Gallery, Google Photos
        Intent galleryIntent = new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        // Start the Intent
        startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
    }
    public void subirImg ()
    {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try {
            // When an Image is picked
            if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
                    && null != data) {
                // Get the Image from data

                Uri selectedImage = data.getData();
                String[] filePathColumn = { MediaStore.Images.Media.DATA };

                // Get the cursor
                Cursor cursor = getContentResolver().query(selectedImage,
                        filePathColumn, null, null, null);
                // Move to first row
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                imgDecodableString = cursor.getString(columnIndex);
                cursor.close();

                final ImageView imgView = (ImageView) findViewById(R.id.circleImageView);
                // Set the Image in ImageView after decoding the String
                imgView.setImageBitmap(BitmapFactory.decodeFile(imgDecodableString));

            } else {
                Toast.makeText(this, "No seleccionaste una imagen",
                        Toast.LENGTH_LONG).show();
            }
        } catch (Exception e) {
            Toast.makeText(this, "Ocurrio algo", Toast.LENGTH_LONG)
                    .show();
        }
    }
}
1
  • 2
    deberías despersonalizar tus credenciales antes de publicar tu código ;) Commented el 18 mar. 2017 a las 18:37

2 respuestas 2

0

Revisa en debug si tienes una NetworkOnMainThreadException. No he usado Cloudinary, pero supongo que uploader().upload(...) toma acceso al internet.

Si es así vas a tener que poner este código en un AsyncTask para funcionar. La razón es que Android ya desde 3.0 no permite acceso directo a la red en la hebra principal.

1
  • jajaja no me di cuenta de mis credenciales, gracias, y gracias por el tip ahorita lo checo con el AsynTask :) Commented el 18 mar. 2017 a las 18:55
0

Recuerda que estas usando un Thread para obtener el valor de ruta, si ejecutas un Thread e inmediatamente de iniciarlo deseas obtener este valor, puede ser que aún no haya terminado la petición y la obtención del valor, lo recomendable es realizarlo dentro de la definición del Thread.

Thread thread = new Thread(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        try
                        {
                            Cloudinary cloudinary = new Cloudinary(config);
                            uploadResult =  cloudinary.uploader().upload(imgDecodableString, ObjectUtils.emptyMap());
                            ruta = String.valueOf(uploadResult.get("url"));
                            Log.d("Ruta",String.valueOf(ruta));
                            Log.d("RESULTADOS",String.valueOf(uploadResult));
                            Log.d("URL",String.valueOf(uploadResult.get("url")));


//*** obten aquí en valor.
Log.d("Ruta en boton guardar",String.valueOf(ruta));

                        } catch (Exception e)
                        {
                            e.printStackTrace();
                        }
                    }
                });
                thread.start();

               // Log.d("Ruta en boton guardar",String.valueOf(ruta));

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.