Sagar Patel
Sagar Patel

Reputation: 586

How to: store image in sdcard, store and get imagepath in sharedpreferences for Profile Pic

Profile pic can be selected and set for a while but what we generally want (first object) is when user re-launch that page, there should be an image previously set by the user and if user has not set that image, there should be default image. I have used sharedpreferences for text views but it is said that for the image views, generally it is good practice to store the selected image first in sdcard, then get that Uri, make it string and then use it for sharedpreferences. i dont know if it can be done through onPause and onResume as well! if it is so, then which way should be prefer? and How to do that? Another thing is (Second object) i have an activity namely user profile where i want to inflate the data (Here, profile pic selected by the user) from edit profile activity. Here is the same case as of edit profile where if the user have not set custom profile pic then there should be default pic. Following is my edit profile activity:

public class EditUserProfile extends AppCompatActivity {

    private CoordinatorLayout coordinatorLayout;
    public static final String Uimage = "Uimage";
    public static final String Name = "nameKey";
    public static final String UContact = "UContact";
    public static final String Uemail = "Uemail";
    private TextInputLayout inputLayoutName, inputLayoutEmail, inputLayoutContact;
    private EditText usernameTextView, userEmailTextView, userContactTextView;
    private ImageView userImageView;
    SharedPreferences sharedpreferences;
    private int PICK_IMAGE_REQUEST = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_user_profile);
        Toolbar userProfileToolbar = (Toolbar) findViewById(R.id.my_toolbar);
        setSupportActionBar(userProfileToolbar);

        inputLayoutName = (TextInputLayout) findViewById(R.id.input_layout_username);
        inputLayoutEmail = (TextInputLayout) findViewById(R.id.input_layout_useremail);
        inputLayoutContact = (TextInputLayout) findViewById(R.id.input_layout_usercontact);

        userImageView = (ImageView) findViewById(R.id.userImage );
        usernameTextView = (EditText) findViewById(R.id.username);
        userContactTextView = (EditText) findViewById(R.id.usercontact);
        userEmailTextView = (EditText) findViewById(R.id.useremail);

        Button btnSave = (Button) findViewById(R.id.action_save);

        sharedpreferences = getSharedPreferences(Uimage, Context.MODE_PRIVATE);
        sharedpreferences = getSharedPreferences(Name, Context.MODE_PRIVATE);
        sharedpreferences = getSharedPreferences(UContact, Context.MODE_PRIVATE);
        sharedpreferences = getSharedPreferences(Uemail, Context.MODE_PRIVATE);

        if (sharedpreferences.contains(Name)) {
            usernameTextView.setText(sharedpreferences.getString(Name, ""));
        }
        if (sharedpreferences.contains(UContact)) {
            userContactTextView.setText(sharedpreferences.getString(UContact, ""));
        }
        if (sharedpreferences.contains(Uemail)) {
            userEmailTextView.setText(sharedpreferences.getString(Uemail, ""));
        }

        usernameTextView.addTextChangedListener(new MyTextWatcher(usernameTextView));
        userEmailTextView.addTextChangedListener(new MyTextWatcher(userEmailTextView));
        userContactTextView.addTextChangedListener(new MyTextWatcher(userContactTextView));

        coordinatorLayout = (CoordinatorLayout) findViewById(R.id
               .coordinatorLayout);

        final ImageButton button = (ImageButton) findViewById(R.id.editImage);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Perform action on click

                Intent intent = new Intent();
                // Show only images, no videos or anything else
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                // Always show the chooser (if there are multiple options available)
                startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
            }
        });
    }

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

        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {

            Uri uri = data.getData();

            try {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
                // Log.d(TAG, String.valueOf(bitmap));
                userImageView.setImageBitmap(bitmap);

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * Validating form
     */

    private boolean submitForm() {
        if (!validateName()) {
            return false;
        }

        if (!validateContact()) {
            return false;
        }

        if (!validateEmail()) {
            return false;
        }

        Snackbar snackbar = Snackbar
                .make(coordinatorLayout, "Saved!", Snackbar.LENGTH_LONG);

        snackbar.show();

        return true;
    }

    private boolean validateName() {
        if (usernameTextView.getText().toString().trim().isEmpty()) {
            inputLayoutName.setError(getString(R.string.err_msg_name));
            requestFocus(usernameTextView);
            return false;
        } else {
            inputLayoutName.setError(null);
        }

        return true;
    }

    private boolean validateEmail() {
        String email = userEmailTextView.getText().toString().trim();

        if (email.isEmpty() || !isValidEmail(email)) {
            inputLayoutEmail.setError(getString(R.string.err_msg_email));
            requestFocus(userEmailTextView);
            return false;
        } else {
            inputLayoutEmail.setError(null);
        }

        return true;
    }

    private boolean validateContact() {
        if (userContactTextView.getText().toString().trim().isEmpty()) {
            inputLayoutContact.setError(getString(R.string.err_msg_contact));
            requestFocus(userContactTextView);
            return false;
        } else {
            inputLayoutContact.setError(null);
        }

        return true;
    }

    private static boolean isValidEmail(String email) {
        return !TextUtils.isEmpty(email) && android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
    }

    private void requestFocus(View view) {
        if (view.requestFocus()) {
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        }
    }

    private class MyTextWatcher implements TextWatcher {

        private View view;

        private MyTextWatcher(View view) {
            this.view = view;
        }

        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        public void afterTextChanged(Editable editable) {
            switch (view.getId()) {
                case R.id.username:
                    validateName();
                    break;
                case R.id.useremail:
                    validateEmail();
                    break;
                case R.id.usercontact:
                    validateContact();
                    break;
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.editprofile_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_save:

              if (!submitForm()){

                  return false;
              }

                TextView usernameTextView = (TextView) findViewById(R.id.username);
                String usernameString = usernameTextView.getText().toString();

                SharedPreferences.Editor editor = sharedpreferences.edit();
                editor.putString(Name, usernameString);
                editor.apply();

                TextView ucontactTV = (TextView) findViewById(R.id.usercontact);
                String uContactS = ucontactTV.getText().toString();

                editor.putString(UContact, uContactS);
                editor.apply();

                TextView uEmailTV = (TextView) findViewById(R.id.useremail);
                String uEmailS = uEmailTV.getText().toString();

                editor.putString(Uemail, uEmailS);
                editor.apply();

                Snackbar snackbar = Snackbar
                        .make(coordinatorLayout, "Saved!", Snackbar.LENGTH_LONG);

                snackbar.show();

                Intent userProfileIntent = new Intent(EditUserProfile.this, UserProfile.class);
                userProfileIntent.putExtra(Name, usernameString);
                userProfileIntent.putExtra(UContact, uContactS);
                userProfileIntent.putExtra(Uemail, uEmailS);

                setResult(RESULT_OK, userProfileIntent);
                finish();

        }
        return true;
    }

}

Following is the user profile activity where i want to inflate default or custom profile pic from edit profile activity as same as i am able to inflate rest of text views:

public class UserProfile extends AppCompatActivity {
    SharedPreferences sharedpreferences;

    public static final String Uimage = "Uimage";
    public static final String Name = "nameKey";
    public static final String UContact = "UContact";
    public static final String Uemail = "Uemail";

    public static final int Edit_Profile = 1;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_profile);
        Toolbar userProfileToolbar = (Toolbar) findViewById(R.id.my_toolbar);
        setSupportActionBar(userProfileToolbar);

        sharedpreferences = getSharedPreferences(Uimage, MODE_PRIVATE);
        sharedpreferences = getSharedPreferences(Name, MODE_PRIVATE);
        sharedpreferences = getSharedPreferences(UContact, MODE_PRIVATE);
        sharedpreferences = getSharedPreferences(Uemail, MODE_PRIVATE);

        displayMessage(sharedpreferences.getString(Name, ""));
        displayUContact(sharedpreferences.getString(UContact, ""));
        displayUEmail(sharedpreferences.getString(Uemail, ""));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.userprofile_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_editProfile:
                Intent userProfileIntent = new Intent(UserProfile.this, EditUserProfile.class);
                startActivityForResult(userProfileIntent, Edit_Profile);
                return true;

        }
        return true;
    }

    // Call Back method  to get the Message form other Activity

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {

            case Edit_Profile:
                if (resultCode == RESULT_OK) {
                    String name = data.getStringExtra(Name);
                    String Result_UContact = data.getStringExtra(UContact);
                    String Result_UEmail = data.getStringExtra(Uemail);
                    displayMessage(name);
                    displayUContact(Result_UContact);
                    displayUEmail(Result_UEmail);
                }

                break;
        }
    }

    public void displayMessage(String message) {
        TextView usernameTextView = (TextView) findViewById(R.id.importProfile);
        usernameTextView.setText(message);
    }

    public void displayUContact(String contact) {
        TextView userContactTextView = (TextView) findViewById(R.id.importContact);
        userContactTextView.setText(contact);
    }

    public void displayUEmail(String email) {
        TextView userEmailTextView = (TextView) findViewById(R.id.importEmail);
        userEmailTextView.setText(email);
    }
}

Please consider that i have no experience in programming, coding or android development and i have just started to learn that!

Upvotes: 0

Views: 98

Answers (3)

Sagar Patel
Sagar Patel

Reputation: 586

We can have method to retrieve the Uri for selected image as below:

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

    if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {

        Uri uri = data.getData();

        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
            // CALL THIS METHOD TO GET THE ACTUAL PATH
            File finalFile = new File(getRealPathFromURI(uri));

            outputFileUri = Uri.fromFile(finalFile);

            stringUri = outputFileUri.toString();
            // Log.d(TAG, String.valueOf(bitmap));
            userImageView.setImageBitmap(bitmap);

            SharedPreferences.Editor editor = sharedpreferences.edit();
            editor.putString(Uimage, stringUri);
            editor.apply();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

public String getRealPathFromURI(Uri uri) {
    Cursor cursor = getContentResolver().query(uri, null, null, null, null);
    cursor.moveToFirst();
    int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
    return cursor.getString(idx);
}

So now we have String that represents or has been stored with value of Uri for our selected image. Next is to use this string for sharedpreferences as below:

    SharedPreferences.Editor editor = sharedpreferences.edit();
    editor.putString(Uimage, stringUri);
    editor.apply();

Uimage is the key and it has string value stringUri with it! Each time user change the profile pic, we will have updated Uimage and associated stringUri at the same time. Now, in onCreate method, we will check if there is sharedpreferences available with this value and if so, then we want to display the selected image. It should be noted here that sharedpreferences is used to save and keep the primitive data across re-launching of the app. Editor.putString is used to store some value and sharedpreferences.getString is used to read that value.

if (sharedpreferences.contains(Uimage)){
    String imagepath = sharedpreferences.getString(Uimage, "");
    uriString = Uri.parse(imagepath);
    userImageView.setImageURI(uriString);
}

uriString is Uri! And it worked! Next is to send this profile pic to the user profile activity. We will use intent to send the selected pic to user profile activity and sharedpreferences in onCreate method of user profile activity to save and keep that pic there across re-launch as below: 1. Sending pic to the user profile activity using intent in edit profile activity as below:

   @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_save:


                Snackbar snackbar = Snackbar
                        .make(coordinatorLayout, "Saved!", Snackbar.LENGTH_LONG);

                snackbar.show();

                Intent userProfileIntent = new Intent(EditUserProfile.this, UserProfile.class);


                if (sharedpreferences.contains(stringUri)){

                    userProfileIntent.putExtra(Uimage, stringUri);
                }

                setResult(RESULT_OK, userProfileIntent);
                finish();

        }
        return true;
    }

….and read and handle this intent at user profile activity as below:

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {

            case Edit_Profile:
                if (resultCode == RESULT_OK) {

                    String imageIntent = data.getStringExtra(Uimage);

                    displayUimage(imageIntent);
                }

                break;
        }
    }

Where:

 public void displayUimage (String imageString){
        ImageView importImage = (ImageView) findViewById(R.id.importImage);
        imageString = sharedpreferences.getString(Uimage, "");
        uriString = Uri.parse(imageString);
        importImage.setImageURI(uriString);

    }

Intent is used to get the pic from edit profile activity to user profile activity. If we press back or exit the app and re-launch it, user profile activity will lose that pic. In order to save and keep that pic there across re-launching of app, we need to use sharedpreferences there.

  1. Save and Keep that pic there at user profile activity using sharedpreferences as below:

    @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_user_profile);
    
    Toolbar userProfileToolbar = (Toolbar) findViewById(R.id.my_toolbar);
    setSupportActionBar(userProfileToolbar);
    
    importImage = (ImageView) findViewById(R.id.importImage);
    
    importImage.setImageResource(R.drawable.defaultprofilepic);
    
    sharedpreferences = getSharedPreferences(Uimage, MODE_PRIVATE);
    
    if (sharedpreferences.contains(Uimage)){
        String imagepath = sharedpreferences.getString(Uimage, "");
        uriString = Uri.parse(imagepath);
        importImage.setImageURI(uriString);
    }
    
    }
    

We first have initialized our importImage with the default one but then we check if there is sharedpreferences with special key is available.

That simply means, if the sharedpreferences contains Uimage (which is possible only if the user have changed the profile pic and the Uimage will be always updated as soon as user change the profile pic) then we will get Uri for that image and set it to importImage so that we will have same profile pic as user have selected at edit profile activity.

Below is the complete Edit profile activity:

public class EditUserProfile extends AppCompatActivity {

    private CoordinatorLayout coordinatorLayout;

    public static final String Uimage = "Uimagepath";
    public static final String Name = "nameKey";
    public static final String UContact = "UContact";
    public static final String Uemail = "Uemail";

    private TextInputLayout inputLayoutName, inputLayoutEmail, inputLayoutContact;
    private EditText usernameTextView, userEmailTextView, userContactTextView;
    private ImageView userImageView;

    SharedPreferences sharedpreferences;
    private int PICK_IMAGE_REQUEST = 1;

    String stringUri;
    Uri outputFileUri;
    Uri uriString;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_user_profile);
        Toolbar userProfileToolbar = (Toolbar) findViewById(R.id.my_toolbar);
        setSupportActionBar(userProfileToolbar);

        inputLayoutName = (TextInputLayout) findViewById(R.id.input_layout_username);
        inputLayoutEmail = (TextInputLayout) findViewById(R.id.input_layout_useremail);
        inputLayoutContact = (TextInputLayout) findViewById(R.id.input_layout_usercontact);

        userImageView = (ImageView) findViewById(R.id.userImage );
        usernameTextView = (EditText) findViewById(R.id.username);
        userContactTextView = (EditText) findViewById(R.id.usercontact);
        userEmailTextView = (EditText) findViewById(R.id.useremail);

        Button btnSave = (Button) findViewById(R.id.action_save);

        sharedpreferences = getSharedPreferences(Uimage, Context.MODE_PRIVATE);
        sharedpreferences = getSharedPreferences(Name, Context.MODE_PRIVATE);
        sharedpreferences = getSharedPreferences(UContact, Context.MODE_PRIVATE);
        sharedpreferences = getSharedPreferences(Uemail, Context.MODE_PRIVATE);

        if (sharedpreferences.contains(Uimage)){
            String imagepath = sharedpreferences.getString(Uimage, "");
            uriString = Uri.parse(imagepath);
            userImageView.setImageURI(uriString);
        }

        if (sharedpreferences.contains(Name)) {
            usernameTextView.setText(sharedpreferences.getString(Name, ""));
        }
        if (sharedpreferences.contains(UContact)) {
            userContactTextView.setText(sharedpreferences.getString(UContact, ""));
        }
        if (sharedpreferences.contains(Uemail)) {
            userEmailTextView.setText(sharedpreferences.getString(Uemail, ""));
        }

        usernameTextView.addTextChangedListener(new MyTextWatcher(usernameTextView));
        userEmailTextView.addTextChangedListener(new MyTextWatcher(userEmailTextView));
        userContactTextView.addTextChangedListener(new MyTextWatcher(userContactTextView));

        coordinatorLayout = (CoordinatorLayout) findViewById(R.id
               .coordinatorLayout);

        final ImageButton button = (ImageButton) findViewById(R.id.editImage);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Perform action on click

                Intent intent = new Intent();
                // Show only images, no videos or anything else
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                // Always show the chooser (if there are multiple options available)
                startActivityForResult(Intent.createChooser(intent, "Select Pic from"), PICK_IMAGE_REQUEST);
            }
        });
    }

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

        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {

            Uri uri = data.getData();

            try {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
                // CALL THIS METHOD TO GET THE ACTUAL PATH
                File finalFile = new File(getRealPathFromURI(uri));

                outputFileUri = Uri.fromFile(finalFile);

                stringUri = outputFileUri.toString();
                // Log.d(TAG, String.valueOf(bitmap));
                userImageView.setImageBitmap(bitmap);

                SharedPreferences.Editor editor = sharedpreferences.edit();
                editor.putString(Uimage, stringUri);
                editor.apply();


            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    public String getRealPathFromURI(Uri uri) {
        Cursor cursor = getContentResolver().query(uri, null, null, null, null);
        cursor.moveToFirst();
        int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
        return cursor.getString(idx);
    }

    /**
     * Validating form
     */

    private boolean submitForm() {
        if (!validateName()) {
            return false;
        }

        if (!validateContact()) {
            return false;
        }

        if (!validateEmail()) {
            return false;
        }

        Snackbar snackbar = Snackbar
                .make(coordinatorLayout, "Saved!", Snackbar.LENGTH_LONG);

        snackbar.show();

        return true;
    }

    private boolean validateName() {
        if (usernameTextView.getText().toString().trim().isEmpty()) {
            inputLayoutName.setError(getString(R.string.err_msg_name));
            requestFocus(usernameTextView);
            return false;
        } else {
            inputLayoutName.setError(null);
        }

        return true;
    }

    private boolean validateEmail() {
        String email = userEmailTextView.getText().toString().trim();

        if (email.isEmpty() || !isValidEmail(email)) {
            inputLayoutEmail.setError(getString(R.string.err_msg_email));
            requestFocus(userEmailTextView);
            return false;
        } else {
            inputLayoutEmail.setError(null);
        }

        return true;
    }

    private boolean validateContact() {
        if (userContactTextView.getText().toString().trim().isEmpty()) {
            inputLayoutContact.setError(getString(R.string.err_msg_contact));
            requestFocus(userContactTextView);
            return false;
        } else {
            inputLayoutContact.setError(null);
        }

        return true;
    }

    private static boolean isValidEmail(String email) {
        return !TextUtils.isEmpty(email) && android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
    }

    private void requestFocus(View view) {
        if (view.requestFocus()) {
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        }
    }

    private class MyTextWatcher implements TextWatcher {

        private View view;

        private MyTextWatcher(View view) {
            this.view = view;
        }

        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        public void afterTextChanged(Editable editable) {
            switch (view.getId()) {
                case R.id.username:
                    validateName();
                    break;
                case R.id.useremail:
                    validateEmail();
                    break;
                case R.id.usercontact:
                    validateContact();
                    break;
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.editprofile_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_save:

              if (!submitForm()){

                  return false;
              }

                SharedPreferences.Editor editor = sharedpreferences.edit();

                TextView usernameTextView = (TextView) findViewById(R.id.username);
                String usernameString = usernameTextView.getText().toString();

                editor.putString(Name, usernameString);
                editor.apply();

                TextView ucontactTV = (TextView) findViewById(R.id.usercontact);
                String uContactS = ucontactTV.getText().toString();

                editor.putString(UContact, uContactS);
                editor.apply();

                TextView uEmailTV = (TextView) findViewById(R.id.useremail);
                String uEmailS = uEmailTV.getText().toString();

                editor.putString(Uemail, uEmailS);
                editor.apply();

                Snackbar snackbar = Snackbar
                        .make(coordinatorLayout, "Saved!", Snackbar.LENGTH_LONG);

                snackbar.show();

                Intent userProfileIntent = new Intent(EditUserProfile.this, UserProfile.class);

                userProfileIntent.putExtra(Name, usernameString);
                userProfileIntent.putExtra(UContact, uContactS);
                userProfileIntent.putExtra(Uemail, uEmailS);

                if (sharedpreferences.contains(stringUri)){

                    userProfileIntent.putExtra(Uimage, stringUri);
                }

                setResult(RESULT_OK, userProfileIntent);
                finish();

        }
        return true;
    }

}

Below is the complete User Profile Activity that shows saved profile:

public class UserProfile extends AppCompatActivity {
    SharedPreferences sharedpreferences;

    public static final String Uimage = "Uimagepath";
    public static final String Name = "nameKey";
    public static final String UContact = "UContact";
    public static final String Uemail = "Uemail";
    ImageView importImage;
    Uri uriString;

    public static final int Edit_Profile = 1;


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

        Toolbar userProfileToolbar = (Toolbar) findViewById(R.id.my_toolbar);
        setSupportActionBar(userProfileToolbar);

        importImage = (ImageView) findViewById(R.id.importImage);

        importImage.setImageResource(R.drawable.defaultprofilepic);

        sharedpreferences = getSharedPreferences(Uimage, MODE_PRIVATE);
        sharedpreferences = getSharedPreferences(Name, MODE_PRIVATE);
        sharedpreferences = getSharedPreferences(UContact, MODE_PRIVATE);
        sharedpreferences = getSharedPreferences(Uemail, MODE_PRIVATE);

        if (sharedpreferences.contains(Uimage)){
            String imagepath = sharedpreferences.getString(Uimage, "");
            uriString = Uri.parse(imagepath);
            importImage.setImageURI(uriString);
        }

        displayMessage(sharedpreferences.getString(Name, ""));
        displayUContact(sharedpreferences.getString(UContact, ""));
        displayUEmail(sharedpreferences.getString(Uemail, ""));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.userprofile_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_editProfile:
                Intent userProfileIntent = new Intent(UserProfile.this, EditUserProfile.class);
                startActivityForResult(userProfileIntent, Edit_Profile);
                return true;

            case R.id.action_dos:

                Intent coffeeIntent = new Intent(UserProfile.this, Dos.class);

                UserProfile.this.startActivity(coffeeIntent);

                return true;

            case R.id.action_13:

                Intent teaIntent = new Intent(UserProfile.this, thirteen.class);

                UserProfile.this.startActivity(teaIntent);

                return true;

        }
        return true;
    }

    // Call Back method  to get the Message form other Activity

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {

            case Edit_Profile:
                if (resultCode == RESULT_OK) {


                    String imageIntent = data.getStringExtra(Uimage);
                    String name = data.getStringExtra(Name);
                    String Result_UContact = data.getStringExtra(UContact);
                    String Result_UEmail = data.getStringExtra(Uemail);

                    displayUimage(imageIntent);
                    displayMessage(name);
                    displayUContact(Result_UContact);
                    displayUEmail(Result_UEmail);
                }

                break;
        }
    }

    public void displayMessage(String message) {
        TextView usernameTextView = (TextView) findViewById(R.id.importProfile);
        usernameTextView.setText(message);
    }

    public void displayUContact(String contact) {
        TextView userContactTextView = (TextView) findViewById(R.id.importContact);
        userContactTextView.setText(contact);
    }

    public void displayUEmail(String email) {
        TextView userEmailTextView = (TextView) findViewById(R.id.importEmail);
        userEmailTextView.setText(email);
    }

    public void displayUimage (String imageString){
        ImageView importImage = (ImageView) findViewById(R.id.importImage);
        imageString = sharedpreferences.getString(Uimage, "");
        uriString = Uri.parse(imageString);
        importImage.setImageURI(uriString);

    }

}

Hope this helps someone!

Upvotes: 0

MojioMS
MojioMS

Reputation: 1693

I have no much timer to write the entire answer, but here is how to store some Strings into the application shared Preferences: 1. storing some strings, it makes sense to store them when your "save"-button is clicked:

// assume a,b,c are strings with the information from ur edittexts to be saved:
String a,b,c;
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sp.edit();
editor.putString("namekey",a);
editor.putString("UContact", b);
editor.putString("UEmail", c);
editor.commit();

now these 3 things are saved. 2. loading these values (e.g. in ur onCreate() method after setting the content):

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
// check if the namevalues "namekey", "UContact", "UEmail" have values saved in the sharedPreferences. If not, load defaultvalue 
String user_name = sp.getString("namekey", "no name entered yet");
String user_email = sp.getString("UEmail", "no email entered yet");
String user_contact = sp.getString("UContact", "no Contact entered yet");
displayMessage(user_name);
displayUContact(user_contact);
displayUEmail(user_email);

Loading a value from the sharedPreferences always needs a 2nd parameter, which will be the result when there is nothing saved for this key. For example, if your application is started for the first time, and the user did not have entered anything in the edittexts, then "no name entered yet", and so on are loaded from the sharedPreferences.

and.. thats it so far. Why did i not provide information on how to store a bitmap in the sharedPreferences? - sharedPreferences can only store basic Types such as Float, Integer, String, Boolean - You could save the image into the sd card, but remember: not every device is using a sd card. If your application uses the camera-intent instead, your foto is already saved in the gallery automatically. You can store this path as a String in the sharedPrefs.

Upvotes: 1

sihao
sihao

Reputation: 431

You are right. You can store the image in your sd card and use the uri to load the image subsequently.

You can consider to save the image uri in the stored preference. With that you will just need to handle two cases.

In your onCreate() method

 - Check if the image uri is valid (image exist)
 - If it does, load it and make it the display image
 - If it is missing, load the default image
 * Alternatively, you can set the default image as the image for the imageview

Whenever the user updates the image

 - Store the image into the sd card
 - Update your shared preference 

As such, you should not need to handle these in your onPause() and onResume() methods.

Hope it helps!

Upvotes: 1

Related Questions