2016-04-08 304 views
0

配置文件图片可以选择和设置一段时间,但我们通常想要的(第一个对象)是当用户重新启动该页面时,应该是以前由用户设置的图像,如果用户没有设置该图像,则应该有默认图像。我已经使用了文本视图的共享首选项,但据说对于图像视图,通常最好先将选定的图像存储在SD卡中,然后获取该Uri,将其设置为字符串,然后将其用于共享首选项。我不知道是否可以通过onPause和onResume完成!如果是这样,那么应该选择哪种方式?以及如何做到这一点?另一件事是(第二个对象)我有一个活动,即用户配置文件,我想从编辑配置文件活动中充入数据(这里,用户选择的配置文件图片)。这与编辑配置文件的情况相同,如果用户没有设置自定义配置文件图片,则应该有默认图片。以下是我的编辑个人资料活动:如何:在SD卡中存储图像,存储和获取配置文件的共享首选图像路径

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

} 

以下是我想要的膨胀从编辑个人资料活动默认或自定义配置文件PIC的一样,我能够膨胀的文本视图其余用户配置文件活动:

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

请考虑,我没有经验的编程,编码或Android开发,我刚开始学习!

回答

0

我们可以有方法来检索的URI所选图像如下。 接下来就是用这个字符串sharedpreferences如下:

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

uImage执行是关键,它有字符串值stringUri吧!每次用户更改配置文件图片时,我们都会同时更新Uimage和相关的stringUri。 现在,在onCreate方法中,我们将检查是否存在与此值共享的首选项,如果是,则我们要显示选定的图像。这里应该注意的是,共享首选项用于在应用重新启动时保存和保留原始数据。 Editor.putString用于存储一些值和sharedpreferences.getString用于读取该值。

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

uriString是Uri! 它的工作! 接下来是将此配置文件图片发送到用户配置文件活动。我们将使用意图将选定的图片发送到用户配置文件活动和用户配置文件活动的onCreate方法中的共享首选项,以在重新启动时保存并保存该图片,如下所示: 1.使用编辑中的意图将图片发送到用户配置文件活动活动简介如下:

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

...以及读取和处理这个意图在下面的用户配置文件活动:

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

其中:

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

    } 

意图用于从编辑配置文件活动获取图片到用户配置文件活动。如果我们按回或退出应用程序并重新启动它,用户配置文件活动将会丢失该图片。为了在重新启动应用程序时保存并保存该图片,我们需要在那里使用共享首选项。

  • 保存并使用sharedpreferences如下记住,PIC有在用户配置文件活动:

    @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); 
    } 
    
    } 
    
  • 我们首先必须初始化我们importImage使用默认的一个,但那么我们检查是否有可用的特殊密钥的共享首选项。

    这就是说,如果sharedpreferences包含Uimage(这只有在用户更改了配置文件图片时才有可能,并且只要用户更改配置文件图片,Uimage就会随时更新),那么我们将获得该图片的Uri并将其设置为importImage,以便我们将具有与用户在编辑配置文件活动中选择的相同的配置文件图片。

    下面是完整的修改个人资料的活动:

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

    下面是完整的用户配置文件的活动,显示保存的个人资料:

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

    希望这可以帮助别人!

    1

    你说得对。您可以将图像存储在SD卡中,然后使用uri加载图像。

    您可以考虑将图像uri保存在存储的首选项中。有了这个,你只需要处理两个案例。

    在你onCreate()方法

    - 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 
    

    每当用户更新图像

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

    因此,你不需要在你的onPause来处理这些()和onResume()方法。

    希望它有帮助!

    +0

    ...以及如何将图像存储到内部存储? (因为有些设备并没有真正的外置SD卡!) –

    +0

    我想我不需要将图像存储在除原始图像以外的任何位置,因为它似乎毫无意义(来自新手视图),因为它可以从那里删除所以我最好把它存储在服务器端! –

    1

    我没有太多的计时器来写完整的答案,但这里是如何将一些字符串存储到应用程序的共享首选项: 1.存储一些字符串,当你的“保存”按钮时存储它们是有意义的点击:

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

    现在这3件东西都保存了。 2.装载这些值(设定内容之后例如在乌尔onCreate()方法):

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

    载入从sharedPreferences的值总是需要一个第二参数,该参数将是结果时还有什么保存这个关键。例如,如果您的应用程序第一次启动,并且用户没有在edittext中输入任何内容,则会从sharedPreferences中加载“尚未输入任何名称”等。

    和..这是迄今为止。 为什么我不提供有关如何在sharedPreferences中存储位图的信息? - sharedPreferences只能存储基本类型,如Float,Integer,String,Boolean - 您可以将图像保存到SD卡中,但请记住:并非每个设备都使用SD卡。如果您的应用程序使用相机意图,您的照片已自动保存在画廊中。您可以将此路径作为字符串存储在sharedPrefs中。所以现在我们有字符串,表示或已经储存与我们所选择的图像乌里值

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

    相关问题