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

问题描述 投票:1回答:4

在这里,我想创建一个拥有profile activity的应用程序,用户可以在其中查看他/她的信息,activity有一个按钮用于编辑配置文件。单击按钮时,将打开新活动,用户可以在此处编辑信息并按保存按钮,然后返回到个人资料活动。所以我的问题是如何用编辑的信息重新加载配置文件活动?

这是我的编辑个人资料活动

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

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

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

}

android android-activity activity-lifecycle
4个回答
2
投票

在OP发布代码之前

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

@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:

private boolean reloadNeed = true;

为了启动EditActivity,您可以:

startActivityForResult(new Intent(EditActivity.class), EDIT_CODE);

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

private static final int EDIT_CODE = 31;

如果您想从EditActivity回来,请致电:

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

这将触发onActivityResult(int, int Intent)中的ProfileActivity函数,您可以在其中告诉活动重新加载数据。

@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,或者只是将其置为假。


编辑:OP发布代码后

我没有测试过您的代码,但我可能只是通过查看它就找到了一些奇怪的东西。

我相信你的if-else conditions函数可能有一些load_user_info()的问题。

当您从EditActivity回来时,活动(很可能)不会再次创建。只调用onResume(),称为load_user_info();

但由于未重新创建Activity,因此您的变量在onCreate()中初始化时保持相同的值。

当他确实检查数据时:

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

你的活动说:

Heyy,名字不是空的并且不同于“”(顺便说一下你应该使用equals(),即使是文字)

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

所以你的活动,从未真正显示更新的数据。显示与之前相同的数据。

您应该尝试应用我在原始答案中发布的相同逻辑。

希望我理解你的问题是正确的......


1
投票

有多种方法可以完成您的要求。有简单的(ish)方式和硬(er)和更正确的方式。

最简单的方法是刷新您正在返回的活动的onResume中所期望的数据。如果您导航到其他活动,则上一个活动将在您返回时调用onPause,然后调用onResume,此时您可以检查新数据并将其加载到位。那是更快捷的方式。

更好,更正确的方法是实现ViewModel并使用LiveData来允许Activity始终拥有最新的数据。这需要您的额外努力,以确保您的应用程序具有适当的架构,但从长远来看,更好的回报方式。查看Android的architecture components


0
投票

要刷新您的活动数据:

finish();
startActivity(getIntent());

0
投票

onBackPressed或finish()然后调用并刷新

@Override
public void onRestart()
{
    super.onRestart();
    finish();
    startActivity(getIntent());
}

我希望这有用......

© www.soinside.com 2019 - 2024. All rights reserved.