Here is the code:
button.setOnClickListener(new View.OnClickListener() {
#Override public void onClick (View view){
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(contactPickerIntent, RESULT_PICK_CONTACT);
}
}); return view;}
public void but(View v) {
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(contactPickerIntent, RESULT_PICK_CONTACT);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case RESULT_PICK_CONTACT:
contactPicked(data);
break;
}
} else {
Log.e("MainActivity", "Failed to pick contact");
}
}
private void contactPicked(Intent data) {
Cursor cursor = null;
try {
String phoneNo = null;
String name = null;
Uri uri = data.getData();
cursor = getActivity().getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int phoneIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
int nameIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
phoneNo = cursor.getString(phoneIndex);
name = cursor.getString(nameIndex);
if (phoneNo.startsWith("+")) {
if (phoneNo.length() == 13) {
String str_getMOBILE = phoneNo.substring(4);
editText.setText(("0") + str_getMOBILE);
}
if (phoneNo.length() == 16) {
String str_getMOBILE = phoneNo.substring(4);
editText.setText(("0") + str_getMOBILE);
}
} else {
editText.setText(phoneNo);
}
} catch (Exception e) {
e.printStackTrace();
}
}
You may be facing any of the following scenarios that led to the crash :
Your button is not declared and initiated properly in the onCreate() method of your main class. So please check if you have the below code in your onCreate() method :
Button button = (Button) findViewById(R.id.button);
Your app reads contacts from the user device I believe. In that case, please check if you have necessary permission to read contacts. For that, just check if the below line is included in the AndroidManifest.xml file :
<uses-permission android:name="android.permission.READ_CONTACTS" />
Check if you have permission to call the appropriate intent.
Your logcat trace will contain the exact line of code that led to the crash and the error code. So if you paste the logcat info here, you can get help.
I am trying to add an image from the gallery to an image view. It has been added but the image is disappearing from the image view on rotating the screen. The image has been saved to firebase. How to save the activity state? I have searched for it but did not find the relevant answer.Can anyone help me out to solve the problem.
public class skcreateac extends AppCompatActivity
{
static final int PICK_IMAGE_REQUEST = 1;
private EditText sketac1;
private EditText sksetac1;
private EditText sketac2;
private EditText sketac3;
private EditText sketac4;
private EditText sketac5;
private Button skbt;
private Spinner spac;
private ImageView skimg;
private StorageReference skdbimg, fp;
private Firebase skrootac1;
private String strsk, skurl;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_skcreateac);
spac = (Spinner)findViewById(R.id.spinner2);
String cities[] = new String[]{"Hyderabad", "Warangal"};
ArrayAdapter<String> cityadapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, cities);
spac.setAdapter(cityadapter);
skimg = (ImageView) findViewById(R.id.skimg);
skdbimg = FirebaseStorage.getInstance().getReference();
sketac1 = (EditText) findViewById(R.id.skonac);
sksetac1 = (EditText) findViewById(R.id.sksncac);
sketac2 = (EditText) findViewById(R.id.skphcac);
sketac3 = (EditText) findViewById(R.id.sksaddress);
sketac4 = (EditText) findViewById(R.id.skpwcac);
sketac5 = (EditText) findViewById(R.id.skpwrcac);
skbt = (Button) findViewById(R.id.bsu);
strsk = getIntent().getExtras().getString("value");
String url1 = "https://my-app2-a14eb.firebaseio.com/Shopkeepers/";
String url2 = strsk;
skurl = url1 + url2;
skrootac1 = new Firebase(skurl);
skimg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent skimg = new Intent(Intent.ACTION_PICK);
skimg.setType("image/*");
startActivityForResult(skimg, PICK_IMAGE_REQUEST);
}
});
skbt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String s1 = sketac1.getText().toString();
if (sketac1.getText().length() == 0) {
sketac1.setError("Kindly enter your Name");
}
Firebase childac1 = skrootac1.child("Name");
childac1.setValue(s1);
String ss1 = sksetac1.getText().toString();
if (sksetac1.getText().length() == 0) {
sksetac1.setError("Kindly enter your ShopName");
}
Firebase childsac1 = skrootac1.child("ShopName");
childsac1.setValue(ss1);
String s2 = sketac2.getText().toString();
long i = Long.parseLong(s2);
int j = 0;
while (i > 0) {
i = i / 10;
j++;
}
if (j == 10) {
Firebase childac2 = skrootac1.child("Phone");
childac2.setValue(s2);
} else {
Toast.makeText(skcreateac.this, "Enter valid Mobile number", Toast.LENGTH_LONG).show();
}
String s3 = spac.getSelectedItem().toString();
Firebase childac3 = skrootac1.child("City");
childac3.setValue(s3);
String s4 = sketac3.getText().toString();
Firebase childac4 = skrootac1.child("Address");
childac4.setValue(s4);
String s5 = sketac4.getText().toString();
String s6 = sketac5.getText().toString();
if (s5.equals(s6)) {
Firebase childac5 = skrootac1.child("Password");
childac5.setValue(s5);
} else {
Toast.makeText(skcreateac.this, "Confirm Password field doesnot match with Create Password field", Toast.LENGTH_LONG).show();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK) {
final Uri uri = data.getData();
fp = skdbimg.child("SKPhotos").child(strsk);
fp.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Picasso.get().load(uri).fit().centerCrop().into(skimg);
Toast.makeText(skcreateac.this, "Uploaded photo", Toast.LENGTH_LONG).show();
}
});
}
}
Add following -
#Override
protected void onSaveInstanceState (Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable("outputFileUri", photoURI);
}
Make a private URI photoURI = null; in your activity.
Then in your onCreate() add do
#Override
protected void onCreate(Bundle savedInstanceState){
// your other codes
skrootac1 = new Firebase(skurl);
// your other codes
if (savedInstanceState != null)
{
photoURI= savedInstanceState.getParcelable("outputFileUri");
setImage(photoURI);
}
}
private void setImage(final Uri uri){
fp = skdbimg.child("SKPhotos").child(strsk);
fp.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Picasso.get().load(uri).fit().centerCrop().into(skimg);
Toast.makeText(skcreateac.this, "Uploaded photo", Toast.LENGTH_LONG).show();
}
});
}
And finally, change your onActivityResult()
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK) {
photoURI = data.getData();
setImage(photoURI);
}
}
Here, I want to make an app which is having profile activity and user can see his/her information in that and the activity has one button for editing the profile. When button is clicked the new activity is opened where user can edit there information & press save button and then return to profile activity.
So my question is how can I reload the profile activity with edited information?
here is my Edit profile 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();
}
And my profile activity class is here
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;
}
}
}
Before OP posted code
You can define a function that loads your data for ProfileActivity and call it in onResume().
#Override
public void onResume() {
super.onResume();
if (this.reloadNedeed)
this.reloadProfileData();
this.reloadNeeded = false; // do not reload anymore, unless I tell you so...
}
This way, since onResume() is also called after onCreate(),
you'd be using the same code both for when the the activity is first created and for when you re-open it (e.g. when you come back from another activity, or another app).
In order to make it work, reloadNedeed must be set to true by default:
private boolean reloadNeed = true;
In order to start the EditActivity you can do:
startActivityForResult(new Intent(EditActivity.class), EDIT_CODE);
where EDIT_CODE can be any number, e.g:
private static final int EDIT_CODE = 31;
When you want to get back to from EditActivity you just call:
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();
This would trigger the function onActivityResult(int, int Intent) in ProfileActivity, in which you can tell the activity to reload the data.
#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() is called after onActivityResult(), so we can safely decide whether to put reloadNeeded to true, or just leave it to false.
Edit: After OP posted code
I haven't tested your code, but I may have found some oddities just by looking at it.
I believe you may have a problem with some if-else conditions in your load_user_info() function.
When you get back from EditActivity the activity is (most likely) not created again. Only onResume() is called, which calls load_user_info();
But since the Activity isn't recreated, your variables hold the same values from when they were initialized in onCreate().
When he does check the data:
if(name != null && name !=""){
tv_name.setText(name);
}else if(db_name != null && db_name !=""){
tv_name.setText(db_name);
}
your activity says:
Heyy, name is not null and is different than "" (by the way you should use equals(), even for literals)
Therefore, I will execute this piece of code tv_name.setText(name);, and since it's an if else statement, the second block will NOT be executed.
So your activity, never really displays the updated data. The same data as before is displayed.
You should try to apply the same logic as I posted in my original answer.
Hope I understood your question right...
There are multiple ways to accomplish what you are asking. There's the simple(ish) way and the hard(er) and more correct way.
The easiest way is to refresh the data you're expecting in the onResume of the activity you are returning to. If you navigate to a different activity, the previous activity will call onPause, then onResume when you return, and at that time you can check for new data and load it in place. That's the quicker way.
A better, more correct way of doing it would be to implement a ViewModel and use LiveData to allow the Activity to always have the most up to date data. This does require a bit of extra effort on your end to make sure your app has proper architecture, but in the long run pays off way better. Check out Android's architecture components.
To refresh your activity data:
finish();
startActivity(getIntent());
onBackPressed or finish() then its call and refresh
#Override
public void onRestart()
{
super.onRestart();
finish();
startActivity(getIntent());
}
I hope this helpful...
I am calling from my app. After ends that call, I am trying to get a call duration. But my code return call duration two times. Last call duration while making call and new call duration after ends a call. But I need only one call duration after user ends the new call. How can i achieve this. Here is my code. Thanks in advance.
public class MainActivity extends AppCompatActivity {
private static final int CALL_PERMISSION= 99;
private static final int READ_LOG_PERMISSION=11;
Button btnGetCallDuration;
Context mContext;
private int mFlag = 0;
String phNumber = "";
boolean flag=false;
String callDuration = "";
public static int REQ_CODE=1;
private boolean callPermission=false;
private boolean readlogPermission=false;
public static final int MULTIPLE_PERMISSIONS = 10; // code you want.
String[] permissions = new String[] {
Manifest.permission.READ_CALL_LOG,
Manifest.permission.CALL_PHONE,
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = MainActivity.this;
btnGetCallDuration = (Button) findViewById(R.id.btnGetCallDuration);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkPermissions();
}
btnGetCallDuration.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.v("onclick", "called");
Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:121"));
startActivity(intent);
//flag = true;
}
});
}
private boolean checkPermissions() {
int result;
List<String> listPermissionsNeeded = new ArrayList<>();
for (String p:permissions) {
result = ContextCompat.checkSelfPermission(mContext,p);
if (result != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(p);
}
}
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new
String[listPermissionsNeeded.size()]), MULTIPLE_PERMISSIONS);
return false;
}
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.v("request code",requestCode+"\t"+resultCode);
if(requestCode==REQ_CODE)
{
Log.v("request code",requestCode+"");
// getCallDruation();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case MULTIPLE_PERMISSIONS: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permissions granted.
callPermission=true;
} else {
// no permissions granted.
callPermission=false;
}
return;
}
}
}
#Override
protected void onPause() {
super.onPause();
Log.v("Pause is called","pause");
flag=true;
}
public boolean checkLocationPermission() {
if (ContextCompat.checkSelfPermission(mContext,
Manifest.permission.CALL_PHONE)
!= PackageManager.PERMISSION_GRANTED) {
// Asking user if explanation is needed
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
Manifest.permission.CALL_PHONE)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.CALL_PHONE},
CALL_PERMISSION);
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.CALL_PHONE},
CALL_PERMISSION);
}
return false;
} else {
return true;
}
}
public boolean readCallLogPermission() {
if (ContextCompat.checkSelfPermission(mContext,
Manifest.permission.READ_CALL_LOG)
!= PackageManager.PERMISSION_GRANTED) {
// Asking user if explanation is needed
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
Manifest.permission.READ_CALL_LOG)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.READ_CALL_LOG},
READ_LOG_PERMISSION);
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.CALL_PHONE},
READ_LOG_PERMISSION);
}
return false;
} else {
callPermission=true;
return callPermission;
}
}
#Override
protected void onResume() {
super.onResume();
Log.v("flag","onrsume called");
if(flag)
{
getCallDruation();
flag=false;
}
}
private void getCallDruation() {
StringBuffer sb = new StringBuffer();
Uri contacts = CallLog.Calls.CONTENT_URI;
Log.v("get duration","called");
Cursor cur = getContentResolver().query(contacts, null, null, null, android.provider.CallLog.Calls.DATE + " DESC");
int number = cur.getColumnIndex(CallLog.Calls.NUMBER);
int duration = cur.getColumnIndex(CallLog.Calls.DURATION);
sb.append("Call Details : \n");
while (cur.moveToNext()) {
phNumber = cur.getString(number);
callDuration = cur.getString(duration);
sb.append("\nPhone Number:" + phNumber+"\t"+callDuration);
break;
}
cur.close();
String str = sb.toString();
Log.v("restult",str);
Toast.makeText(mContext, phNumber + "\t\t" + callDuration, Toast.LENGTH_SHORT).show();
}
}
This above code is called from onResume() life cycle method of activity.
In the below code,getInfoFromDevice is not being executed, I also tried with a Log.d() but it could not be of further help.
In the code I am using runtime permissions to check if the user has granted permission to access external storage and if yes the function getInfoFromDevice() is called. I am not sure if the placement of the function is correct or not ? But this function is not executing. what could be the reason ?
It does not throw any error,
public class MainActivity extends Activity implements ActivityCompat.OnRequestPermissionsResultCallback {
ArrayList<String> listOfSongs = new ArrayList<String>();
ListView liststructure;
final private int REQUEST_CODE_ASK_PERMISSIONS = 123;
String MUSIC_STRING = MediaStore.Audio.Media.IS_MUSIC + "!=0";
String[] STAR = {"*"};
String orderColumns = MediaStore.Audio.AudioColumns.TITLE + " COLLATE LOCALISED ASC";
private final int REQUEST_GRANTED_BY_USER = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkPermissions();
liststructure = (ListView) findViewById(R.id.listView);
SongsList list = new SongsList(MainActivity.this, listOfSongs);
liststructure.setAdapter(list);
}
private void checkPermissions() {
int permissionCheck = ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.READ_EXTERNAL_STORAGE);
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_GRANTED_BY_USER);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if(requestCode == REQUEST_GRANTED_BY_USER )
{
getInfoFromDevice();
} else {
// Permission Denied
Toast.makeText(MainActivity.this, "EXTERNAL_STORAGE Denied", Toast.LENGTH_SHORT)
.show();
}
}
void getInfoFromDevice() {
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor cursor = getContentResolver().query(uri, STAR, MUSIC_STRING, null, null);
if (cursor != null)
{
if (cursor.moveToFirst()) {
do {
String name = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME));
String data = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
String album = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM));
String albumID = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
listOfSongs.add(album + " " + name + " " + albumID);
} while (cursor.moveToNext());
}
}
}
}
Please let me know if you need more details.
EDIT 1
The code will look for mp3 files with the help of MediaStore library and will check if it has a permission to access external storage and if yes it will call the function getInfoFromDevice()
just change you code like below:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
liststructure = (ListView) findViewById(R.id.listView);
SongsList list = new SongsList(MainActivity.this, listOfSongs);
liststructure.setAdapter(list);
checkPermissions();
}
private void checkPermissions() {
if (Build.VERSION.SDK_INT >= 23) {
int permissionCheck = ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.READ_EXTERNAL_STORAGE);
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_GRANTED_BY_USER);
}else{
getInfoFromDevice();
}
}else{
getInfoFromDevice();
}
}
First check permission as below,
public void checkPermission(String permission) {
if (ContextCompat.checkSelfPermission(BaseActivity.this,
permission)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(BaseActivity.this,
Manifest.permission.READ_EXTERNAL_STORAGE)) {
ActivityCompat.requestPermissions(BaseActivity.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
10);
} else {
ActivityCompat.requestPermissions(BaseActivity.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
10);
}
}
}
then,
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case 10: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
// permission granted call your function
getInfoFromDevice();
} else {
// permission denied.
}
return;
}
}
}
You can also use below plugin to easily add run time permission without more effort,
https://android-arsenal.com/details/1/3571