2016-04-08 73 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); 
    } 
    

    相關問題