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

Posted

技术标签:

【中文标题】当我们从另一个活动返回时如何刷新活动的数据?【英文标题】:How to refresh the activity's data when we return from another activity? 【发布时间】:2018-03-17 04:56:36 【问题描述】:

在这里,我想制作一个具有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]\\d9$").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;
    

【问题讨论】:

if(data.hasExtra("name") &amp;&amp; data.hasExtra("email") &amp;&amp; data.hasExtra("profile_url") &amp;&amp; data.hasExtra("token")) ... else if(data.hasExtra("name") &amp;&amp; data.hasExtra("email") &amp;&amp; data.hasExtra("profile_url") &amp;&amp; data.hasExtra("token")) ... 他们是一样的!就像if (true) ... else if (true) ... 这是什么?您可能想检查phone 字符串,对吧? 是的,如果有电子邮件或电话来自活动.. 好的!但是您的 ifelse if 语句包含完全相同的条件。希望你明白我在告诉你什么。这就像写if (val == 5) ... else if (val == 5) ... 。我的回答对你有帮助吗?如果您不理解这些概念,我建议您将代码发布在代码审查网站上。 我进行了更改,因为它在两种情况下都检查电子邮件,感谢您的指点。 记得发布一些更新。 【参考方案1】:

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

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

@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 发布代码后

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

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

当您从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);

你的活动说:

嘿,name 不是 null 并且不同于 ""(顺便说一下,你应该使用 equals(),即使是文字)

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

因此,您的活动永远不会真正显示更新的数据。显示与之前相同的数据。

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

希望我能正确理解您的问题...

【讨论】:

【参考方案2】:

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

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

更好、更正确的做法是实现ViewModel 并使用LiveData 让活动始终拥有最新数据。这确实需要您付出一些额外的努力来确保您的应用程序具有正确的架构,但从长远来看,回报会更好。查看 android 的 architecture components。

【讨论】:

当我单击保存按钮时,它将数据保存在 sqlite 中并返回到配置文件活动,在配置文件活动的 onResume 方法中,我调用了加载用户方法,该方法从 sqlite 获取更新的数据但它没有设置在 textview 中,当我按下返回按钮时,它会显示更新的数据 要准确排除故障,需要更多信息。在不知道 Activity 代码的情况下,无法准确说明为什么数据没有加载。 您正在通过 Intent 数据加载新信息,这很好,但您只是通过 onCreate 设置它,这不会总是被调用。您可以添加 onNewIntent 的覆盖来帮助处理该问题,但我提供的信息仍然准确 - 您没有从生命周期的 onResume 部分加载数据。 Android 生命周期可能非常变化无常。【参考方案3】:

刷新您的活动数据:

finish();
startActivity(getIntent());

【讨论】:

【参考方案4】:

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

@Override
public void onRestart()

    super.onRestart();
    finish();
    startActivity(getIntent());

我希望这会有所帮助...

【讨论】:

以上是关于当我们从另一个活动返回时如何刷新活动的数据?的主要内容,如果未能解决你的问题,请参考以下文章

当我尝试从另一个活动中获取数据时,应用程序返回上一页

Android Kotlin 无法从另一个活动中获取结果

从另一个活动返回后如何恢复活动中最后打开的片段

从另一个活动返回后应用程序未恢复捆绑包

C#当用户控件变为活动状态时,如何自动刷新文本文件中的数据?

从另一个活动返回时,MapFragment 的地图加载滞后