当我们从另一个 activity return 时如何刷新 activity 的数据?
How to refresh the activity's data when we return from another activity?
在这里,我想制作一个具有 profile activity
的应用程序,用户可以在其中看到 his/her 信息,并且 activity
有一个用于编辑配置文件的按钮。单击按钮后,将打开新的 activity,用户可以在其中编辑信息并按保存按钮,然后 return 到配置文件 activity。
所以我的问题是如何使用编辑后的信息重新加载配置文件 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();
}
我的个人资料 activity class 在这里
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;
}
}
}
要刷新您的 activity 数据:
finish();
startActivity(getIntent());
有多种方法可以完成您的要求。有简单的(大概)方法和困难的(呃)更正确的方法。
最简单的方法是在您returnactivity 的 onResume
中刷新您期望的数据。如果您导航到另一个 activity,前一个 activity 将调用 onPause
,然后 return 时将调用 onResume
,那时您可以检查新的数据并将其加载到位。这是更快的方法。
更好、更正确的方法是实施 ViewModel
并使用 LiveData
以允许 Activity 始终拥有最新数据。这确实需要您付出一些额外的努力来确保您的应用程序具有适当的架构,但从长远来看 运行 会获得更好的回报。查看 Android 的 architecture components.
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()
之后被调用,
您将在 activity 首次创建时和重新打开它时使用相同的代码(例如,当您从另一个 activity 或另一个应用程序返回时)。
为了让它工作,reloadNedeed
必须默认设置为真:
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),您可以在其中告诉 activity 重新加载数据。
@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 发布代码后
我没有测试你的代码,但我可能只是通过查看它发现了一些奇怪的地方。
我相信您的 load_user_info()
函数中的某些 if-else conditions
可能有问题。
当您从 EditActivity
回来时,activity(很可能)不会再次创建。只调用了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);
}
你的 activity 说:
嘿,name 不为 null 并且不同于 ""(顺便说一句,你应该使用 equals()
,即使是文字)
因此,我将执行这段代码 tv_name.setText(name);
,因为它是一个if else
语句,第二个块将不被执行.
因此您的 activity 从未真正显示更新的数据。显示与之前相同的数据。
您应该尝试应用我在原始答案中发布的相同逻辑。
希望我理解你的问题...
onBackPressed 或 finish() 然后它的调用和刷新
@Override
public void onRestart()
{
super.onRestart();
finish();
startActivity(getIntent());
}
希望对您有所帮助...
在这里,我想制作一个具有 profile activity
的应用程序,用户可以在其中看到 his/her 信息,并且 activity
有一个用于编辑配置文件的按钮。单击按钮后,将打开新的 activity,用户可以在其中编辑信息并按保存按钮,然后 return 到配置文件 activity。
所以我的问题是如何使用编辑后的信息重新加载配置文件 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();
}
我的个人资料 activity class 在这里
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;
}
}
}
要刷新您的 activity 数据:
finish();
startActivity(getIntent());
有多种方法可以完成您的要求。有简单的(大概)方法和困难的(呃)更正确的方法。
最简单的方法是在您returnactivity 的 onResume
中刷新您期望的数据。如果您导航到另一个 activity,前一个 activity 将调用 onPause
,然后 return 时将调用 onResume
,那时您可以检查新的数据并将其加载到位。这是更快的方法。
更好、更正确的方法是实施 ViewModel
并使用 LiveData
以允许 Activity 始终拥有最新数据。这确实需要您付出一些额外的努力来确保您的应用程序具有适当的架构,但从长远来看 运行 会获得更好的回报。查看 Android 的 architecture components.
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()
之后被调用,
您将在 activity 首次创建时和重新打开它时使用相同的代码(例如,当您从另一个 activity 或另一个应用程序返回时)。
为了让它工作,reloadNedeed
必须默认设置为真:
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),您可以在其中告诉 activity 重新加载数据。
@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 发布代码后
我没有测试你的代码,但我可能只是通过查看它发现了一些奇怪的地方。
我相信您的 load_user_info()
函数中的某些 if-else conditions
可能有问题。
当您从 EditActivity
回来时,activity(很可能)不会再次创建。只调用了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);
}
你的 activity 说:
嘿,name 不为 null 并且不同于 ""(顺便说一句,你应该使用 equals()
,即使是文字)
因此,我将执行这段代码 tv_name.setText(name);
,因为它是一个if else
语句,第二个块将不被执行.
因此您的 activity 从未真正显示更新的数据。显示与之前相同的数据。
您应该尝试应用我在原始答案中发布的相同逻辑。
希望我理解你的问题...
onBackPressed 或 finish() 然后它的调用和刷新
@Override
public void onRestart()
{
super.onRestart();
finish();
startActivity(getIntent());
}
希望对您有所帮助...