Сохранение изображения из галереи в android
у меня возник вопрос при установке изображения в ImageView: при нажатии на него открывается галерея, человек выберет фото, фото устанавливается в профиль, но при следующем запуске приложения или activity ему придётся снова его выбирать. Что нужно сделать, чтобы фото сохранялось в самом приложении или путь к нему? Но тут появляется еще один вопрос: если сохранить путь, а изображение пользователь удалит, то ничего не установиться (я так думаю). Вот Activity
public class MyAccountSettingsActivity extends AppCompatActivity implements View.OnClickListener {
ImageView arrowIm;
CircleImageView profileImage;
private final int Pick_image = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_account_settings);
arrowIm = findViewById(R.id.picArrow);
profileImage = findViewById(R.id.profileImage);
arrowIm.setOnClickListener(this);
profileImage.setOnClickListener(this);
}
@Override
public void onClick(View v) {
Intent intent;
switch (v.getId()) {
case R.id.picArrow:
intent = new Intent(MyAccountSettingsActivity.this, UserSettings.class);
startActivity(intent);
break;
case R.id.profileImage:
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
//Тип получаемых объектов - image:
photoPickerIntent.setType("image/*");
//Запускаем переход с ожиданием обратного результата в виде информации об изображении:
startActivityForResult(photoPickerIntent, Pick_image);
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case Pick_image:
if (resultCode == RESULT_OK) {
try {
//Получаем URI изображения, преобразуем его в Bitmap
//объект и отображаем в элементе ImageView нашего интерфейса:
final Uri imageUri = imageReturnedIntent.getData();
final InputStream imageStream = getContentResolver().openInputStream(imageUri);
final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
Log.e("mLog", "onActivityResult: " + imageStream + " " + imageReturnedIntent + " " + imageUri);
profileImage.setImageBitmap(selectedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="1"
tools:context="adwantay.studio.dindon.MyAccountSettingsActivity">
<LinearLayout
android:id="@+id/settings"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/white"
android:orientation="vertical"
android:paddingLeft="20sp"
android:paddingTop="10sp"
android:paddingRight="20sp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:orientation="horizontal"
android:paddingTop="10sp"
android:paddingBottom="10sp"
android:weightSum="1">
<ImageView
android:id="@+id/picArrow"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="0.45"
android:clickable="true"
android:gravity="left|center_vertical"
android:src="@drawable/ic_monday_arrow" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.1"
android:fontFamily="@font/ttcommons_medium"
android:paddingLeft="25sp"
android:paddingRight="25sp"
android:text="@string/my_account"
android:textColor="@android:color/black"
android:textSize="25sp" />
<ImageView
android:id="@+id/picDone"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="0.45"
android:clickable="true"
android:src="@drawable/ic_monday_done" />
</LinearLayout>
</LinearLayout>
<View
android:id="@+id/view"
android:layout_width="match_parent"
android:layout_height="0.5dp"
android:layout_marginLeft="10sp"
android:layout_marginRight="10sp"
android:background="@color/greyAction" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingLeft="20dp"
android:paddingRight="20sp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:gravity="center_horizontal"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<de.hdodenhof.circleimageview.CircleImageView
android:id="@+id/profileImage"
android:layout_width="115dp"
android:layout_height="115dp"
app:civ_border_color="#FF000000"
app:civ_border_width="0dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingLeft="15sp">
<TextView
android:id="@+id/textView3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="@font/ttcommons_light"
android:text="@string/user_name"
android:textColor="@color/greyAction"
android:textSize="18sp" />
<EditText
android:id="@+id/userName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/my_account_edit_text"
android:fontFamily="@font/ttcommons_light"
android:paddingLeft="7sp"
android:paddingTop="7sp"
android:paddingBottom="3sp"
android:text="TextView" />
<TextView
android:id="@+id/textView9"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10sp"
android:fontFamily="@font/ttcommons_light"
android:text="@string/group"
android:textColor="@color/greyAction"
android:textSize="18sp" />
<Spinner
android:id="@+id/url2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="@array/group"
android:fontFamily="@font/ttcommons_light"
android:paddingLeft="1sp"
android:paddingTop="6sp"
android:paddingBottom="7sp"
android:text="TextView" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
<TextView
android:id="@+id/textView5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:fontFamily="@font/ttcommons_light"
android:text="@string/email"
android:textColor="@color/greyAction"
android:textSize="20sp" />
<EditText
android:id="@+id/url4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="15dp"
android:background="@drawable/my_account_edit_text"
android:fontFamily="@font/ttcommons_light"
android:paddingLeft="7sp"
android:paddingTop="7sp"
android:paddingBottom="3sp"
android:text="[email protected]" />
<TextView
android:id="@+id/textView10"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:fontFamily="@font/ttcommons_light"
android:text="@string/safety"
android:textColor="@color/greyAction"
android:textSize="20sp" />
<LinearLayout
android:id="@+id/toc"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/hover"
android:clickable="true"
android:orientation="vertical"
android:paddingRight="20sp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal"
android:paddingTop="5sp"
android:paddingBottom="10sp"
android:weightSum="1">
<ImageView
android:id="@+id/picToc"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="0.9"
android:gravity="center_vertical"
android:src="@drawable/ic_monday_toc" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.1"
android:fontFamily="@font/ttcommons_light"
android:paddingLeft="25sp"
android:paddingRight="25sp"
android:text="@string/edit_psw"
android:textColor="@android:color/black"
android:textSize="20sp" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="@+id/account"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/hover"
android:clickable="true"
android:orientation="vertical"
android:paddingRight="20sp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal"
android:paddingTop="10sp"
android:paddingBottom="10sp"
android:weightSum="1">
<ImageView
android:id="@+id/picAccount"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="0.9"
android:gravity="center_vertical"
android:src="@drawable/ic_monday_toc" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.1"
android:fontFamily="@font/ttcommons_light"
android:paddingLeft="25sp"
android:paddingRight="25sp"
android:text="@string/two_fact_auth"
android:textColor="@android:color/black"
android:textSize="20sp" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="@+id/notifications"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/hover"
android:clickable="true"
android:orientation="vertical"
android:paddingRight="20sp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal"
android:paddingTop="10sp"
android:paddingBottom="10sp"
android:weightSum="1">
<ImageView
android:id="@+id/picNotifications"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="0.9"
android:gravity="center_vertical"
android:src="@drawable/ic_monday_toc" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.1"
android:fontFamily="@font/ttcommons_light"
android:paddingLeft="25sp"
android:paddingRight="25sp"
android:text="@string/deactivate_account"
android:textColor="@android:color/black"
android:textSize="20sp" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="@+id/palette"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5sp"
android:background="@drawable/hover"
android:clickable="true"
android:orientation="vertical"
android:paddingRight="20sp">
</LinearLayout>
<LinearLayout
android:id="@+id/about"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5sp"
android:background="@drawable/hover"
android:clickable="true"
android:orientation="vertical"
android:paddingRight="20sp">
</LinearLayout>
</LinearLayout>
</ScrollView>
</LinearLayout>
Вот XML
Ответы (1 шт):
Для сохранения пути, можно использовать SharedPreferences. Для этого берем uri выбранной картинки и сохраняем в память:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case Pick_image:
if (resultCode == RESULT_OK) {
try {
final Uri imageUri = imageReturnedIntent.getData();
...
SharedPreferences mySharedPreferences = getSharedPreferences(APP_PREFERENCES, Context.MODE_PRIVATE);
mSettings.edit().putString("path", imageUri.toString()).apply();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
}
дальше при запуске приложения проверяем есть ли что-то в памяти:
SharedPreferences mySharedPreferences = getSharedPreferences(APP_PREFERENCES, Context.MODE_PRIVATE);
String path = mySharedPreferences.getString("path", "");
if(path != null && !path.trim().isEmpty()){
\\ сетим картинку по сохраненному пути
InputStream imageStream = getContentResolver().openInputStream(imageUri);
Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
profileImage.setImageBitmap(selectedImage);
}else{
\\ картинка не сохранена в памяти
}
Для того чтобы проверить есть ли картинка, можно сделать так:
File file = new File(URI.create(path).getPath());
if (file.exists()) {
\\ картинка существует
}
и вот итоговое решение должно быть приблизительно таким:
String path = mySharedPreferences.getString("path", "");
if(path != null && !path.trim().isEmpty()){
File file = new File(URI.create(path).getPath());
if (file.exists()) {
InputStream imageStream = getContentResolver().openInputStream(imageUri);
Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
profileImage.setImageBitmap(selectedImage);
}
}else{
\\ картинка не сохранена в памяти
}