Issues uploading images - java

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.

Related

Shared Preferences ImageView

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???

can i erase the part or full of a image which is loaded from the SD card to the canvas or DrawView

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

check to see if a button have been clicked

In my activity I am able to upload a picture from the gallery.
I would like to check if the user has indeed uploaded the picture prior to hitting confirm. One way of achieving this, I want to check if the upload picture button has been clicked.
I also want to see if an edittext has been filled through the following code but is struggling with image:
String name = mName.getText().toString();
// Number age = mAge.getText(;
String headline = mHeadline.getText().toString();
// age = ((String) age).trim();
name = name.trim();
headline = headline.trim();
if (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!
below is how the image is being selected:
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();
}
Update:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_creation);
feedBack = new FeedbackDialog(this, "AF-46D8F2A319EA-0A");
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);
male = (RadioButton)findViewById(R.id.rimale);
female = (RadioButton)findViewById(R.id.rifemale);
lmale = (RadioButton)findViewById(R.id.rlmale);
lfemale = (RadioButton)findViewById(R.id.rlfemale);
seekBarMinimum = (SeekBar) findViewById(R.id.sbseekBarMinimumAge);
seekBarMaximum = (SeekBar) findViewById(R.id.sbseekBarMaximumAge);
seekBarDistance = (SeekBar) findViewById(R.id.sbseekBarDistance);
seekBarActivityDistance = (SeekBar) findViewById(R.id.sbseekBarActivityDistance);
mConfirm = (Button)findViewById(R.id.btnConfirm);
mConfirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
findViewById(R.id.btnConfirm).setBackgroundResource(R.drawable.gray_bac);
String name = mName.getText().toString();
// Number age = mAge.getText(;
String headline = mHeadline.getText().toString();
// age = ((String) age).trim();
name = name.trim();
headline = headline.trim();
if (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();
if(male.isChecked())
gender = "Male";
else
gender = "Female";
if(lmale.isChecked())
lgender = "Male";
else
lgender = "Female";
age = Integer.parseInt(mAge.getText().toString());
ParseInstallation installation = ParseInstallation.getCurrentInstallation();
installation.put("Name", name);
installation.put("UserAge", age);
installation.put("Headline", headline);
installation.put("Gender", gender);
installation.put("Looking_Gender", lgender);
installation.put("Minimum_Age", seekBarMinimum.getProgress());
installation.put("Maximum_Age", seekBarMaximum.getProgress());
installation.put("Maximum_Distance_Match", seekBarDistance.getProgress());
installation.put("Maximum_Distance_Activity", seekBarActivityDistance.getProgress());
installation.saveInBackground();
currentUser.put("Name", name);
currentUser.put("UserAge", age);
currentUser.put("Headline", headline);
currentUser.put("Gender", gender);
currentUser.put("Looking_Gender", lgender);
currentUser.put("Minimum_Age", seekBarMinimum.getProgress());
currentUser.put("Maximum_Age", seekBarMaximum.getProgress());
currentUser.put("Maximum_Distance_Match", seekBarDistance.getProgress());
currentUser.put("Maximum_Distance_Activity", seekBarActivityDistance.getProgress());
/* 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 */
ImageView myImgView = (ImageView) findViewById(R.id.profilePicturePreview);
Bitmap bitmap = ((BitmapDrawable) myImgView.getDrawable()).getBitmap();
// 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 "Profile Picture" and set the string
currentUser.put("ImageName", "Profile Picture");
// Create a column named "ImageFile" and insert the image
currentUser.put("ProfilePicture", file);
currentUser.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
setProgressBarIndeterminateVisibility(false);
if (e == null) {
// Success!
Intent intent = new Intent(ProfileCreation.this, betaEventsActivity.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_message)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
}
});
}
}
});
SeekBar seekBar = (SeekBar) findViewById(R.id.sbseekBarDistance);
final TextView seekBarValue = (TextView) findViewById(R.id.tvseekBarDistanceValue);
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 seekBarActivity = (SeekBar) findViewById(R.id.sbseekBarActivityDistance);
final TextView seekBarActivityValue = (TextView) findViewById(R.id.tvseekBarActivityDistanceValue);
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
SeekBar seekBarMinimum = (SeekBar) findViewById(R.id.sbseekBarMinimumAge);
final TextView txtMinimum = (TextView) findViewById(R.id.tvMinAge);
seekBarMinimum.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
if (progress <= 18) {
seekBar.setProgress(18);
} else {
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.sbseekBarMaximumAge);
final TextView txtMaximum = (TextView) findViewById(R.id.tvMaxAge);
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 can set a boolean to true, if image is selected by user in onActivityResult
//global variable
boolean imagePicked = false;
//In onActivityResult change its value
#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) {
imagePicked = true;
//other things
}
else {
imagePicked = false;
//other things
}
In last button click check imagePicked is true or false and proceed accordingly.
Hope it helps.

Storing and retrieving user uploaded images in parse

I have successfully been able to store user entered information into parse, but I haven't figure out how to do store a user uploaded image that would be associated with the current user in parse, and to retrieve a user image at a later time.
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
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 Button mConfirm;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_creation);
Parse.initialize(this, "ID", "ID");
mName = (EditText)findViewById(R.id.etxtname);
mAge = (EditText)findViewById(R.id.etxtage);
mHeadline = (EditText)findViewById(R.id.etxtheadline);
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();
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();
}
}
});
}
}
});
save = (Button) findViewById(R.id.button2);
String picturePath = PreferenceManager.getDefaultSharedPreferences(this).getString("picturePath", "");
if (!picturePath.equals("")) {
ImageView imageView = (ImageView) findViewById(R.id.profilePicturePreview);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
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
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);
}
});
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Locate the image in res >
Bitmap bitmap = BitmapFactory.decodeFile("picturePath");
// Convert it to byte
ByteArrayOutputStream stream = new ByteArrayOutputStream();
// Compress image to lower quality scale 1 - 100
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
Object image = null;
try {
String path = null;
image = readInFile(path);
} catch (Exception e) {
e.printStackTrace();
}
// Create the ParseFile
ParseFile file = new ParseFile("picturePath", (byte[]) image);
// Upload the image into Parse Cloud
file.saveInBackground();
// Create a New Class called "ImageUpload" in Parse
ParseObject imgupload = new ParseObject("Image");
// Create a column named "ImageName" and set the string
imgupload.put("Image", "picturePath");
// Create a column named "ImageFile" and insert the image
imgupload.put("ImageFile", file);
// Create the class and the columns
imgupload.saveInBackground();
// Show a simple toast message
}
});
}
#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();
}
}
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.
Read the docs on files and on the response type when a file is upload to parse.com
"media":{"__type":"File","name":"e580f231-...-picf1","url":"http://files.parse.com/..52d6-picf1"}
So, after POST on the file to parse, you have a logical FILE entity that you can then point to in another class.
In that other clase , you can also point to the user who created the FILE.
Class2 {"createdby" : pointer($user), "media" : pointer($file)}
With that, you have a separate class with 2 , pointer types ( toUser, toFile ) and the col headers on the data browser will show :
pointer<_User> for the user
file for the file

Camera activity does not start on the second time

I have making a tab based app. There are three tabs. One of the tab is used to camera. So when I press camera tab then it opens up camera activity so that I could take pictures. Until here it works fine. When I take picture then that picture is showed in ImageView. From here when I press any other tab and then I press camera tab then camera activity does not start. It keep shows me that previous image on ImageView. What I want is whenever user taps on camera tab then it should opens camera activity. How can I achieve this effect?
Here is my code. Below os oncreate method which is in camera activity. So when camera tab is pressed it opens this activity.
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.camera);
userFunctions = new UserFunctions();
globalUID = getIntent().getExtras().getString("globalUID");
Toast.makeText(getApplicationContext(), globalUID, Toast.LENGTH_LONG).show();
ivUserImage = (ImageView)findViewById(R.id.ivUserImage);
bUpload = (Button)findViewById(R.id.bUpload);
openCamera();
}
private void openCamera() {
i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, CameraResult);
}
Update
I did this but still the same problem
boolean flag = true;
#Override
protected void onResume() {
super.onResume();
//flag = true;
if(flag) {
openCamera();
flag = false;
}
}
Edit
After following Imran's answer my code looks like this now. I am also adding additional code. But this code still does not work.
public class Camera extends Activity {
ImageView ivUserImage;
Button bUpload;
Intent i;
int CameraResult = 0;
Bitmap bmp;
public String globalUID;
UserFunctions userFunctions;
String photoName;
InputStream is;
String largeImagePath;
int serverResponseCode = 0;
public static boolean flag = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.camera);
userFunctions = new UserFunctions();
globalUID = getIntent().getExtras().getString("globalUID");
//flag = getIntent().getExtras().getBoolean("flag");
Toast.makeText(getApplicationContext(), globalUID, Toast.LENGTH_LONG).show();
ivUserImage = (ImageView)findViewById(R.id.ivUserImage);
bUpload = (Button)findViewById(R.id.bUpload);
//openCamera();
if(flag ==true)
openCamera();
}
#Override
protected void onResume() {
super.onResume();
if(flag==true)
openCamera();
}
private void openCamera() {
i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, CameraResult);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
flag = false;
if(resultCode == RESULT_OK) {
//set image taken from camera on ImageView
Bundle extras = data.getExtras();
bmp = (Bitmap) extras.get("data");
ivUserImage.setImageBitmap(bmp);
//Create new Cursor to obtain the file Path for the large image
String[] largeFileProjection = {
MediaStore.Images.ImageColumns._ID,
MediaStore.Images.ImageColumns.DATA
};
String largeFileSort = MediaStore.Images.ImageColumns._ID + " DESC";
Cursor myCursor = this.managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, largeFileProjection, null, null, largeFileSort);
try {
myCursor.moveToFirst();
//This will actually give you the file path location of the image.
largeImagePath = myCursor.getString(myCursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATA));
File f = new File("" + largeImagePath);
photoName = f.getName();
bUpload.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new Upload().execute(largeImagePath, globalUID, photoName);
}
});
} finally {
myCursor.close();
}
}
}
}
Here is my tab activity code
public class DashboardActivity extends TabActivity {
UserFunctions userFunctions;
public String globalUID;
DatabaseHandler db;
boolean flag = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.dashboard);
db = new DatabaseHandler(getApplicationContext());
// Check login status in database
userFunctions = new UserFunctions();
if(userFunctions.isUserLoggedIn(getApplicationContext())){
//globalUID = getIntent().getExtras().getString("globalUID");
HashMap<String, String> data = db.getUserDetails();
globalUID = data.get("uid");
Resources res = getResources(); // Resource object to get Drawables
TabHost tabHost = getTabHost(); // The activity TabHost
TabHost.TabSpec spec; // Resusable TabSpec for each tab
Intent intent; // Reusable Intent for each tab
//Home
intent = new Intent(this, Home.class);
intent.putExtra("globalUID", globalUID);
spec = tabHost.newTabSpec("home").setIndicator("", res.getDrawable(R.drawable.home_icon)).setContent(intent);
tabHost.addTab(spec);
//Camera
intent = new Intent(this, Camera.class);
intent.putExtra("globalUID", globalUID);
//intent.putExtra("flag", flag);
spec = tabHost.newTabSpec("camera").setIndicator("", res.getDrawable(R.drawable.camera_icon)).setContent(intent);
tabHost.addTab(spec);
//Albums
intent = new Intent(this, Albums.class);
intent.putExtra("globalUID", globalUID);
spec = tabHost.newTabSpec("albums").setIndicator("", res.getDrawable(R.drawable.albums_icon)).setContent(intent);
tabHost.addTab(spec);
//tabHost.setCurrentTab(1);
} else {
// user is not logged in show login screen
Intent login = new Intent(getApplicationContext(), LoginActivity.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(login);
// Closing dashboard screen
finish();
}
}
}
Here is my whole camera activity
public class Camera extends Activity {
ImageView ivUserImage;
Button bUpload;
Intent i;
int CameraResult = 0;
Bitmap bmp;
public String globalUID;
UserFunctions userFunctions;
String photoName;
InputStream is;
String largeImagePath;
int serverResponseCode = 0;
public static boolean flag = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.camera);
userFunctions = new UserFunctions();
globalUID = getIntent().getExtras().getString("globalUID");
//flag = getIntent().getExtras().getBoolean("flag");
Toast.makeText(getApplicationContext(), globalUID, Toast.LENGTH_LONG).show();
ivUserImage = (ImageView)findViewById(R.id.ivUserImage);
bUpload = (Button)findViewById(R.id.bUpload);
//openCamera();
//if(flag ==true)
openCamera();
}
/*
#Override
protected void onResume() {
super.onResume();
if(flag==true)
openCamera();
}*/
private void openCamera() {
i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, CameraResult);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
flag = false;
if(resultCode == RESULT_OK) {
//set image taken from camera on ImageView
Bundle extras = data.getExtras();
bmp = (Bitmap) extras.get("data");
ivUserImage.setImageBitmap(bmp);
//Create new Cursor to obtain the file Path for the large image
String[] largeFileProjection = {
MediaStore.Images.ImageColumns._ID,
MediaStore.Images.ImageColumns.DATA
};
String largeFileSort = MediaStore.Images.ImageColumns._ID + " DESC";
Cursor myCursor = this.managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, largeFileProjection, null, null, largeFileSort);
try {
myCursor.moveToFirst();
//This will actually give you the file path location of the image.
largeImagePath = myCursor.getString(myCursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATA));
File f = new File("" + largeImagePath);
photoName = f.getName();
bUpload.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new Upload().execute(largeImagePath, globalUID, photoName);
}
});
} finally {
myCursor.close();
}
}
}
public class Upload extends AsyncTask<String, Integer, String> {
ProgressDialog dialog;
protected void onPreExecute() {
dialog = ProgressDialog.show(Camera.this, "", "Uploading file...", true);
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
String success = "false";
Bitmap bitmapOrg = setImageToImageView(largeImagePath);//BitmapFactory.decodeFile(largeImagePath);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte [] ba = bao.toByteArray();
String ba1=Base64.encodeToString(ba, 0);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("image",ba1));
nameValuePairs.add(new BasicNameValuePair("imageName", photoName));
nameValuePairs.add(new BasicNameValuePair("uid", globalUID));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.example.info/android/fileupload.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if(response != null) {
success = "true";
}
is = entity.getContent();
} catch(Exception e) {
Log.e("log_tag", "Error in http connection "+e.toString());
}
dialog.dismiss();
return success;
}
protected void onProgressUpdate(Integer...progress) {
}
protected void onPostExecute(String f) {
Toast.makeText(getApplicationContext(), "File uploaded", Toast.LENGTH_LONG).show();
}
}
public Bitmap setImageToImageView(String filePath) {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 1024;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
Bitmap bitmap = BitmapFactory.decodeFile(filePath, o2);
return bitmap;
}
public boolean fileData(String guid, String photoName) {
Toast.makeText(getApplicationContext(), photoName, Toast.LENGTH_LONG).show();
JSONObject json = userFunctions.uploadFileData(guid, photoName);
try {
if(Integer.parseInt(json.getString("success")) != 1) {
Toast.makeText(getApplicationContext(), json.getInt("error_msg"), Toast.LENGTH_LONG).show();
//register_error.setText(json.getString("error_msg"));
return false;
}
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
}
This is because when you are switching between tabs your activity doesnt call onCreate again.
Try moving call to openCamera(); into onResume method and it should be fine.
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.camera);
userFunctions = new UserFunctions();
globalUID = getIntent().getExtras().getString("globalUID");
Toast.makeText(getApplicationContext(), globalUID, Toast.LENGTH_LONG).show();
ivUserImage = (ImageView)findViewById(R.id.ivUserImage);
bUpload = (Button)findViewById(R.id.bUpload);
}
protectd void onResume(){
super.onResume();
openCamera();
}
private void openCamera() {
i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, CameraResult);
}
Each Activity in an TabHost calls onCreate() only once for reason of efficiency. This is why the openCamera() doesn't get called again and again.
In order to handle this, you can in the parent Activity to implement and register an OnTabChangeListener, where you can catch which tab is clicked and perform any desired action.
Hope this helps!
add onResume() in your activity and call openCamera(); from onResume() also as:
public static boolean flag = true;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.camera);
userFunctions = new UserFunctions();
globalUID = getIntent().getExtras().getString("globalUID");
Toast.makeText(getApplicationContext(), globalUID, Toast.LENGTH_LONG).show();
ivUserImage = (ImageView)findViewById(R.id.ivUserImage);
bUpload = (Button)findViewById(R.id.bUpload);
if(flag ==true)
openCamera();
}
#Override
protected void onResume() {
super.onResume();
if(flag==true)
openCamera();
}
and in on onActivityResut()
flag =false;
or on tabclick
YourflagActivity.flag=true;

Categories

Resources