如何在Android中上传图片后更新活动

时间:2018-05-20 12:56:28

标签: android android-activity uiimageview

我有一项活动,用户可以更新与其个人资料相关的一些数据(例如,他的名字),他还可以上传新的个人资料图片。

更新操作后,用户将被重定向到新活动。 问题是当用户回到他的个人资料活动时,显示的图像仍然是旧的,而不是新的,而名称更新正确。

要查看新的个人资料图片,用户需要关闭该应用并再次打开。

我该如何解决这个问题? 我使用函数updateInfo(),但似乎无法正常工作。

请帮帮我吗?

    public class ProfileActivity extends BaseActivity implements ProfileView {

    @BindView(R.id.avatar)
    ImageView p_avatar;
    @BindView(R.id.ib_back)
    ImageButton ibBack;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.ib_right)
    ImageButton ibRight;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.et_fullname)
    EditText etFullname;
    @BindView(R.id.et_email)
    EditText etEmail;
    @BindView(R.id.btn_update)
    Button btnUpdate;
    @BindView(R.id.txt_logout)
    TextView txtLogout;
    @BindView(R.id.ll_main)
    LinearLayout llMain;

    private static final String TAG = "ProfileActivity";
    private String userName = null, userEmail = null;
    private ProfilePresenter profilePresenter;
    private Dialog dialog;
    Bitmap FixBitmap;
    Bitmap bitmap_to_save;
    ImageView ShowSelectedImage;
    String converted_img;
    ByteArrayOutputStream byteArrayOutputStream;
    byte[] byteArray ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile);
        ButterKnife.bind(this);
        byteArrayOutputStream = new ByteArrayOutputStream();

        init_view();
        upDateInfo();
    }


    private void init_view() {
        txtTitle.setText(R.string.profileActivity_title);
        ibRight.setImageResource(R.drawable.ic_edit);

        dialog = commonUtils.createCustomLoader(ProfileActivity.this, false);
        profilePresenter = new ProfilePresenterImpl(this);

        upDateInfo();
    }

    private void upDateInfo() {
        if (Conts.USERINFO != null) {
            String subName = firstTwoChar(Conts.USERINFO.getName());
           // Picasso.get().load("http://www.server.com/uploads/avatars/73.png").transform(transformation).into(p_avatar);

            final int radius = 30;
            final int margin = 1;
            final RoundedCornersTransformation transformation = new RoundedCornersTransformation(radius, margin);
            Picasso.get().load("http://www.server.com/uploads/avatars/"+Conts.USERINFO.getId()).transform(transformation).into(p_avatar);


            etFullname.setText(Conts.USERINFO.getName().toLowerCase());
            etFullname.setEnabled(false);
            etEmail.setText(Conts.USERINFO.getEmail());
            etEmail.setEnabled(false);
            btnUpdate.setVisibility(View.INVISIBLE);
        }
    }

    @OnClick({R.id.ib_back, R.id.ib_right, R.id.btn_update, R.id.txt_logout, R.id.avatar})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ib_back:
                onBackPressed();
                break;
            case R.id.ib_right:
                etFullname.setEnabled(true);
                etFullname.setSelection(etFullname.getText().toString().length());
                btnUpdate.setVisibility(View.VISIBLE);
                Log.d(TAG, "validate ID: " + Conts.USERINFO.getId());
                return;
            case R.id.avatar:
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent, "Select Image From Gallery"), 1);
                return;
            case R.id.btn_update:
                if (validate()) {
                    if (!commonUtils.isNetworkAvailable()) {
                        Toast.makeText(this, "No Internet Connection", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    profilePresenter.dataListAPI(Conts.USERINFO.getId(), userName, Conts.USERINFO.getEmail(), converted_img);
                }
                break;
            case R.id.txt_logout:
                get_dialog();
                break;
        }
    }


    @Override
    protected void onActivityResult(int RC, int RQC, Intent I) {

        super.onActivityResult(RC, RQC, I);

        if (RC == 1 && RQC == RESULT_OK && I != null && I.getData() != null) {

            Uri uri = I.getData();

            try {

                FixBitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
                bitmap_to_save = scaleBitmapAndKeepRation(FixBitmap, 320, 320);


                RoundedBitmapDrawable roundedBitmapDrawable = RoundedBitmapDrawableFactory.create(getResources(), bitmap_to_save);
                final float roundPx = (float) bitmap_to_save.getWidth() * 0.15f;
                roundedBitmapDrawable.setCornerRadius(roundPx);
                roundedBitmapDrawable.setAntiAlias(true);
                p_avatar.setImageDrawable(roundedBitmapDrawable);


                bitmap_to_save.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);

                byteArray = byteArrayOutputStream.toByteArray();

                converted_img = Base64.encodeToString(byteArray, Base64.DEFAULT); // this is the image string to send to the server!


            } catch (IOException e) {

                e.printStackTrace();
            }
        }
        else {
            Toast.makeText(this, "An error has occurred!", Toast.LENGTH_SHORT).show();

        }
    }

    public static Bitmap scaleBitmapAndKeepRation(Bitmap TargetBmp, int reqHeightInPixels, int reqWidthInPixels)
    {
        Matrix m = new Matrix();
        m.setRectToRect(new RectF(0, 0, TargetBmp.getWidth(), TargetBmp.getHeight()), new RectF(0, 0, reqWidthInPixels, reqHeightInPixels), Matrix.ScaleToFit.CENTER);
        Bitmap scaledBitmap = Bitmap.createBitmap(TargetBmp, 0, 0, TargetBmp.getWidth(), TargetBmp.getHeight(), m, true);
        return scaledBitmap;
    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    private void get_dialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setCancelable(false);

        View view = LayoutInflater.from(this).inflate(R.layout.dialog_logout, null);

        builder.setView(view);
        final AlertDialog alertDialog = builder.create();
        alertDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        alertDialog.show();

        TextView txtyes, txtno;

        txtyes = view.findViewById(R.id.txt_yes);
        txtno = view.findViewById(R.id.txt_no);

        txtyes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
                sharedPref.setBoolean(Conts.IsLogin, false);
                sharedPref.clearAllPref();
                Conts.USERINFO = null;

                Intent iLogin = new Intent(ProfileActivity.this, MainActivity.class);
                iLogin.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(iLogin);
            }
        });

        txtno.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
            }
        });
    }

    public String firstTwoChar(String str) {
        return str.length() < 2 ? str : str.substring(0, 2);
    }

    @Override
    public void showLoader() {
        dialog.show();
    }

    @Override
    public void hideLoader() {
        if (dialog != null)
            dialog.dismiss();
    }

    @Override
    public void showError(String msg) {
        Snackbar snackbar = Snackbar
                .make(llMain, msg, Snackbar.LENGTH_INDEFINITE)
                .setAction("RETRY", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //  nothing anything
                    }
                });

        snackbar.show();

        // Changing message text color
        snackbar.setActionTextColor(Color.RED);

        // Changing action button text color
        View sbView = snackbar.getView();
        TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
        textView.setTextColor(Color.WHITE);
        snackbar.show();
    }

    @Override
    public Context getContextAppp() {
        return this;
    }

    @Override
    public void onBackPress() {

    }

    @Override
    public void successResponse(Data data) {
        if (data != null) {
            Toast.makeText(this, "Profile updated successfully", Toast.LENGTH_SHORT).show();

            UserInfo userInfo = new UserInfo(data.getId(), data.getName(), data.getEmail());
            Conts.USERINFO = userInfo;
            String userinfo = gson.toJson(Conts.USERINFO, UserInfo.class);
            sharedPref.setDataInPref(Conts.UserInfo, userinfo);

            startActivity(getIntent());
            Intent iPlace = new Intent(ProfileActivity.this, AddPlaceActivity.class);
            iPlace.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
            Toast.makeText(this, "Profile saved!", Toast.LENGTH_SHORT).show();
            startActivity(iPlace);



        }
    }

    @Override
    public void errorResponce(String msg) {
        if (msg != null) {
            Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
        }
    }

    private boolean validate() {
        commonUtils.hideKeyboard(this);

        if (etFullname.getText().toString().trim().isEmpty()) {
            Toast.makeText(this, "Please enter Fullname", Toast.LENGTH_SHORT).show();
        } else if (etFullname.getText().toString().trim().length() <= 2) {
            Toast.makeText(this, "Minimum 3 character require", Toast.LENGTH_SHORT).show();
        } else if (etFullname.getText().toString().trim().length() > 30) {
            Toast.makeText(this, "Maximum 30 character require", Toast.LENGTH_SHORT).show();
        }
        /*else if (etEmail.getText().toString().trim().isEmpty()) {
            Toast.makeText(this, "Please enter Email", Toast.LENGTH_SHORT).show();
        } else if (!validation.checkEmail(etEmail)) {
            Toast.makeText(this, "Please enter valid Email", Toast.LENGTH_SHORT).show();
        }
*/
        if (!etFullname.getText().toString().trim().isEmpty() && etFullname.getText().toString().trim().length() > 2 && etFullname.getText().toString().trim().length() <= 30) {
            userName = etFullname.getText().toString().trim();
        } else {
            userName = null;
        }

        /*if (!etEmail.getText().toString().trim().isEmpty() && validation.checkEmail(etEmail)) {
            userEmail = etEmail.getText().toString().trim();
        } else {
            userEmail = null;
        }
*/
        if (userName != null /*&& userEmail != null*/) {
            Log.d(TAG, "validate: " + userName);
            return true;
        } else {
            return false;
        }
    }
}

2 个答案:

答案 0 :(得分:1)

当您返回到个人资料活动时,您的应用程序的任务堆栈将恢复已在内存中的个人资料活动。因此,您应该通知您的个人资料活动它已更新。在您的个人资料活动的onStart回调中,检查它是否已更新。如果是这样加载新图像。简而言之,将upDateInfo()方法放在onStart()中。

答案 1 :(得分:1)

更新信息后,在callback方法onResponse中,您需要在成功完成信息更新后调用updateInfo()在您的用户界面上进行更新。确保您从服务器提供新值,尤其是static变量,因为只要应用程序处于活动状态,它们就会保留值。如果您不使用新值更新它们,它们将保留旧值。

目前,您正在尝试仅在需要创建onCreate()时调用的Activity中更新信息。在这种情况下,只有当您在Back按钮上按Home按钮退出并再次输入应用程序时,它才会在操作系统销毁应用程序之前无法正常工作。

您还可以使用onResume方法,该方法在暂停时返回Activity时调用,并且在您已经退出时创建新Activity时会发生这种情况。