如何在线程内部访问变量?

时间:2017-03-20 04:34:03

标签: java android cloudinary

这是我的问题,用户需要上传个人资料图片,但我无法运行应用程序而不会出现任何错误,在logcat中我得到 NetworkOnMainThreadException 所以试图解决它的实现一个线程,但现在任何其他方法都无法访问该变量,我需要该值将其保存在我的数据库中。

我已经读过我需要使用Asysntask但我不知道该怎么做,请提前谢谢

这是我的代码:

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

2 个答案:

答案 0 :(得分:1)

由于Android不允许主(UI)线程上的网络com,您可以扩展AsyncTask以支持文件上传到Cloudinary。 然后,从onPostExecute处理上传响应(在您的数据库中存储信息,更新UI等)。 一个基本的例子 -

    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


    }
}

答案 1 :(得分:0)

以下是AsyncTask的一个示例:

private Player player;

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

假设Player类内部有一些网络操作。