Shared Preferences Deleting Data When App Is Reloaded - android

I am creating my first project using Android Studio, I am aiming to create an app where you can load photos in from the phones memory and display them so people can see.
I've managed to get it working sort of how I want it to, the pictures in the gallery stay where they should do when I close out of the app and then reopen it - however if I close the app restart it and then try and add a new photo it overwrites the gallery and deletes the pictures I orginally put in. Does anyone have any ideas on how I can fix this? I tried playing with when I create the images ArrayList but that didn't help.
Code:
Main Activity
public class MainActivity extends AppCompatActivity {
private static final int PERMISSION_REQUEST = 0;
private static final int RESULT_LOAD_IMAAGE = 1;
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String Name = "nameKey";
ImageView imageView;
Button uploadButton;
Button savedPhotos;
List<String> images;
String imageCreated;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED){
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST);
}
imageView = (ImageView) findViewById(R.id.imageView);
uploadButton = (Button) findViewById(R.id.button);
savedPhotos = (Button) findViewById(R.id.button2);
SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
images = new ArrayList<>();
uploadButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAAGE);
SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(imageCreated, "Complete");
}
});
savedPhotos.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openPage2();
}
});
}
public void openPage2()
{
Intent intent = new Intent(this, SavedPhotos.class);
startActivity(intent);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch(requestCode)
{
case PERMISSION_REQUEST:
if(grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(this, "Permission Not Granted", Toast.LENGTH_SHORT).show();
finish();
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
switch(requestCode)
{
case RESULT_LOAD_IMAAGE:
if(resultCode == RESULT_OK)
{
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
images.add(picturePath);
StringBuilder stringBuilder = new StringBuilder();
for(String i : images)
{
stringBuilder.append(i);
stringBuilder.append(",");
}
SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("images", stringBuilder.toString() );
editor.commit();
}
}
}}
And SavedPhotos
public class SavedPhotos extends AppCompatActivity {
public static final String MyPREFERENCES = "MyPrefs" ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_saved_photos);
SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
String wordsString = sharedpreferences.getString("images", "");
String[] itemWords = wordsString.split(",");
List<String> items = new ArrayList<String>();
LinearLayout layout = (LinearLayout) findViewById(R.id.linear);
for(int i = 0; i < itemWords.length; i++) {
ImageView imageView = new ImageView(this);
imageView.setId(i);
imageView.setPadding(2, 2, 2, 2);
imageView.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher_foreground));
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
layout.addView(imageView);
items.add(itemWords[i]);
imageView.setImageBitmap(BitmapFactory.decodeFile(items.get(i)));
}
}}
Thank you for your help :)

I actually run to same issues before until i met a well made library and requires nothing and made my code much good looking, FastSave: https://github.com/yehiahd/FastSave-Android.

Related

My Fragment doesn't get destroyed after it is recreated

I am developing a gallery application, I display all the icons from the external storage into my application. I followed the tutorial from the below link and it is working.
https://deepshikhapuri.wordpress.com/2017/03/20/get-all-images-from-gallery-in-android-programmatically/
Now in addition to this, I provide an option for the user to take a picture from the application and save it to the gallery. When the picture is taken using the Camera intent, the image gets actually saved in the gallery. But I have to intent to another fragment and come back to the Gallery to see the picture I have taken.
To see the changes immediately, onActivityResult() of the Camera intent, I am recreating the fragment. But the problem occurs when we click the back button. The recreated fragment stays in the backstack forever. I am brain faded searching for answers. Any help is appreciated.
Please find below what I have tried so far.
public class GalleryFragment extends Fragment {
Toolbar toolbar;
MenuItem search;
public static ArrayList<Model_images> al_images = new ArrayList<>();
boolean boolean_folder;
Adapter_PhotosFolder obj_adapter;
GridView gv_folder;
FloatingActionButton cameraButton;
private static final int REQUEST_PERMISSIONS = 100;
static final int REQUEST_TAKE_PHOTO = 1;
static final int REQUEST_IMAGE_CAPTURE = 1;
String projectName = "ProjectGA";
File directory;
String mCurrentPhotoPath;
List<GridViewItem> gridItems;
GridView gridView;
public static GalleryFragment newInstance(){
GalleryFragment galleryFragment = new GalleryFragment();
return galleryFragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
directory = new File(Environment.getExternalStorageDirectory() + projectName);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_gallery, container, false);
toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
ImageView icon = (ImageView) getActivity().findViewById(R.id.toolbarIcon);
icon.setImageResource(R.drawable.ic_perm_media_black_24dp);
icon.setColorFilter(getResources().getColor(R.color.Gallery));
TextView title = (TextView) getActivity().findViewById(R.id.toolbarTitle);
title.setText(getString(R.string.galleryLabel));
title.setTextColor(getResources().getColor(R.color.textInputEditTextColor));
toolbar.setBackground(getResources().getDrawable(R.drawable.tile_green));
toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_menu_green_24dp));
cameraButton = (FloatingActionButton) getActivity().findViewById(R.id.rightActionButton);
cameraButton.setVisibility(View.VISIBLE);
cameraButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dispatchTakePictureIntent();
}
});
//gridView = (GridView) view.findViewById(R.id.gridView);
gv_folder = (GridView)view.findViewById(R.id.gv_folder);
gv_folder.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getContext(), PhotosActivity.class);
intent.putExtra("value",i);
startActivity(intent);
}
});
if ((ContextCompat.checkSelfPermission(getContext(),
Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) && (ContextCompat.checkSelfPermission(getContext(),
Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
if ((ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
Manifest.permission.WRITE_EXTERNAL_STORAGE)) && (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
Manifest.permission.READ_EXTERNAL_STORAGE))) {
} else {
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_PERMISSIONS);
}
}else {
Log.e("Else","Else");
fn_imagespath();
}
setHasOptionsMenu(true);
return view;
}
#Override
public void onDestroyView() {
cameraButton.setVisibility(View.INVISIBLE);
super.onDestroyView();
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {photoFile = createImageFile();
} catch (IOException ex) {
Context context = getContext();
CharSequence text = "Photo cannot be stored.";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
// Continue only if the File was successfully created
if (photoFile != null) {
Context context = getContext();
Uri photoURI = FileProvider.getUriForFile(context,
"com.example.projectga.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}else{
Context context = getContext();
CharSequence text = "Attention! Required to take picture!!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
}
public void createFolder(){
if (!directory.exists()){
directory.mkdirs();
}
}
private File createImageFile() throws IOException {
createFolder();
// Create an image file name
Context context = getContext();
String timeStamp = new SimpleDateFormat("dd-MMM-yyyy").format(new Date());
String imageFileName = projectName + "_" + timeStamp + "_";
File storageDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
addImageToGallery(image, context);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getPath();
return image;
}
public static void addImageToGallery(File image, final Context context) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
values.put(MediaStore.MediaColumns.DATA, image.toString());
context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
getFragmentManager().beginTransaction()
.replace(R.id.container_gaFragments, GalleryFragment.newInstance()).commit();
}
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
search = menu.add("search").setIcon(R.drawable.ic_search_green_24dp).setShowAsActionFlags(1);
super.onCreateOptionsMenu(menu, inflater);
}
public ArrayList<Model_images> fn_imagespath() {
al_images.clear();
int int_position = 0;
Uri uri;
Cursor cursor;
int column_index_data, column_index_folder_name;
String absolutePathOfImage = null;
uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String[] projection = {MediaStore.MediaColumns.DATA, MediaStore.Images.Media.BUCKET_DISPLAY_NAME};
final String orderBy = MediaStore.Images.Media.DATE_TAKEN;
cursor = getContext().getContentResolver().query(uri, projection, null, null, orderBy + " DESC");
column_index_data = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
column_index_folder_name = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.BUCKET_DISPLAY_NAME);
while (cursor.moveToNext()) {
absolutePathOfImage = cursor.getString(column_index_data);
Log.e("Column", absolutePathOfImage);
Log.e("Folder", cursor.getString(column_index_folder_name));
for (int i = 0; i < al_images.size(); i++) {
if (al_images.get(i).getStr_folder().equals(cursor.getString(column_index_folder_name))) {
boolean_folder = true;
int_position = i;
break;
} else {
boolean_folder = false;
}
}
if (boolean_folder) {
ArrayList<String> al_path = new ArrayList<>();
al_path.addAll(al_images.get(int_position).getAl_imagepath());
al_path.add(absolutePathOfImage);
al_images.get(int_position).setAl_imagepath(al_path);
} else {
ArrayList<String> al_path = new ArrayList<>();
al_path.add(absolutePathOfImage);
Model_images obj_model = new Model_images();
obj_model.setStr_folder(cursor.getString(column_index_folder_name));
obj_model.setAl_imagepath(al_path);
al_images.add(obj_model);
}
}
for (int i = 0; i < al_images.size(); i++) {
Log.e("FOLDER", al_images.get(i).getStr_folder());
for (int j = 0; j < al_images.get(i).getAl_imagepath().size(); j++) {
Log.e("FILE", al_images.get(i).getAl_imagepath().get(j));
}
}
obj_adapter = new Adapter_PhotosFolder(getContext(),al_images);
gv_folder.setAdapter(obj_adapter);
return al_images;
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_PERMISSIONS: {
for (int i = 0; i < grantResults.length; i++) {
if (grantResults.length > 0 && grantResults[i] == PackageManager.PERMISSION_GRANTED) {
fn_imagespath();
} else {
Toast.makeText(getContext(), "The app was not allowed to read or write to your storage. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show();
}
}
}
}
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
I also override the onBackPressed() in the Activity. Please help. Also attaching some images to make it clear.
The exact problem of what is happening
Any help is appreciated.

How to get a Result from Image Capture and save it to Shared Preferences in Android

I am building an app in which I want when the user clicks the imageview, the device camera app to launch and take a picture and set it to the imageview. I have accomplished that!!! But when I exit the app and re-open it the image has been deleted. How can I do it so the image is permanent?
My code:
private SessionManager session;
private static final int REQ_CODE = 1152;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
private Uri file;
private String fileName = "ImageTaken";
private ImageView imagePhoto;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_data);
session = new SessionManager(getApplicationContext());
session.checkLogin();
HashMap<String, String> user = session.getUserDetails();
Toolbar tb = (Toolbar)findViewById(R.id.topBar);
setSupportActionBar(tb);
String name = user.get(SessionManager.KEY_NAME);
TextView watersName = (TextView)findViewById(R.id.waitersName);
TextView date = (TextView)findViewById(R.id.date);
TextView time = (TextView)findViewById(R.id.time);
watersName.setText(Html.fromHtml("<b>" + name + "</b>"));
Calendar c = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd" + "/" + "mm" + "/" + "yyyy");
String text = dateFormat.format(c.getTime());
date.setText(text);
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");
String timeF = timeFormat.format(c.getTime());
time.setText(timeF);
Button btnnewworder = (Button)findViewById(R.id.btnnewworder);
btnnewworder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(UserData.this, Tables.class);
startActivity(intent);
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_right);
}
});
Button payment = (Button)findViewById(R.id.btnpayment);
payment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogMessageDisplay.displayInfoMessage(UserData.this, "Payment Details", "There was no order made. \n Make an order and then tap the payment button.", AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
}
});
imagePhoto = (ImageView)findViewById(R.id.waiterPhoto);
imagePhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
file = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//file = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, file);
startActivityForResult(intent, REQ_CODE);
}
});
}
OnActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQ_CODE){
if(resultCode == RESULT_OK){
imagePhoto.setImageURI(file);
editor.putString(fileName, file.toString());
editor.commit();
Toast.makeText(UserData.this, "Your file has been saved at " + file, Toast.LENGTH_SHORT).show();
}else if(resultCode == RESULT_CANCELED){
Toast.makeText(UserData.this, "Action Cancelled", Toast.LENGTH_SHORT).show();
}
}
}
Thanks in advance!!!
Try this:
1) Initialize these:
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;
2) Modify your onCreate() like:
sharedPreferences = getSharedPreferences(fileName, MODE_PRIVATE);
editor = sharedPreferences.edit();
imagePhoto = (ImageView)findViewById(R.id.waiterPhoto);
String commited = sharedPreferences.getString(fileName, null);
if(commited != null) {
imagePhoto.setImageURI(Uri.parse(commited));
}
3) Modify your onActivityResult() like:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQ_CODE){
if(resultCode == RESULT_OK){
imagePhoto.setImageURI(file);
editor.putString(fileName, file.toString());
editor.commit();
}else if(resultCode == RESULT_CANCELED){
Toast.makeText(UserData.this, "Action Cancelled", Toast.LENGTH_SHORT).show();
}
}
}
And then you will have your desired effect. Hope it helps!!!
SharedPreferences are not meant for holding quantities of data such as imagery. They are meant for holding information about where an image is, or other small selections that the user has chosen.
If you want to save an image off, then you should do just that. Save the image within a local file within the application and then retrieve it later. You can save the location of that file in a SharedPreference object if you would like for you when you return. If it is only one, then you can replace it with the next one in the same file name the next time a picture is taken. This way you always have the latest image available since the last time that picture is taken; even after you shut down and restart the phone.

Android: Store Photo that i too in app in SharedPreferences

I'm trying to store a photo in SharedPreferences that it took from inside my app.
but i cant find any code that will help me with that.
can you help me with it please ?
public class RegisterActivity extends Activity {
private final int REQUEST_IMAGE = 100;
EditText nameEditText;
EditText phoneEditText;
EditText emailEditText;
EditText bdayEditText;
ImageView photoImageView;
ImageButton cameraButton;
Button saveButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
// String nameEt = nameEditText.getText().toString();
// String phoneEt = phoneEditText.getText().toString();
// String emailEt = emailEditText.getText().toString();
// String bdayEt = bdayEditText.getText().toString();
photoImageView = (ImageView) findViewById(R.id.photoImageView);
cameraButton = (ImageButton) findViewById(R.id.cameraImageButton);
cameraButton.setOnClickListener(cameraButtonListener);
saveButton = (Button) findViewById(R.id.saveButton);
saveButton.setOnClickListener(saveButtonListener);
}
private OnClickListener cameraButtonListener = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_IMAGE);
}
};
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE && resultCode == Activity.RESULT_OK) {
Bitmap userImage = (Bitmap) data.getExtras().get("data");
photoImageView.setImageBitmap(userImage);
}
};
private OnClickListener saveButtonListener = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
SharedPreferences sharedPreferences = getSharedPreferences(
"WaiterData", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
nameEditText = (EditText) findViewById(R.id.nameEditText);
phoneEditText = (EditText) findViewById(R.id.phoneEditText);
emailEditText = (EditText) findViewById(R.id.emailEditText);
bdayEditText = (EditText) findViewById(R.id.bdayEditText);
if (nameEditText.getText().length() > 0
&& phoneEditText.getText().length() > 0
&& emailEditText.getText().length() > 0
&& bdayEditText.getText().length() > 0) {
editor.putString("name", nameEditText.getText().toString());
editor.putString("phone", phoneEditText.getText().toString());
editor.putString("email", emailEditText.getText().toString());
editor.putString("bday", bdayEditText.getText().toString());
// move back to MainActivity
Intent intent = new Intent(RegisterActivity.this,
MainActivity.class);
startActivity(intent);
} else {
Toast.makeText(RegisterActivity.this,
"Please fill all The fields", Toast.LENGTH_SHORT)
.show();
}
}
};
}
and how can i can get the code out in other activity ?
The way I'm using to store images using SharedPreferences is to encode your image bitmap to a String then store that string, and then when needing the image retrieve that String and decode it again to a bitmap:
// declaring the sharedPreferences
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
// encoding image bitmap to String
int size = userImage.getWidth() * userImage.getHeight();
ByteArrayOutputStream stream = new ByteArrayOutputStream(
size);
userImage.compress(Bitmap.CompressFormat.JPEG, 50,
stream);
byte[] b = stream.toByteArray();
Editor editor = sharedPreferences.edit();
editor.putString("userImage", encodedImage);
editor.commit();
stream.close();
stream = null;
// then when needing that image again from the SharedPreferences
String decoded_image = sharedPreferences.getString("userImage", "default");
try{
byte[] decodedString = Base64.decode(decoded_image, Base64.DEFAULT);
Bitmap stored_userImage = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
// do whatever you want with it now
}catch(OutOfMemoryError oom){
}

How can I take a photo from gallery on a Dialog? - Android

I'm trying to take a photo from gallery on a Dialog but I couldn't. I cannot call startActivityResult() method to override on Dialog. Does anybody know a way to do it on Dialog?
Here is my code. (I need to do it in buttonG.setOnClickListener())
public class AddBirthdayDialog extends Dialog {
private Context context;
String name;
String sname;
private int day;
private int month;
private int year;
private byte[] imageByte;
private Bitmap imageBitmap;
private int RESULT_LOAD_IMAGE = 1;
final EditText textName;
final EditText textSname;
final DatePicker birthDate;
private DB myDB;
private SQLiteDatabase database;
private Person person = new Person();
public AddBirthdayDialog(final Context context) {
super(context);
this.context = context;
setCanceledOnTouchOutside(false);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.addbirthday_layout);
myDB = new DB(context);
textName = (EditText) findViewById(R.id.editTextname);
textSname = (EditText) findViewById(R.id.editTextsname);
birthDate = (DatePicker) findViewById(R.id.datePicker);
Button buttonG = (Button) findViewById(R.id.buttonUploadG);
buttonG.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
**//Need to call gallery and take a photo's bitmap or byte[] here.**
}
});
Button buttonC = (Button) findViewById(R.id.buttonUploadC);
buttonC.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
Button cancelButton = (Button) findViewById(R.id.cancelbutton);
cancelButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dismiss();
}
});
Button save = (Button) findViewById(R.id.buttonadd);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name = textName.getText().toString();
sname = textSname.getText().toString();
day = birthDate.getDayOfMonth();
month = birthDate.getMonth()+1;
year = birthDate.getYear();
final String dayStr = String.valueOf(day);
final String monthStr = String.valueOf(month+1);
final String yearStr = String.valueOf(year);
person.setName(name);
person.setSname(sname);
person.setDay(day);
person.setMonth(month);
person.setYear(year);
person.setDateStr(dayStr + "/" + monthStr + "/" + yearStr);
myDB.addBirthday(person);
if(context instanceof MainActivity)
((MainActivity)context).onResume();
dismiss();
}
});
}
}
Thanks in advance :)
inside your class:
#SuppressLint("NewApi")
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case SELECTED_PICTURE:
if (resultCode == RESULT_OK) {
Uri uri = data.getData();
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri, projection,
null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(projection[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
selectedImage = BitmapFactory.decodeFile(filePath);
d = new BitmapDrawable(selectedImage);
iv.setBackground(d);
update.setVisibility(View.VISIBLE);
}
break;
}
}
inside onClick:
Intent i = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, SELECTED_PICTURE);
Global variables:
private static final int SELECTED_PICTURE = 1;
Bitmap selectedImage;
What is context? If it is an activity, you can to start activity from your context-activity and handle onActivityResult in context-activity

how to store data permanently in listview

i use this (link or code) to store id and password of user
http://techblogon.com/android-login-registration-screen-with-sqlite-database-example/
problem is i want to store list view item permanently in my listview when user login against their account
private static int RESULT_LOAD_IMAGE = 1;
private String currentImageName = "ic_launcher";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_ad_layout);
Button saveButton = (Button) findViewById(R.id.buttonSaveAdd);
saveButton.setOnClickListener(this);
Button buttonaddimage = (Button) findViewById(R.id.buttonAddImage);
buttonaddimage.setOnClickListener(this);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want Create a new Add?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
Intent intent = new Intent(Create_adds_Activity.this, Button_mak.class);
startActivity(intent);
}
});
builder.show();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonAddImage:
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
break;
case R.id.buttonSaveAdd:
EditText editTextTitle = (EditText) findViewById(R.id.editTextTitle);
EditText editTextDes = (EditText) findViewById(R.id.editTextDescription);
EditText editTextOwner = (EditText) findViewById(R.id.editTextOwnerName);
EditText editTextOwnerEmail = (EditText) findViewById(R.id.editTextOwnerEmail);
EditText editTextPrice = (EditText) findViewById(R.id.editTextPrice);
//populating data object from the values received
//from view
String title = editTextTitle.getText().toString();
String description = editTextDes.getText().toString();
String ownerName = editTextOwner.getText().toString();
String ownerEmail = editTextOwnerEmail.getText().toString();
String pricce = editTextPrice.getText().toString();
Advertisement object = new Advertisement(title, description,
ownerName, ownerEmail, currentImageName, Integer.parseInt(pricce), 100);
Button_mak.ads.add(object);
this.finish();
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView10 = (ImageView) findViewById(R.id.creatae);
imageView10.setImageBitmap(BitmapFactory.decodeFile(picturePath));
currentImageName = ">>>"+picturePath;
}
i use array adapter
final Context context = this;
public static ArrayList<Advertisement> ads = new ArrayList<Advertisement>();
I would deffenitely recommend using SQLite to save your data.
In the beginning it might seem a bit complex, but when ur used to it, its an ease.
Here's a handy little tutorial: http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/

Categories

Resources