I'm working in android studios and I have this app that displays an imageView and has seekbars that allow you to edit the RGB values of the photo, but when I rotate from portrait to landscape (or vice versa) the imageView doesnt save and goes back to the original imageView and not the one that I selected. The Seekbars keep their values though. Any ideas on how I can used shared preferences to save the image? Thanks
public class MainActivity extends AppCompatActivity {
////////////////////////////////////////////////////////////////////////////
TextView textTitle;
ImageView image;
SeekBar barR, barG, barB, barAlpha;
int ColorValues;
private static final int SELECT_PHOTO = 100;
private static final int CAMERA_PIC_REQUEST = 101;
private static final String PREFS_NAME = "PrefsFile";
private static final String COLOR_VALUES = "ColorVals";
private static final String PICTURE = "Picture";
///////////////////////////////////////////////////////////////////////////
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textTitle = (TextView)findViewById(R.id.title);
image = (ImageView)findViewById(R.id.image);
barR = (SeekBar)findViewById(R.id.red);
barG = (SeekBar)findViewById(R.id.green);
barB = (SeekBar)findViewById(R.id.blue);
barAlpha = (SeekBar)findViewById(R.id.alpha);
barR.setOnSeekBarChangeListener(myOnSeekBarChangeListener);
barG.setOnSeekBarChangeListener(myOnSeekBarChangeListener);
barB.setOnSeekBarChangeListener(myOnSeekBarChangeListener);
barAlpha.setOnSeekBarChangeListener(myOnSeekBarChangeListener);
//default color
ColorValues = barAlpha.getProgress() * 0x1000000
+ barR.getProgress() * 0x10000
+ barG.getProgress() * 0x100
+ barB.getProgress();
image.setColorFilter(ColorValues, Mode.MULTIPLY);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
ColorValues = settings.getInt(COLOR_VALUES, ColorValues);
}
//menu/////////////////
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.savePicture:
Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();
MediaStore.Images.Media.insertImage
(getContentResolver(), bitmap, "yourTitle", "yourDescription");
}
return true;
}
//on click function////////////////
public void selectPicture(View view) {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
}
public void takePicture(View view){
try{
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
} catch(Exception e){
e.printStackTrace();
}
}
//activity///////////////
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case SELECT_PHOTO:
if (resultCode == RESULT_OK) {
Uri selectedImage = data.getData();
InputStream imageStream = null;
try {
imageStream = getContentResolver().openInputStream(selectedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream);
image.setImageURI(selectedImage);// To display selected image in image view
break;
}
case CAMERA_PIC_REQUEST:
try {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
thumbnail = Bitmap.createScaledBitmap(thumbnail, 700, 500, true);
ImageView imageView = (ImageView) findViewById(R.id.image);
image.setImageBitmap(thumbnail);
} catch (Exception ee) {
ee.printStackTrace();
}
break;
}
}
//warning before exit
#Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Closing Activity")
.setMessage("Are you sure you want to close\nthis activity? \n\nProgress will NOT be saved ")
.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton("No", null);
AlertDialog dialog = builder.show();
TextView messageText = (TextView)dialog.findViewById(android.R.id.message);
messageText.setGravity(Gravity.CENTER);
dialog.show();
}
//edit picture
OnSeekBarChangeListener myOnSeekBarChangeListener = new OnSeekBarChangeListener(){
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
//Colorize ImageView
int newColor = barAlpha.getProgress() * 0x1000000
+ barR.getProgress() * 0x10000
+ barG.getProgress() * 0x100
+ barB.getProgress();
image.setColorFilter(newColor, Mode.MULTIPLY);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
ColorValues = newColor;
editor.putInt(COLOR_VALUES, ColorValues);
// Commit the edits
editor.commit();
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {}
};
#Override
protected void onSaveInstanceState(Bundle icicle) {
super.onSaveInstanceState(icicle);
icicle.putInt(COLOR_VALUES, ColorValues);
}
this is what it would look like if I saved the colorvalues(which are somehow already being saved without this code)
if (savedInstanceState != null) {
colorvalues = savedInstanceState.getInt("COLOR_VALUES");
image = savedInstanceState.get??????????????????????
}
image is not an Int so what values should be put there?
also to get the exact RGB values like RBar = savedInstanceState.getInt doesnt works becuase Rbar is a seekbar not an int???
Related
I am using togglebutton to switch between images obtained using Intent (selected from sdcard). However i have an error after i select image. Basically my idea is to browse an image and display on (originalimage) Imageview based on the state of togglebutton. Moreover when i change the state of togglebutton i should see different images.
public class LoadImage extends AppCompatActivity {
public static final int REQUEST_CODE = 10;
ToggleButton togglebtn;
Bitmap imgb;
Button browseimagebtn;
Bitmap operation;
ImageView originalimage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.image_load);
originalimage = (ImageView) findViewById(R.id.originalimage);
browseimagebtn = (Button) findViewById(R.id.browseimagebtn);
//browse image button clicked
browseimagebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent rawIntent = new Intent(Intent.ACTION_PICK);
File pictureDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
String pictureDirectoryPath = pictureDirectory.getPath();
Uri data=Uri.parse(pictureDirectoryPath);
rawIntent.setDataAndType(data, "image/*");
startActivityForResult(rawIntent, REQUEST_CODE);
}
});
//browse image button long pressed
browseimagebtn.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Toast.makeText(getApplicationContext(), "Loads image from Picture Gallery", Toast.LENGTH_SHORT).show();
return true;
}
});
//toggle switch to decide which image to be displayed on screen
togglebtn = (ToggleButton) findViewById(R.id.togglebtn);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode==RESULT_OK){
if(requestCode==REQUEST_CODE){
final float red = (float) 0.299;
final float green = (float) 0.587;
final float blue = (float) 0.114;
final Uri imagef = data.getData();
InputStream streamI;
try {
streamI = getContentResolver().openInputStream(imagef);
//Create bitmap from selected image
Bitmap imgb = BitmapFactory.decodeStream(streamI);
//Define rows and columns of selected image
int rows = imgb.getHeight();int cols = imgb.getWidth();
operation = Bitmap.createBitmap(cols, rows, imgb.getConfig());
//Convert original image to Gray Image
for (int i=0;i<cols;i++){
for(int j=0;j<rows;j++){
int p = imgb.getPixel(i,j);
int r = Color.red(p);
int g = Color.green(p);
int b = Color.blue(p);
r = (int) (red*r);
g = (int) (green*g);
b = (int) (blue*b);
int gray = (int) (r*0.299+g*0.587+b*0.114);
operation.setPixel(i, j, Color.argb(Color.alpha(p), gray, gray, gray));
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();}
}
togglebtn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
Toast.makeText(getApplicationContext(), "if is checked", Toast.LENGTH_SHORT).show();
originalimage.setImageBitmap(operation);
} else {
Toast.makeText(getApplicationContext(), "else is checked", Toast.LENGTH_SHORT).show();
originalimage.setImageBitmap(imgb);
}
}
});
}
}
}
Not sure if this fixes everything but:
Bitmap imgb -> will always be null.
Fix:
In your onActivityResult:
try {
streamI = getContentResolver().openInputStream(imagef);
//Create bitmap from selected image
imgb = BitmapFactory.decodeStream(streamI);
.....
}
Included Android permission.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
iam successfully getting the image from the SD card to the canvas but i want to erase some part of the loaded image.... suggest me suitable code this is my main activity and i can draw on canvas save the content and i can erase the drawn content but i have to erase the loaded image please suggest me
//custom drawing view
private DrawingView drawView;
//buttons
private ImageButton currPaint, drawBtn, eraseBtn, newBtn, saveBtn,loadBtn;
//sizes
private float Brush;
Bitmap bitmap;
int mWidth;
int mHeight;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWidth=mHeight=0;
//get drawing view
drawView = (DrawingView)findViewById(R.id.drawing);
//get the palette and first color button
LinearLayout paintLayout = (LinearLayout)findViewById(R.id.paint_colors);
currPaint = (ImageButton)paintLayout.getChildAt(0);
currPaint.setImageDrawable(getResources().getDrawable(R.drawable.paint_pressed));
//sizes from dimensions
Brush = getResources().getInteger(R.integer.small_size);
//draw button
drawBtn = (ImageButton)findViewById(R.id.draw_btn);
drawBtn.setOnClickListener(this);
//set initial size
drawView.setBrushSize(Brush);
//erase button
eraseBtn = (ImageButton)findViewById(R.id.erase_btn);
eraseBtn.setOnClickListener(this);
//new button
newBtn = (ImageButton)findViewById(R.id.new_btn);
newBtn.setOnClickListener(this);
//save button
saveBtn = (ImageButton)findViewById(R.id.save_btn);
saveBtn.setOnClickListener(this);
//load button
loadBtn = (ImageButton)findViewById(R.id.load_btn);
loadBtn.setOnClickListener(this);
}
private Bitmap getBitmapFromUri(Uri data){
Bitmap bitmap = null;
// Starting fetch image from file
InputStream is=null;
try {
is = getContentResolver().openInputStream(data);
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
// BitmapFactory.decodeFile(path, options);
BitmapFactory.decodeStream(is, null, options);
// Calculate inSampleSize
// options.inSampleSize = calculateInSampleSize(options, mWidth, mHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
is = getContentResolver().openInputStream(data);
bitmap = BitmapFactory.decodeStream(is,null,options);
if(bitmap==null){
Toast.makeText(getBaseContext(), "Image is not Loaded",Toast.LENGTH_SHORT).show();
return null;
}
is.close();
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch(NullPointerException e){
e.printStackTrace();
}
return bitmap;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, intent);
if (requestCode == 10 && resultCode == RESULT_OK && null != intent) {
Uri data = intent.getData();
Bitmap bitmap = getBitmapFromUri(data);
if(bitmap!=null){
drawView.addBitmap(bitmap);
}
}
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
// TODO Auto-generated method stub
super.onWindowFocusChanged(hasFocus);
mWidth = drawView.getWidth();
mHeight = drawView.getHeight();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putInt("width", mWidth);
outState.putInt("height", mHeight);
if(drawView.getBitmap()!=null){
outState.putParcelable("bitmap", drawView.getBitmap());
}
super.onSaveInstanceState(outState);
}
public void paintClicked(View view){
//use chosen color
//set erase false
drawView.setErase(false);
drawView.setPaintAlpha(100);
drawView.setBrushSize(Brush);
if(view!=currPaint){
ImageButton imgView = (ImageButton)view;
String color = view.getTag().toString();
drawView.setColor(color);
//update ui
imgView.setImageDrawable(getResources().getDrawable(R.drawable.paint_pressed));
currPaint.setImageDrawable(getResources().getDrawable(R.drawable.paint));
currPaint=(ImageButton)view;
}
}
#Override
public void onClick(View view){
if(view.getId()==R.id.draw_btn){
drawView.setErase(false);
drawView.setBrushSize(Brush);
drawView.setLastBrushSize(Brush);
}
else if(view.getId()==R.id.erase_btn){
//switch to erase - choose size
final Dialog brushDialog = new Dialog(this);
drawView.setErase(true);
drawView.setBrushSize(getResources().getInteger(R.integer.medium_size));
brushDialog.dismiss();
}
if(view.getId()==R.id.new_btn){
//new button
AlertDialog.Builder newDialog = new AlertDialog.Builder(this);
newDialog.setTitle("Clear Drawing");
newDialog.setMessage("Are You Sure To Clear (you will lose the current drawing)?");
newDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener(){
#SuppressLint("NewApi") public void onClick(DialogInterface dialog, int which){
drawView.deleteBitmap();
drawView.startNew();
dialog.dismiss();
}
});
newDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which){
dialog.cancel();
}
});
newDialog.show();
}
else if(view.getId()==R.id.save_btn){
//save drawing
AlertDialog.Builder saveDialog = new AlertDialog.Builder(this);
saveDialog.setTitle("Save drawing");
saveDialog.setMessage("Save drawing to device Gallery?");
saveDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which){
//save drawing
drawView.setDrawingCacheEnabled(true);
//attempt to save
String imgSaved = MediaStore.Images.Media.insertImage(
getContentResolver(), drawView.getDrawingCache(),
UUID.randomUUID().toString()+".png", "drawing");
//feedback
if(imgSaved!=null){
Toast savedToast = Toast.makeText(getApplicationContext(),
"Drawing saved to Gallery!", Toast.LENGTH_SHORT);
savedToast.show();
}
else{
Toast unsavedToast = Toast.makeText(getApplicationContext(),
"Oops! Image could not be saved.", Toast.LENGTH_SHORT);
unsavedToast.show();
}
drawView.destroyDrawingCache();
}
});
saveDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which){
dialog.cancel();
}
});
saveDialog.show();
}
else if (view.getId()==R.id.load_btn){
Intent i = new Intent();
i.setType("image/*");
i.setAction(Intent.ACTION_GET_CONTENT);
Intent customChooserIntent = Intent.createChooser(i, "Pick an image");
startActivityForResult(customChooserIntent, 10);
}
}
}
I'm having a problem. I wrote an app to select and pass an image to another activity and have it shown on the screen of second activity. However, I found that my app crashes after receiving a high resolution image. I sent a 1440x810 image (size is 166KB) in my test.
Below is my code:
First Activity
public class MainActivity extends ActionBarActivity {
private Button button;
private Intent intent ;
public final static String EXTRA_BITMAP_BYTE_STREAM = "EXTRA_BITMAP_BYTE_STREAM";
private static final int PICK_IMAGE = 1;
private String imageFilePath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
setActionListener();
Intent getImgIntent = new Intent();
getImgIntent .setType("image/*");
getImgIntent .setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(getImgIntent , "Select Picture"), PICK_IMAGE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == PICK_IMAGE && data != null && data.getData() != null) {
Uri _uri = data.getData();
//User had pick an image.
Cursor cursor = getContentResolver().query(_uri, new String[] { android.provider.MediaStore.Images.ImageColumns.DATA }, null, null, null);
cursor.moveToFirst();
//Link to the image
imageFilePath = cursor.getString(0);
cursor.close();
}
super.onActivityResult(requestCode, resultCode, data);
}
private void setActionListener(){
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Bitmap resImage;
ByteArrayOutputStream outImageByteArrayOutputStream = new ByteArrayOutputStream();
byte [] outImageByteArray;
intent = new Intent(MainActivity.this,SecMainActivity.class);
File file = new File(imageFilePath);
resImage = BitmapFactory.decodeFile(imageFilePath);
resImage.compress(Bitmap.CompressFormat.JPEG,100,outImageByteArrayOutputStream);
outImageByteArray = outImageByteArrayOutputStream.toByteArray();
intent.putExtra(EXTRA_BITMAP_BYTE_STREAM, outImageByteArray);
startActivity(intent);
}
});
}
}
Second Activity
public class SecMainActivity extends ActionBarActivity {
private Button returnButton;
private ImageView receivedImageView;
Intent intent;
Thread handleBitmapImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sec_main);
findViews();
handleReceivedInfoToUI();
setActionListener();
}
#Override
protected void onStart(){
super.onStart();
handleBitmapImage.start();
}
private void findViews(){
returnButton = (Button) findViewById(R.id.returnButton);
receivedImageView = (ImageView) findViewById(R.id.receivedImageView);
}
private void handleReceivedInfoToUI(){
intent = getIntent();
handleBitmapImage = new Thread(new Runnable(){
#Override
public void run(){
byte [] receivedImageByteArray = intent.getByteArrayExtra(MainActivity.EXTRA_BITMAP_BYTE_STREAM);
final Bitmap bmp = BitmapFactory.decodeByteArray(receivedImageByteArray, 0, receivedImageByteArray.length);
runOnUiThread(new Runnable(){
#Override
public void run(){
setReceivedImage(bmp);
}
});
}
});
}
private void setActionListener(){
returnButton.setOnClickListener( new OnClickListener(){
#Override
public void onClick(View v){
finish();
}
});
}
public void setReceivedImage(Bitmap bmp){
receivedImageView.setImageBitmap(bmp);
}
}
Do I have to compress and resize my received image to solve this problem?
If you pass bitmap width and height then use below function.
public Bitmap getResizedBitmap(Bitmap image, int bitmapWidth,
int bitmapHeight) {
return Bitmap.createScaledBitmap(image, bitmapWidth, bitmapHeight,
true);
}
if you want bitmap ratio same and reduce bitmap size. then pass your maximum size bitmap. you can use this function
public Bitmap getResizedBitmap(Bitmap image, int maxSize) {
int width = image.getWidth();
int height = image.getHeight();
float bitmapRatio = (float)width / (float) height;
if (bitmapRatio > 0) {
width = maxSize;
height = (int) (width / bitmapRatio);
} else {
height = maxSize;
width = (int) (height * bitmapRatio);
}
return Bitmap.createScaledBitmap(image, width, height, true);
}
I'm trying to used sharedpreferences for when a user chooses a specific custom image they want in their storage for a part of a grid of images. I want the image they chose to show up even after they close the application and reopen it. The problem I'm having is that the sharedpreferences don't seem to be working. Nothing shows up as the background image for the grid item they've selected once they've closed the app or even just pressed the back button.
Do I have to create a sharedpreferences file myself? I can't figure out how to get to it or create one if so using androidstudio.
Here's my code for the class (Sorry if it's long and messy...I am new to coding and still testing things):
public class editCreations extends Activity {
public int mPosition = 0;
protected static Sounds sound = new Sounds();
private static int RESULT_LOAD_IMAGE = 1;
private MediaRecorder mRecorder;
private MediaPlayer mPlayer;
private String mOutputFile = Environment.getExternalStorageDirectory().getAbsolutePath();
private Drawable mImageFileName;
private Button recordBtn;
private Button stopBtn;
private Button playBtn;
private Button stopPlayBtn;
private ImageButton imgBtn;
private Drawable bg;
private String mPicturePath;
private ImageAdapter img = new ImageAdapter(this);
View.OnClickListener playListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(editCreations.this, "test", Toast.LENGTH_SHORT);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create);
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
mRecorder.setOutputFile(mOutputFile);
recordBtn = (Button)findViewById(R.id.create_record_button);
recordBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
start(view);
}
});
stopBtn = (Button)findViewById(R.id.create_stop_record_button);
stopBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
stop(view);
}
});
playBtn = (Button)findViewById(R.id.create_play_button);
playBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
play(view);
}
});
stopPlayBtn = (Button)findViewById(R.id.create_stop_button);
stopPlayBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
stopPlay(view);
}
});
imgBtn = (ImageButton)findViewById(R.id.imageButton);
Intent extra = getIntent();
Bundle extras = extra.getExtras();
// gave mPosition a default int to debug and find problem -> found it
mPosition = extras.getInt("position");
getSelectedFile(mPosition);
imgBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(
Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
}
public void start (View view) {
try {
mRecorder.prepare();
mRecorder.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
recordBtn.setEnabled(false);
stopBtn.setEnabled(true);
Toast.makeText(editCreations.this, mPosition + "!", Toast.LENGTH_SHORT).show();
}
public void stop(View view){
try {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
stopBtn.setEnabled(false);
recordBtn.setEnabled(true);
Toast.makeText(getApplicationContext(), "Stop recording...",
Toast.LENGTH_SHORT).show();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (RuntimeException e) {
e.printStackTrace();
}
}
public void play(View view) {
try{
mPlayer = new MediaPlayer();
mPlayer.setDataSource(mOutputFile);
mPlayer.prepare();
mPlayer.start();
playBtn.setEnabled(false);
stopPlayBtn.setEnabled(true);
Toast.makeText(getApplicationContext(), "Start play the recording...",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
public void stopPlay(View view) {
try {
if (mPlayer != null) {
mPlayer.stop();
mPlayer.release();
mPlayer = null;
playBtn.setEnabled(true);
stopPlayBtn.setEnabled(false);
Toast.makeText(getApplicationContext(), "Stop playing the recording...",
Toast.LENGTH_SHORT).show();
}
} catch (Exception e){
e.printStackTrace();
}
}
public void getSoundPosition(int position) {
mOutputFile = mOutputFile + "/Lollatone_clip_" + mPosition + ".3gpp";
// use to get proper image and sound files and edit output file to proper name
}
public void getSelectedFile(int position) {
switch (mPosition) {
case 0:
imgBtn.setBackgroundResource(R.drawable.sample_0);
imgBtn.refreshDrawableState();
break;
case 1:
imgBtn.setImageBitmap(BitmapFactory.decodeFile(mPicturePath));
imgBtn.refreshDrawableState();
break;
case 2:
imgBtn.setImageBitmap(BitmapFactory.decodeFile(mPicturePath));
imgBtn.refreshDrawableState();
break;
case 3:
imgBtn.setImageBitmap(BitmapFactory.decodeFile(mPicturePath));
imgBtn.refreshDrawableState();
break;
case 4:
imgBtn.setBackgroundResource(R.drawable.sample_4);
imgBtn.refreshDrawableState();
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.edit_creations, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#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]);
mPicturePath = cursor.getString(columnIndex);
cursor.close();
imgBtn.setImageBitmap(BitmapFactory.decodeFile(mPicturePath));
imgBtn.refreshDrawableState();
// String picturePath contains the path of
// selected image
}
}
protected void onPause() {
super.onPause();
//need an editor object to make preference changes
// all objects are from android.context.Context
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("img_" + mPosition, mPicturePath);
editor.commit();
}
protected void onResume() {
super.onResume();
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
mPicturePath = sharedPref.getString("img_" + mPosition, "img_" + mPosition);
}
}
You are using SharedPreferences correctly but you are not placing the code in the right activity lifecycle methods. You are reading the preference on onCreate() and saving on onStop() so maybe what you can do it save the preference on onPause() (to make sure it gets saved earlier) and reload on onResume() instead of onCreate() (the latter only occurs once in the life cycle of an activity).
Also, you might want to check if Context.getSharedPreferences() would be a better choice for this, since it's shared between more than just one activity.
I have successfully been able to store user entered information into parse, but I have been having difficulty storing images into to parse, to be able to retrieve at a later date.
To clarify this, below is the code I have used for my profile creation activity, an activity that is prompted after the user has signing using social media and responds to a series of questions like age, preferred name, and where those information are later updated in the parse database and added to the current user.
Also in the activity, the user is already able to upload a picture from their device, my issue now resolves around taking that uploaded picture and storing it on parse, and associating the image with the current user who has signing using their social media account - the social media integration is done through parse.
I have looked into the following guide, but is still greatly confused.https://www.parse.com/docs/android_guide#files
Now I have tried to accomplish this, and have left my comments in the code below.
Any assistance would be greatly appreciated. Thanks in advance.
public class ProfileCreation extends Activity {
private static final int RESULT_LOAD_IMAGE = 1;
FrameLayout layout;
Button save;
protected EditText mName;
protected EditText mAge;
protected EditText mHeadline;
protected ImageView mprofilePicture;
protected Button mConfirm;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_creation);
RelativeLayout v = (RelativeLayout) findViewById(R.id.main);
v.requestFocus();
Parse.initialize(this, "ID", "ID");
mName = (EditText)findViewById(R.id.etxtname);
mAge = (EditText)findViewById(R.id.etxtage);
mHeadline = (EditText)findViewById(R.id.etxtheadline);
mprofilePicture = (ImageView)findViewById(R.id.profilePicturePreview);
mConfirm = (Button)findViewById(R.id.btnConfirm);
mConfirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name = mName.getText().toString();
String age = mAge.getText().toString();
String headline = mHeadline.getText().toString();
age = age.trim();
name = name.trim();
headline = headline.trim();
if (age.isEmpty() || name.isEmpty() || headline.isEmpty()) {
AlertDialog.Builder builder = new AlertDialog.Builder(ProfileCreation.this);
builder.setMessage(R.string.signup_error_message)
.setTitle(R.string.signup_error_title)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
else {
// create the new user!
setProgressBarIndeterminateVisibility(true);
ParseUser currentUser = ParseUser.getCurrentUser();
/* This is the section where the images is converted, saved, and uploaded. I have not been able Locate the image from the ImageView, where the user uploads the picture to imageview from either their gallery and later on from facebook */
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
/*fron image view */);
// Convert it to byte
ByteArrayOutputStream stream = new ByteArrayOutputStream();
// Compress image to lower quality scale 1 - 100
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] image = stream.toByteArray();
// Create the ParseFile
ParseFile file = new ParseFile("profilePicture.png", image);
// Upload the image into Parse Cloud
file.saveInBackground();
// Create a column named "ImageName" and set the string
currentUser.put("ImageName", "AndroidBegin Logo");
// Create a column named "ImageFile" and insert the image
currentUser.put("ProfilePicture", file);
// Create the class and the columns
currentUser.saveInBackground();
currentUser.put("name", name);
currentUser.put("age", age);
currentUser.put("headline", headline);
currentUser.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
setProgressBarIndeterminateVisibility(false);
if (e == null) {
// Success!
Intent intent = new Intent(ProfileCreation.this, MoodActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
else {
AlertDialog.Builder builder = new AlertDialog.Builder(ProfileCreation.this);
builder.setMessage(e.getMessage())
.setTitle(R.string.signup_error_title)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
}
});
}
}
});
SeekBar seekBar = (SeekBar) findViewById(R.id.seekBarDistance);
final TextView seekBarValue = (TextView) findViewById(R.id.seekBarDistanceValue);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
seekBarValue.setText(String.valueOf(progress));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}); // Add this
Button mcancel = (Button)findViewById(R.id.btnBack);
mcancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ProfileCreation.this.startActivity(new Intent(ProfileCreation.this, LoginActivity.class));
}
});
SeekBar seekBarMinimum = (SeekBar) findViewById(R.id.seekBarMinimumAge);
final TextView txtMinimum = (TextView) findViewById(R.id.tMinAge);
seekBarMinimum.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
txtMinimum.setText(String.valueOf(progress));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}); // Add this
SeekBar seekBarMaximum = (SeekBar) findViewById(R.id.seekBarMaximumAge);
final TextView txtMaximum = (TextView) findViewById(R.id.tMaxAge);
seekBarMaximum.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
txtMaximum.setText(String.valueOf(progress));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}); // Add this
Button buttonLoadImage = (Button) findViewById(R.id.btnPictureSelect);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
}
#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 imageView = (ImageView) findViewById(R.id.profilePicturePreview);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
private byte[] readInFile(String path) throws IOException {
// TODO Auto-generated method stub
byte[] data = null;
File file = new File(path);
InputStream input_stream = new BufferedInputStream(new FileInputStream(
file));
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
data = new byte[16384]; // 16K
int bytes_read;
while ((bytes_read = input_stream.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, bytes_read);
}
input_stream.close();
return buffer.toByteArray();
}
}
You need to wait for the file to finish saving before you add it to the user.
Try adding a completion block to your file.saveInBackground() call, and moving all the currentUser manipulation into that completion block.