0

Here is my problem, the user needs to upload a profile image, but I can't run the application without getting any error, in the logcat I get the NetworkOnMainThreadException so tried to solve it implementing a thread but now the variable can't be accessed by any other method, and I need that value to save it in my database.

I have read that I need to use Asysntask but I don't know how to do it, thank you in advance

Here is my code:

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 save;

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

        save= (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;

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

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

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

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


        save.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());
                            route= String.valueOf(uploadResult.get("url"));
                            Log.d("Route",String.valueOf(route));
                           Log.d("URL",String.valueOf(uploadResult.get("url")));

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

                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, "Data saved", 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, "Data saved", Toast.LENGTH_SHORT).show();
                        }
                        return data;
                    }

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


                        try {
                            Toast.makeText(edit_profile_activity.this, "Data saved", 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(route)
                );

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

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

    @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();
        }
    }
}
Phantom_strike
  • 149
  • 2
  • 10

2 Answers2

1

As Android doesn't allow network com on the main (UI) thread, you can extend the AsyncTask to support file uploads to Cloudinary. Then, handle the upload response (store info in your DB, update the UI, etc.) from onPostExecute. A basic example -

    class UploadTask extends AsyncTask<String, String, Map<String, String>> {

    private Exception exception;

    protected Map<String, String> doInBackground(String... params) {
        Map response = ObjectUtils.asMap();
        try{

            response = cloudinary.uploader().upload(<Image file>,
                    ObjectUtils.asMap("resource_type", "image",
                    "public_id", <"somePublicId">));

        }catch (IOException e){
            System.out.println(e.getMessage());
        }
        return response;
    }

    protected void onPostExecute(Map<String, String> response) {
        // TODO: handle the response


    }
}
Maor.G
  • 440
  • 2
  • 5
0

Here is an example of AsyncTask:

private Player player;

private void connect_to_server() {
    AsyncTask.execute(new Runnable() {
        @Override
        public void run() {
            player = new Player();
            player.start();
        }
    });
}

Suppose that the Player class has some network operations inside.

JJHH
  • 67
  • 1
  • 9