首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >当我们从另一个活动返回时,如何刷新活动的数据?

当我们从另一个活动返回时,如何刷新活动的数据?
EN

Stack Overflow用户
提问于 2017-10-05 14:15:01
回答 4查看 7.7K关注 0票数 2

在这里,我想制作一个有profile activity的应用程序,用户可以在其中看到他/她的信息,而activity有一个按钮来编辑配置文件。单击按钮时,将打开新的活动,用户可以在那里编辑信息&按保存按钮,然后返回到profile活动。因此,我的问题是如何使用编辑的信息重新加载概要文件活动?

这是我的编辑档案活动

代码语言:javascript
复制
public class EditProfileActivity extends AppCompatActivity implements View.OnClickListener  {

Button save_profile;
RadioGroup radioGroup;
EditText user_name,user_email,user_phone,user_addhar_number,birthdate;
ImageView user_profile_bg,user_profile,back_arrow;

private static final int RESULT_LOAD_IMAGE=24;

//db_details
String db_email="",db_name="",db_birthday,db_phone=" ";
String db_profile_pic = "",db_profile_pic_bg = "",db_token="";

String email,phone,name,profile_pic_url=" ",gender=" ",birthday;
String token="",addhar_number,new_profile_pic_url;

private double currentLatitude;
private double currentLongitude;

private boolean check_flag = false;

byte[] profile_pic_array;
byte[] profile_pic_bg_array;
Bitmap bitmap_profile= null,bitmap_bg=null;

Calendar mycalender;
ImageView CurrentImageView = null;
int choosebutton;
private long imei_number = 0;

private ProgressDialog pDialog;

Bitmap selectedImage = null;
Bitmap selectedImage2 = null;

SQliteHandler db;

private static final String TAG = EditProfileActivity.class.getSimpleName();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_edit_profile);
    user_name =(EditText)findViewById(R.id.et_user_name);
    user_email =(EditText)findViewById(R.id.et_user_email);
    user_phone =(EditText)findViewById(R.id.et_user_phone);
    user_addhar_number =(EditText)findViewById(R.id.et_user_aadhar_number);
    birthdate = (EditText)findViewById(R.id.et_user_birthday);

    user_profile_bg =(ImageView)findViewById(R.id.header_cover_image);
    user_profile=(ImageView) findViewById(R.id.user_profile_photo);
    back_arrow = (ImageView)findViewById(R.id.iv_back);

    mycalender = Calendar.getInstance();

    save_profile =(Button)findViewById(R.id.btn_profile_save);

    db=new SQliteHandler(getApplicationContext());

    pDialog = new ProgressDialog(this);
    pDialog.setCancelable(false);




    back_arrow.setOnClickListener(this);
    save_profile.setOnClickListener(this);

    user_profile_bg.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            check_flag =true;
           CurrentImageView = (ImageView) v;
            Intent gallery = new Intent(Intent.ACTION_PICK,
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(gallery,RESULT_LOAD_IMAGE);
            choosebutton=1;
        }
    });

    user_profile.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            check_flag =true;
           CurrentImageView = (ImageView) v;
            Intent gallery = new Intent(Intent.ACTION_PICK,
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(gallery,RESULT_LOAD_IMAGE);
            choosebutton=2;
        }
    });

    final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                              int dayOfMonth) {
            // TODO Auto-generated method stub
            mycalender.set(Calendar.YEAR, year);
            mycalender.set(Calendar.MONTH, monthOfYear);
            mycalender.set(Calendar.DAY_OF_MONTH, dayOfMonth);
            updateLabel();
        }
    };
        if(db_birthday != null && db_birthday != " " ){
            birthdate.setText(db_birthday);
            birthdate.setClickable(false);
        }else {
            birthdate.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    new DatePickerDialog(EditProfileActivity.this, date, mycalender.get(Calendar.YEAR),
                            mycalender.get(Calendar.MONTH), mycalender.get(Calendar.DAY_OF_MONTH)).show();
                    }
            });
        }


    Intent data = getIntent();
    if(data.hasExtra("name") && data.hasExtra("email") && data.hasExtra("profile_url") && data.hasExtra("token")) {
        name = data.getStringExtra("name");
        email = data.getStringExtra("email");
        profile_pic_url = data.getStringExtra("profile_url");
        token = data.getStringExtra("token");
        currentLatitude = data.getDoubleExtra("latitude",0.0);
        currentLongitude = data.getDoubleExtra("longitude",0.0);
    }else if(data.hasExtra("name") && data.hasExtra("email") && data.hasExtra("profile_url") && data.hasExtra("token")){
        name = data.getStringExtra("name");
        phone = data.getStringExtra("phone");
        profile_pic_url = data.getStringExtra("profile_url");
        token = data.getStringExtra("token");
        currentLatitude = data.getDoubleExtra("latitude",0.0);
        currentLongitude = data.getDoubleExtra("longitude",0.0);
    }


    //load user data from sqlite
    if(email != null && email !=" ") {
        HashMap<String, String> user = db.getuserdetails(email);
        db_name = user.get("name");
        db_email = user.get("email");
        db_phone = user.get("phone");
        db_profile_pic = user.get("profile_pic");
        db_profile_pic_bg = user.get("profile_pic_bg");
        birthday = user.get("birthday");
        db_token= user.get("token");
    }else if(phone != null && phone !=" "){
        HashMap<String, String> user = db.getuserdetails(phone);
        db_name = user.get("name");
        db_email = user.get("email");
        db_phone = user.get("phone");
        db_profile_pic = user.get("profile_pic");
        db_profile_pic_bg = user.get("profile_pic_bg");
        birthday = user.get("birthday");
        db_token= user.get("token");
    }

    user_name.setText(name);
    if ((email != " " && email != null)&&(Patterns.EMAIL_ADDRESS.matcher(email).matches())){
        user_email.setText(email);
        KeyListener keyListener = user_email.getKeyListener();
        user_email.setKeyListener(null);
    }else if((phone !=" " && phone !=null)&& (Pattern.compile("^[789]\\d{9}$").matcher(phone).matches())) {
        user_phone.setText("+91 " + phone);
        KeyListener keyListener = user_phone.getKeyListener();
        user_phone.setKeyListener(null);
    }

    Glide.with(this)
            .load(profile_pic_url)
            .placeholder(R.drawable.default_avtar)
            .centerCrop()
            .diskCacheStrategy(DiskCacheStrategy.ALL)
            .bitmapTransform(new CropCircleTransformation(this))
            .into(user_profile);

    radioGroup =(RadioGroup)findViewById(R.id.gender_rg);
    radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, @IdRes int i) {
            RadioButton rb=(RadioButton)radioGroup.findViewById(i);
            switch (i){
                case R.id.rb_male:
                    gender = "male";
                    break;

                case R.id.rb_female:
                    gender = "female";
                    break;
            }
        }
    });
}

@Override
public void onClick(View v) {
    switch (v.getId()){
        case R.id.btn_profile_save:
            name = user_name.getText().toString();
            email = user_email.getText().toString();
            phone = user_phone.getText().toString();
            addhar_number = user_addhar_number.getText().toString();
            birthday = birthdate.getText().toString();

            if(!check_flag) {
                if (profile_pic_url != null && !profile_pic_url.equals(" ") && !profile_pic_url.isEmpty()) {
                    BitMap m = new BitMap();
                    try {
                        bitmap_profile = m.execute(profile_pic_url).get();
                        bitmap_bg = BitmapFactory.decodeResource(getResources(),R.drawable.beach);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (ExecutionException e) {
                        e.printStackTrace();
                    }
                    profile_pic_array = bitmapToByte(bitmap_profile);
                    profile_pic_bg_array = bitmapToByte(bitmap_bg);

                } else {
                    bitmap_profile = BitmapFactory.decodeResource(getResources(),R.drawable.default_avtar);
                    bitmap_bg = BitmapFactory.decodeResource(getResources(),R.drawable.beach);
                    profile_pic_array = bitmapToByte(bitmap_profile);
                    profile_pic_bg_array = bitmapToByte(bitmap_bg);
                }
            }else{
                profile_pic_array = bitmapToByte(selectedImage2);
                profile_pic_bg_array = bitmapToByte(selectedImage);
            }
            String profile_pic= null;
            String profile_pic_bg = null;
            profile_pic = Base64.encodeToString(profile_pic_array,Base64.DEFAULT);
            profile_pic_bg = Base64.encodeToString(profile_pic_bg_array,Base64.DEFAULT);

            db.updateUser(name,email,phone,addhar_number,gender,profile_pic,profile_pic_bg,birthday,token);
            updateProfile();

            break;

        case R.id.iv_back:
            Intent home = new Intent(getApplicationContext(),ProfileActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(home);
            break;
    }
}

private void updateLabel() {
    String myFormat = "dd/mm/yyyy"; //In which you need put here
    SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.UK);

    birthdate.setText(sdf.format(mycalender.getTime()));
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && data != null) {
        Uri selected_image = data.getData();
        new_profile_pic_url = selected_image.toString();
        Log.d("new profile_pic_url",new_profile_pic_url);
            String[] filePath = { MediaStore.Images.Media.DATA };
            Cursor cursor = getContentResolver().query(selected_image,filePath,null,null,null);
            cursor.moveToFirst();
            String imagePath = cursor.getString(cursor.getColumnIndex(filePath[0]));
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inPreferredConfig = Bitmap.Config.ARGB_8888;
            if(choosebutton==1) {
                selectedImage = BitmapFactory.decodeFile(imagePath, options);
                Glide.with(this)
                        .load(selected_image)
                        .crossFade()
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        .into(CurrentImageView);

            }else if(choosebutton ==2){
                selectedImage2 = BitmapFactory.decodeFile(imagePath, options);
                Glide.with(this)
                        .load(selected_image)
                        .centerCrop()
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        .bitmapTransform(new CropCircleTransformation(this))
                        .into(CurrentImageView);

            }
            cursor.close();
    }
}
public byte[] bitmapToByte(Bitmap bitmap){
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG,0,baos);

    return baos.toByteArray();
} private class BitMap extends AsyncTask<String, Void, Bitmap> {

    @Override
    protected Bitmap doInBackground(String... params) {
        Bitmap bitmap = null;
        try {
            URL url = new URL(params[0]);
            bitmap = BitmapFactory.decodeStream(url.openStream());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }
}

        private void showDialog() {
            if (!pDialog.isShowing())
                pDialog.show();
        }

        private void hideDialog() {
            if (pDialog.isShowing())
                pDialog.dismiss();
        }

我的个人资料活动课在这里

代码语言:javascript
复制
public class ProfileActivity extends Activity implements View.OnClickListener {

ImageView heder_bg,profile_pic,back;
Button edit_profile;
TextView tv_name,tv_email,tv_phone,tv_birthday;

String email=" ",phone=" ",name,profile_pic_url,token;

//db_details
String db_email="",db_name="",birthday = " ",db_phone=" ";
String db_profile_pic = "",db_profile_pic_bg = "";

private double currentLatitude;
private double currentLongitude;

//datetbase variables
SQliteHandler db;

private static final String TAG = ProfileActivity.class.getSimpleName();

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

    heder_bg =(ImageView)findViewById(R.id.profile_header_cover_image);
    profile_pic = (ImageView)findViewById(R.id.profile_user_profile_photo);
    back = (ImageView)findViewById(R.id.iv_profile_back);

    edit_profile = (Button)findViewById(R.id.btn_edit_profile);

    tv_name = (TextView)findViewById(R.id.profile_name);
    tv_email = (TextView)findViewById(R.id.profile_email);
    tv_phone = (TextView)findViewById(R.id.profile_phone);
    tv_birthday = (TextView)findViewById(R.id.profile_birthday);

    Intent data = getIntent();
    if(data.hasExtra("name") && data.hasExtra("email") && data.hasExtra("profile_url") && data.hasExtra("token")) {
        name = data.getStringExtra("name");
        email = data.getStringExtra("email");
        profile_pic_url = data.getStringExtra("profile_url");
        token = data.getStringExtra("token");
        currentLatitude = data.getDoubleExtra("latitude",0.0);
        currentLongitude = data.getDoubleExtra("longitude",0.0);
    }
    else if(data.hasExtra("name") && data.hasExtra("email") && data.hasExtra("profile_url") && data.hasExtra("token")){
        name = data.getStringExtra("name");
        phone = data.getStringExtra("phone");
        profile_pic_url = data.getStringExtra("profile_url");
        token = data.getStringExtra("token");
        currentLatitude = data.getDoubleExtra("latitude",0.0);
        currentLongitude = data.getDoubleExtra("longitude",0.0);
    }

    db = new SQliteHandler(getApplicationContext());

    //load user data from sqlite
    if(email != null && email !=" ") {
        HashMap<String, String> user = db.getuserdetails(email);
        db_name = user.get("name");
        db_email = user.get("email");
        db_phone = user.get("phone");
        db_profile_pic = user.get("profile_pic");
        db_profile_pic_bg = user.get("profile_pic_bg");
        birthday = user.get("birthday");
    }else if(phone != null && phone !=" "){
        HashMap<String, String> user = db.getuserdetails(phone);
        db_name = user.get("name");
        db_email = user.get("email");
        db_phone = user.get("phone");
        db_profile_pic = user.get("profile_pic");
        db_profile_pic_bg = user.get("profile_pic_bg");
        birthday = user.get("birthday");
    }


    edit_profile.setOnClickListener(this);
    back.setOnClickListener(this);

    load_user_info();
}

public void load_user_info(){
    if(name != null && name !=""){
        tv_name.setText(name);
    }else if(db_name != null && db_name !=""){
        tv_name.setText(db_name);
    }

    if (email != " " && email != null){
        tv_email.setText(email);
    }else if(db_email != null && db_email != "") {
        tv_email.setText(db_email);
    }else {
        tv_email.setText(" ");
    }

    if(phone !=" " && phone !=null) {
        tv_phone.setText("+91 " + phone);
    }else if(db_phone !=null && db_phone !=" ") {
        tv_phone.setText(db_phone);
    }else {
        tv_phone.setText("");
    }
    if(profile_pic_url!=null && profile_pic_url != "") {
        Glide.with(this)
                .load(profile_pic_url)
                .error(R.drawable.default_avtar)
                .centerCrop()
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .bitmapTransform(new CropCircleTransformation(this))
                .into(profile_pic);

        Glide.with(this)
                .load(R.drawable.beach)
                .crossFade()
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .into(heder_bg);
    }
    else if((db_profile_pic !=null && !db_profile_pic.equals(" "))&&(db_profile_pic_bg !=null && !db_profile_pic_bg.equals(" "))){
        byte[] db_profile;
        byte[] db_profile_bg;

        Bitmap db_profile_bitmap,db_profile_pic_bg_bitmap;
        db_profile = Base64.decode(db_profile_pic,Base64.DEFAULT);
        db_profile_bitmap = getBitmap(db_profile);

        db_profile_bg = Base64.decode(db_profile_pic_bg,Base64.DEFAULT);
        db_profile_pic_bg_bitmap = getBitmap(db_profile_bg);

        Glide.with(this)
                .load(db_profile_bitmap)
                .centerCrop()
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .bitmapTransform(new CropCircleTransformation(this))
                .into(profile_pic);

        Glide.with(this)
                .load(db_profile_pic_bg_bitmap)
                .crossFade()
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .into(heder_bg);
    }else {
        Glide.with(this)
                .load(R.drawable.default_avtar)
                .centerCrop()
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .bitmapTransform(new CropCircleTransformation(this))
                .into(profile_pic);
        Log.d("Default image set",TAG);
    }
    if(birthday !=" " && birthday !=null && birthday.equals("test")){
        tv_birthday.setText("Born on " + birthday);
    } else {
        tv_birthday.setText(" ");
    }
}

@Override
public void onResume(){
    super.onResume();
    load_user_info();
    Log.d("in resume methode",TAG);
}

public Bitmap getBitmap(byte[] bitmap) {
    return BitmapFactory.decodeByteArray(bitmap , 0, bitmap.length);
}

@Override
public void onClick(View v) {
    switch (v.getId()){

        case R.id.btn_edit_profile:
            Intent edit_profile = new Intent(getApplicationContext(),EditProfileActivity.class);
            edit_profile.putExtra("name",name);
            if((email !=null && email !="") && Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
                edit_profile.putExtra("email", email);
            }else if(phone != null && phone !="") {
                edit_profile.putExtra("phone", phone);
            }
            edit_profile.putExtra("profile_url",profile_pic_url);
            edit_profile.putExtra("token",token);
            edit_profile.putExtra("latitude",currentLatitude);
            edit_profile.putExtra("longitude",currentLongitude);
            startActivity(edit_profile);
            break;

        case R.id.iv_profile_back:
            Intent home = new Intent(getApplicationContext(),HomeActivity.class);
            startActivity(home);
            break;
    }
}

}

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2017-10-05 14:49:46

在OP发布代码之前

您可以定义一个函数,该函数为ProfileActivity加载数据并在onResume()中调用它。

代码语言:javascript
复制
@Override
public void onResume() {
    super.onResume();

    if (this.reloadNedeed)
        this.reloadProfileData();

    this.reloadNeeded = false; // do not reload anymore, unless I tell you so...
}

这样,由于onResume()也是在onCreate()之后调用的,所以您将使用相同的代码,无论是在第一次创建活动时还是在重新打开活动时(例如,当您从另一个活动或另一个应用程序返回时)。

为了使其工作,默认情况下必须将reloadNedeed设置为true:

代码语言:javascript
复制
private boolean reloadNeed = true;

为了启动EditActivity,您可以这样做:

代码语言:javascript
复制
startActivityForResult(new Intent(EditActivity.class), EDIT_CODE);

其中EDIT_CODE可以是任意数字,例如:

代码语言:javascript
复制
private static final int EDIT_CODE = 31;

当您想从EditActivity返回时,只需打电话:

代码语言:javascript
复制
Intent returnIntent = new Intent();
setResult(Activity.RESULT_OK,returnIntent); // or RESULT_CANCELED if user did not make any changes
// it would be better to use some custom defined codes here
finish();

这将触发ProfileActivity中的函数ProfileActivity,在该函数中,您可以告诉活动重新加载数据。

代码语言:javascript
复制
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == EDIT_CODE) { // Ah! We are back from EditActivity, did we make any changes?
        if (resultCode == Activity.RESULT_OK) {
            // Yes we did! Let's allow onResume() to reload the data
            this.reloadNeeded = true;
        }    
    }

onResume()onActivityResult()之后被称为,因此我们可以安全地决定是将reloadNeeded变为true,还是将其留给false。

编辑: OP发布后的代码

我还没有测试您的代码,但是我可能通过查看它就发现了一些奇怪的地方。

我相信您可能对if-else conditions函数中的某些load_user_info()有问题。

当您从EditActivity返回时,活动(很可能)不会再次创建。只有onResume()被调用,它调用load_user_info()

但是,由于活动不是重新创建的,所以变量在onCreate()中初始化时保持相同的值。

当他检查数据时:

代码语言:javascript
复制
if(name != null && name !=""){
    tv_name.setText(name);
}else if(db_name != null && db_name !=""){
    tv_name.setText(db_name);
}

你的活动是:

Heyy,name不是null,它不同于"“(顺便说一句,您应该使用equals(),即使是文字)

因此,我将执行这段代码tv_name.setText(name);,因为它是一个if else语句,所以不会执行第二个块。

所以你的活动,永远不会真正显示更新的数据。显示的数据与以前相同。

你应该尝试应用与我在最初的答案中发布的相同的逻辑。

希望我能正确理解你的问题。

票数 3
EN

Stack Overflow用户

发布于 2017-10-05 14:24:06

有多种方法来完成你的要求。有简单的,困难的,更正确的方法。

最简单的方法是刷新您要返回的活动的onResume中所期望的数据。如果导航到不同的活动,前面的活动将调用onPause,然后在返回时调用onResume,此时您可以检查新数据并将其加载到位。那是更快的方法。

一种更好、更正确的方法是实现ViewModel并使用LiveData允许活动始终拥有最新的数据。这确实需要你额外的努力,以确保你的应用程序有适当的架构,但从长远来看,回报要好得多。看看安卓的体系结构组件

票数 1
EN

Stack Overflow用户

发布于 2017-10-05 14:22:58

要刷新您的活动数据:

代码语言:javascript
复制
finish();
startActivity(getIntent());
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46587880

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档