Android: Renaming images from camera - java

Currently I am using this code in my application to allow users to capture photos.But how do i change the code so that after the users capture the photo, it will be renamed to name such as "xxxx01.jpg"?
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.photo);
_image = (ImageView) findViewById(R.id.image);
_field = (TextView) findViewById(R.id.field);
_button = (Button) findViewById(R.id.button);
_button.setOnClickListener(new ButtonClickHandler());
_path = Environment.getExternalStorageDirectory()
+ "/images/make_machine_example.jpg";
}
public class ButtonClickHandler implements View.OnClickListener {
#Override
public void onClick(View view) {
Log.i("MakeMachine", "ButtonClickHandler.onClick()");
startCameraActivity();
}
}
protected void startCameraActivity() {
Log.i("MakeMachine", "startCameraActivity()");
File file = new File(_path);
Uri outputFileUri = Uri.fromFile(file);
Intent intent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, 0);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.i("MakeMachine", "resultCode: " + resultCode);
switch (resultCode) {
case 0:
Log.i("MakeMachine", "User cancelled");
break;
case -1:
onPhotoTaken();
break;
}
}
protected void onPhotoTaken() {
Log.i("MakeMachine", "onPhotoTaken");
_taken = true;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
Bitmap bitmap = BitmapFactory.decodeFile(_path, options);
_image.setImageBitmap(bitmap);
_field.setVisibility(View.GONE);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
Log.i("MakeMachine", "onRestoreInstanceState()");
if (savedInstanceState.getBoolean(PhotoCaptureExample.PHOTO_TAKEN)) {
onPhotoTaken();
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean(PhotoCaptureExample.PHOTO_TAKEN, _taken);
}
}

Try this.
//camera stuff
Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
//folder stuff
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "MyImages");
imagesFolder.mkdirs();
filePath = "/MyImages/QR_" + timeStamp + ".png" ;
File image = new File(imagesFolder, "QR_" + timeStamp + ".png");
Uri uriSavedImage = Uri.fromFile(image);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
startActivityForResult(imageIntent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
Taken From Here.

Related

Take image from camera or gallery and show in activity

I want to write a module where on a click of a button, the camera opens and I can click and capture an image. If I don't like the image, I can delete it and click one more image, and then select the image and it should return back and display that image in the activity.
The problem comes when I took a picture the camera application gets crashed and when I took a picture from the gallery the pic doesn't show in image view.
This is the script I wrote:
public class MainpageActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
final int TAKE_PICTURE = 1;
final int ACTIVITY_SELECT_IMAGE = 2;
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mainpage);
Toolbar toolbar = findViewById(R.id.toolbar);
imageView = (ImageView)this.findViewById(R.id.imageView1);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setImageResource(R.drawable.ic_camera_alt_black_24dp);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{ RxPermissions rxPermissions = new RxPermissions(MainpageActivity.this);
rxPermissions
.request(Manifest.permission.CAMERA) // ask single or multiple permission once
.subscribe(granted -> {
if (granted) {
selectImage();
} else {
Toast.makeText(MainpageActivity.this, "Permission of camera is denied", Toast.LENGTH_SHORT).show();
}
});
}
});
private File savebitmap(Bitmap bmp) {
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
OutputStream outStream = null;
// String temp = null;
File file = new File(extStorageDirectory, "temp.png");
if (file.exists()) {
file.delete();
file = new File(extStorageDirectory, "temp.png");
}
try {
outStream = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
} catch (Exception e) {
e.printStackTrace();
return null;
}
return file;
}
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(MainpageActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(options,new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
if(options[which].equals("Take Photo"))
{
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, TAKE_PICTURE);
}
else if(options[which].equals("Choose from Gallery"))
{
Intent intent=new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, ACTIVITY_SELECT_IMAGE);
}
else if(options[which].equals("Cancel"))
{
dialog.dismiss();
}
}
});
builder.show();
}
public void onActivityResult(int requestcode,int resultcode,Intent intent)
{
super.onActivityResult(requestcode, resultcode, intent);
if(resultcode==RESULT_OK)
{
if(requestcode==TAKE_PICTURE)
{
Bitmap photo = (Bitmap)intent.getExtras().get("data");
Drawable drawable=new BitmapDrawable(photo);
imageView.setBackgroundDrawable(drawable);
}
else if(requestcode==ACTIVITY_SELECT_IMAGE)
{
Uri selectedImage = intent.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
Drawable drawable=new BitmapDrawable(thumbnail);
imageView.setBackgroundDrawable(drawable);
}
}
}
}
#Uma : Please follow this steps and change your code.
Step 1 - add both two line in AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
And also add this properties in application tag in manifest file:
android:largeHeap="true"
android:hardwareAccelerated="false"
Step - 2 - import lib in build.gradle file
implementation 'com.karumi:dexter:4.2.0' // for handling runtime permissions
Step - 3 - In your MainpageActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.imageView = (ImageView)this.findViewById(R.id.imageView1);
this.fab = (FloatingActionButton) this.findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
CheckPermission();
}
});
}
private void CheckPermission(){
Dexter.withActivity(this)
.withPermissions(
Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
.withListener(new MultiplePermissionsListener() {
#Override
public void onPermissionsChecked(MultiplePermissionsReport report) {
// check if all permissions are granted
if (report.areAllPermissionsGranted()) {
selectImage();
}
// check for permanent denial of any permission
if (report.isAnyPermissionPermanentlyDenied()) {
// permission is denied permenantly, navigate user to app settings
}
}
#Override
public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
token.continuePermissionRequest();
}
})
.onSameThread()
.check();
}
private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
new AlertDialog.Builder(MainActivity.this)
.setMessage(message)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", null)
.create()
.show();
}
private File savebitmap(Bitmap bmp) {
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
OutputStream outStream = null;
// String temp = null;
File file = new File(extStorageDirectory, "temp.png");
if (file.exists()) {
file.delete();
file = new File(extStorageDirectory, "temp.png");
}
try {
outStream = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
} catch (Exception e) {
e.printStackTrace();
return null;
}
return file;
}
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo"))
{
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, 1);
}
else if (options[item].equals("Choose from Gallery"))
{
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
}
else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#SuppressLint("LongLogTag")
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
} else if (requestCode == 2) {
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));
}
}}
Hope it helps you.
I think you should try to add this "android:required="true".
<uses-feature android:name="android.hardware.camera"
android:required="true" />
First of all, you need to handle with permissions
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
After this, you can use this for opening gallery with button
//opening image chooser option
choose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_PICK);
startActivityForResult(Intent.createChooser(intent, "Select Image"), PICK_IMAGE_REQUEST);
}
});
And with this function, you can show the image on UI
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri filePath = data.getData();
try {
//getting image from gallery
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
//Setting image to ImageView
image.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Also, you can convert image to bitmap64:
//converting image to base64 string
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, baos);
byte[] imageBytes = baos.toByteArray();
final String imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT);

How to call different methods with LocalBroadcastManager

I have 3 menu buttons (add_image,save_meme and share_meme) on my action bar, which are declared in Mainactivity.java. The buttons are responsible for calling the corresponding methods in another fragment. The connection is established with LocalBroadcastManager.
public class MainActivity extends AppCompatActivity{
Intent saveIntent, shareIntent, addImageIntent;
LocalBroadcastManager localBroadcastManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
localBroadcastManager = LocalBroadcastManager.getInstance(getApplicationContext());
addImageIntent = new Intent("ADD_ACTION");
saveIntent = new Intent("SAVE_ACTION");
shareIntent = new Intent("SHARE_ACTION");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.add_image:
localBroadcastManager.sendBroadcast(addImageIntent);
case R.id.save_meme:
localBroadcastManager.sendBroadcast(saveIntent);
case R.id.share_meme:
localBroadcastManager.sendBroadcast(shareIntent);
default:
return super.onOptionsItemSelected(item);
}
}
}
As mentioned above, the corresponding methods are in the TopImageFragment.java class. The add_image button calls the method that allows the user to upload an image to the ImageView from the device:
public void selectedImage() {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(intent, PICK_IMAGE);
}
The save_meme button calls the method that saves the bitmap to the device:
public void saveMeme(Bitmap btm) {
counter++;
File file;
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getPath();
file = new File(path + "/Memery/" + timeStamp + counter + ".jpg");
file.getParentFile().mkdir();
try {
OutputStream stream = new FileOutputStream(file);
btm.compress(Bitmap.CompressFormat.JPEG, 100, stream);
stream.flush();
stream.close();
Toast.makeText(getContext(), "Meme Saved", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
Uri contentUri = Uri.fromFile(file);
mediaScanIntent.setData(contentUri);
Objects.requireNonNull(getContext()).sendBroadcast(mediaScanIntent);
}
The share_meme button calls the method that allows the user to share the meme on a variety of social media apps and email clients:
public void shareMeme(Bitmap bitmap) {
String path = MediaStore.Images.Media.insertImage(Objects.requireNonNull(getContext()).getContentResolver(), bitmap, "Meme", null);
Uri uri = Uri.parse(path);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/*");
share.putExtra(Intent.EXTRA_STREAM, uri);
share.putExtra(Intent.EXTRA_TEXT, "This is my Meme");
getContext().startActivity(Intent.createChooser(share, "Share Your Meme!"));
}
But what's happening now is that whenever I select whichever of the 3 menu buttons, all 3 methods get called. This is my full fragment:
public class TopImageFragment extends Fragment {
ImageView imageView;
TextView topTextView, bottomTextView;
RelativeLayout topImageRelativeLayout;
public static final int PICK_IMAGE = 1;
Uri imageUri;
int counter = 0;
String timeStamp = new SimpleDateFormat("yyyyMMdd", Locale.CANADA).format(new Date());
float textSize, x, imageViewArea, canvasArea;
double val;
MemeViewModel memeViewModel;
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_top_image, container, false);
imageView = view.findViewById(R.id.meme_image_view);
topTextView = view.findViewById(R.id.top_text_view);
bottomTextView = view.findViewById(R.id.bottom_text_view);
topImageRelativeLayout = view.findViewById(R.id.top_image_relative_layout);
if (savedInstanceState != null) {
imageUri = savedInstanceState.getParcelable("imageUri");
imageView.setImageURI(imageUri);
}
return view;
}
#Override
public void onSaveInstanceState(#NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable("imageUri", imageUri);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
memeViewModel = ViewModelProviders.of(Objects.requireNonNull(getActivity())).get(MemeViewModel.class);
memeViewModel.getTopText().observe(getViewLifecycleOwner(), new Observer<CharSequence>() {
#Override
public void onChanged(#Nullable CharSequence charSequence) {
topTextView.setText(charSequence);
}
});
memeViewModel.getBottomText().observe(getViewLifecycleOwner(), new Observer<CharSequence>() {
#Override
public void onChanged(#Nullable CharSequence charSequence) {
bottomTextView.setText(charSequence);
}
});
}
public void selectedImage() {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(intent, PICK_IMAGE);
}
public Bitmap getBitmap(ImageView img) {
BitmapDrawable bitmapDrawable = ((BitmapDrawable) img.getDrawable());
Bitmap bitmap = bitmapDrawable.getBitmap();
return bitmap.copy(Bitmap.Config.ARGB_8888, true);
}
public Bitmap screenshotMeme() {
Bitmap image = Bitmap.createBitmap(topImageRelativeLayout.getWidth(), topImageRelativeLayout.getHeight(), Bitmap.Config.RGB_565);
topImageRelativeLayout.draw(new Canvas(image));
return image.copy(Bitmap.Config.ARGB_8888, true);
}
public Bitmap drawMeme(Bitmap mutableBitmap) {
String topText = topTextView.getText().toString();
String bottomText = bottomTextView.getText().toString();
topText = topText.toUpperCase();
bottomText = bottomText.toUpperCase();
Canvas canvas = new Canvas(mutableBitmap);
TextPaint topFillPaint = new TextPaint();
TextPaint bottomFillPaint = new TextPaint();
TextPaint topStrokePaint = new TextPaint();
TextPaint bottomStrokePaint = new TextPaint();
Typeface typeface = getResources().getFont(R.font.impact);
textSize = topTextView.getTextSize();
imageViewArea = (imageView.getWidth()) * (imageView.getHeight());
canvasArea = (canvas.getWidth()) * (canvas.getHeight());
val = textSize * sqrt(canvasArea / imageViewArea);
x = (float) val;
topFillPaint.setColor(Color.WHITE);
topFillPaint.setTextSize(x);
topFillPaint.setTypeface(typeface);
topFillPaint.setStyle(Paint.Style.FILL_AND_STROKE);
topStrokePaint.setStyle(Paint.Style.STROKE);
topStrokePaint.setStrokeWidth(4);
topStrokePaint.setTextSize(x);
topStrokePaint.setColor(Color.BLACK);
topStrokePaint.setTypeface(typeface);
bottomFillPaint.setColor(Color.WHITE);
bottomFillPaint.setTextSize(x);
bottomFillPaint.setTypeface(typeface);
bottomFillPaint.setStyle(Paint.Style.FILL_AND_STROKE);
bottomStrokePaint.setStyle(Paint.Style.STROKE);
bottomStrokePaint.setStrokeWidth(4);
bottomStrokePaint.setColor(Color.BLACK);
bottomStrokePaint.setTextSize(x);
bottomStrokePaint.setTypeface(typeface);
StaticLayout topFillLayout = new StaticLayout(topText, topFillPaint, canvas.getWidth(), Layout.Alignment.ALIGN_CENTER,
0.8f, 0.0f, false);
StaticLayout topStrokeLayout = new StaticLayout(topText, topStrokePaint, canvas.getWidth(), Layout.Alignment.ALIGN_CENTER,
0.8f, 0.0f, false);
StaticLayout bottomFillLayout = new StaticLayout(bottomText, bottomFillPaint, canvas.getWidth(), Layout.Alignment.ALIGN_CENTER,
0.8f, 0.0f, false);
StaticLayout bottomStrokeLayout = new StaticLayout(bottomText, bottomStrokePaint, canvas.getWidth(), Layout.Alignment.ALIGN_CENTER,
0.8f, 0.0f, false);
topFillLayout.draw(canvas);
topStrokeLayout.draw(canvas);
canvas.translate(0, canvas.getHeight() - bottomFillLayout.getHeight());
bottomFillLayout.draw(canvas);
bottomStrokeLayout.draw(canvas);
return mutableBitmap;
}
public void saveMeme(Bitmap btm) {
counter++;
File file;
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getPath();
file = new File(path + "/Memery/" + timeStamp + counter + ".jpg");
file.getParentFile().mkdir();
try {
OutputStream stream = new FileOutputStream(file);
btm.compress(Bitmap.CompressFormat.JPEG, 100, stream);
stream.flush();
stream.close();
Toast.makeText(getContext(), "Meme Saved", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
Uri contentUri = Uri.fromFile(file);
mediaScanIntent.setData(contentUri);
Objects.requireNonNull(getContext()).sendBroadcast(mediaScanIntent);
}
public void shareMeme(Bitmap bitmap) {
String path = MediaStore.Images.Media.insertImage(Objects.requireNonNull(getContext()).getContentResolver(), bitmap, "Meme", null);
Uri uri = Uri.parse(path);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/*");
share.putExtra(Intent.EXTRA_STREAM, uri);
share.putExtra(Intent.EXTRA_TEXT, "This is my Meme");
getContext().startActivity(Intent.createChooser(share, "Share Your Meme!"));
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == PICK_IMAGE) {
imageUri = Objects.requireNonNull(data).getData();
imageView.setImageURI(imageUri);
memeViewModel.setSharedId(imageUri.getLastPathSegment());
}
}
#Override
public void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(Objects.requireNonNull(getActivity())).registerReceiver(addListener, new IntentFilter("ADD_ACTION"));
LocalBroadcastManager.getInstance(Objects.requireNonNull(getActivity())).registerReceiver(saveListener, new IntentFilter("SAVE_ACTION"));
LocalBroadcastManager.getInstance(Objects.requireNonNull(getActivity())).registerReceiver(shareListener, new IntentFilter("SHARE_ACTION"));
}
private BroadcastReceiver addListener = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
selectedImage();
}
};
private BroadcastReceiver saveListener = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
float height = getBitmap(imageView).getHeight();
float width = getBitmap(imageView).getWidth();
if ((height <= 600) || (width <= 600)) {
saveMeme(screenshotMeme());
Toast.makeText(getContext(), "screenshotMeme() method was called", Toast.LENGTH_SHORT).show();
} else {
saveMeme(drawMeme(getBitmap(imageView)));
Toast.makeText(getContext(), "drawMeme() method was called", Toast.LENGTH_SHORT).show();
}
}
};
private BroadcastReceiver shareListener = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
float height = getBitmap(imageView).getHeight();
float width = getBitmap(imageView).getWidth();
if ((height <= 600) || (width <= 600)) {
shareMeme(screenshotMeme());
Toast.makeText(getContext(), "screenshotMeme() method was called", Toast.LENGTH_SHORT).show();
} else {
shareMeme(drawMeme(getBitmap(imageView)));
Toast.makeText(getContext(), "drawMeme() method was called", Toast.LENGTH_SHORT).show();
}
}
};
#Override
public void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(Objects.requireNonNull(getActivity())).unregisterReceiver(addListener);
LocalBroadcastManager.getInstance(Objects.requireNonNull(getActivity())).unregisterReceiver(saveListener);
LocalBroadcastManager.getInstance(Objects.requireNonNull(getActivity())).unregisterReceiver(shareListener);
}
}
Problem: Because in switch-case block, you do not return or put a break statement, then whenever a menu item is clicked, it will executes all statements in the switch-case.
Solution: Put a return true on each case to indicate you want consume the event when a menu item is clicked.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.add_image:
localBroadcastManager.sendBroadcast(addImageIntent);
return true;
case R.id.save_meme:
localBroadcastManager.sendBroadcast(saveIntent);
return true;
case R.id.share_meme:
localBroadcastManager.sendBroadcast(shareIntent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
or using a break statement on each case, then returning true at the end of method.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.add_image:
localBroadcastManager.sendBroadcast(addImageIntent);
break;
case R.id.save_meme:
localBroadcastManager.sendBroadcast(saveIntent);
break;
case R.id.share_meme:
localBroadcastManager.sendBroadcast(shareIntent);
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}

Attempt to invoke virtual method 'android.os.Parcelable android.os.Bundle.getParcelable(java.lang.String)' null object reference

I am making an app in which a feature that user can upload images and video to server
it was working well on activity but now I want to use it in a fragment. I try to code effectively, efficiently and I am not getting any error during compiling and my app runs successfully but when I click on fragment it shows "unfortunately app has stopped " and in log cat I am getting this error:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Parcelable android.os.Bundle.getParcelable(java.lang.String)' on a null object reference
and its points this line:
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
this line ➦ fileUri = savedInstanceState.getParcelable("file_uri");
}
i don't know whats wrong
my code:
public class TabFragment4 extends Fragment implements View.OnClickListener{
View parentHolder;
private static final String TAG = MainActivity.class.getSimpleName();
int req_code = 100;
int video_code = 20;
String path;
Uri selectedImageUri;
// Camera activity request codes
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 10;
private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
Context mContext;
private Uri fileUri; // file url to store image/video
private ImageButton btnCapturePicture, btnRecordVideo,gallerybtn , videobtn,b1,location;
public TabFragment4() {
// Required empty public constructor
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
parentHolder = inflater.inflate(R.layout.fragment_tab_fragment4, container, false);
final LocationManager manager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
AlertDialog.Builder mAlertDialog = new AlertDialog.Builder(getActivity());
// Setting Dialog Title
mAlertDialog.setTitle("Location not available, Open GPS?")
.setMessage("Activate GPS to use Location Service ?")
.setPositiveButton("Open Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
})
.setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
}).show();
// Call your Alert message
}
btnCapturePicture = (ImageButton)parentHolder.findViewById(R.id.btnCapturePicture);
btnRecordVideo = (ImageButton)parentHolder. findViewById(R.id.btnRecordVideo);
gallerybtn=(ImageButton)parentHolder.findViewById(R.id.imagegallery);
videobtn = (ImageButton)parentHolder.findViewById(R.id.videogallery);
location=(ImageButton)parentHolder.findViewById(R.id.location);
videobtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
video();
}
});
gallerybtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// record video
galleryimage();
}
});
btnCapturePicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// record video
captureImage();
}
});
/**
* Capture image button click event
*/
btnRecordVideo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// record video
recordVideo();
}
});
/**
* Record video button click event
*/
btnRecordVideo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// record video
recordVideo();
}
});
return parentHolder;
}
public void video(){
Intent intent = new Intent();
intent.setType("video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select file to upload "), video_code);
}
public void galleryimage(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select file to upload "), req_code);
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
/**
* Launching camera app to record video
*/
private void recordVideo() {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
// set video quality
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file
// name
// start the video capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
}
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// save file url in bundle as it will be null on screen orientation
// changes
outState.putParcelable("file_uri", fileUri);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
fileUri = savedInstanceState.getParcelable("file_uri");
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
if (requestCode == req_code) {
selectedImageUri = data.getData();
if (resultCode ==Activity. RESULT_OK) {
path = getPath(selectedImageUri);
launchUpload(true);
System.out.println("selectedPath1 : " + path);
}
}
if (requestCode == video_code) {
selectedImageUri = data.getData();
if (resultCode == Activity. RESULT_OK) {
path = getPath(selectedImageUri);
launchUpload(false);
System.out.println("selectedPath1 : " + path);
}
}
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
//successfully captured the image
// launching upload activity
launchUploadActivity(true);
//Intent intent = new Intent(this,UploadActivity.class);
//startActivity(intent);
} else if (resultCode ==Activity. RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getActivity(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
} else {
// failed to capture image
Toast.makeText(getActivity(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
} else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
// video successfully recorded
// launching upload activity
launchUploadActivity(false);
} else if (resultCode == Activity.RESULT_CANCELED) {
// user cancelled recording
Toast.makeText(getActivity(),
"User cancelled video recording", Toast.LENGTH_SHORT)
.show();
} else {
// failed to record video
Toast.makeText(getActivity(),
"Sorry! Failed to record video", Toast.LENGTH_SHORT)
.show();
}
}
}
private void launchUploadActivity(boolean isImage) {
Intent i = new Intent(getActivity(), UploadActivity.class);
i.putExtra("filePath", fileUri.getPath());
i.putExtra("isImage", isImage);
startActivity(i);
}
private void launchUpload(boolean isImage) {
Intent i = new Intent(getActivity(), UploadActivity.class);
i.putExtra("filePath", path);
i.putExtra("isImage", isImage);
startActivity(i);
}
/**
* ------------ Helper Methods ----------------------
* */
/**
* Creating file uri to store image/video
*/
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/**
* returning image / video
*/
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
Config.IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(TAG, "Oops! Failed create "
+ Config.IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else if (type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "VID_" + timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
#Override
public void onClick(View v) {
}
}
Uri imageUri = data.getData();
Bitmap bitmap= null;
try {
bitmap = MediaStore.Images.Media.getBitmap(getContext().getContentResolver(), imageUri);
} catch (IOException e) {
e.printStackTrace();
}
Seems savedInstanceState == null so use something like this:
if (savedInstanceState != null) {
fileUri = savedInstanceState.getParcelable("file_uri");
} else {
fileUri = ??? - what You want do to in else case;
}

post video on facebook using android application

This is my code i capture image and share successfully but can't upload video
public class CaptureActivity extends AppCompatActivity {
ShareButton shareButton;
private ImageView imgPreview;
private VideoView videoPreview;
private Button btnCapture;
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
private Uri fileUri;
private static final String IMAGE_DIRECTORY_NAME = "CityApp";
static File mediaFile;
static File mediaStorageDir;
Bitmap bitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_capture);
imgPreview = (ImageView) findViewById(R.id.imageView);
videoPreview = (VideoView) findViewById(R.id.videoPreview);
btnCapture = (Button) findViewById(R.id.btn_Capture);
shareButton = (ShareButton) findViewById(R.id.fb_share_button);
// shareButton.setFragment(this);
shareButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
publishImage();
// publishVideo();
}
});
btnCapture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
}
private void selectImage() {
final CharSequence[] options = {"Take Photo", "Tack Video", "Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(CaptureActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
} else if (options[item].equals("Tack Video")) {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
// set video quality
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file
// name
// start the video capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
} else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// save file url in bundle as it will be null on scren orientation
// changes
outState.putParcelable("file_uri", fileUri);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// get the file url
fileUri = savedInstanceState.getParcelable("file_uri");
}
/**
* Display image from a path to ImageView
*/
private void previewCapturedImage() {
try {
// hide video preview
videoPreview.setVisibility(View.GONE);
imgPreview.setVisibility(View.VISIBLE);
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();
// downsizing image as it throws OutOfMemory Exception for larger
// images
options.inSampleSize = 8;
bitmap = BitmapFactory.decodeFile(fileUri.getPath(), options);
imgPreview.setImageBitmap(bitmap);
}
catch (NullPointerException e) {
e.printStackTrace();
}
}
/**
* Previewing recorded video
*/
private void previewVideo() {
try {
// hide image preview
imgPreview.setVisibility(View.GONE);
videoPreview.setVisibility(View.VISIBLE);
videoPreview.setVideoPath(fileUri.getPath());
// start playing
videoPreview.start();
}
catch (Exception e) {
e.printStackTrace();
}
}
/**
* Creating file uri to store image/video
*/
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/**
* returning image / video
*/
public static File getOutputMediaFile(int type) {
// External sdcard location
mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
+ IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else if (type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "VID_" + timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// successfully captured the image
// display it in image view
previewCapturedImage();
} else if (resultCode == RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
} else {
// failed to capture image
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
} else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// video successfully recorded
// preview the recorded video
previewVideo();
} else if (resultCode == RESULT_CANCELED) {
// user cancelled recording
Toast.makeText(getApplicationContext(),
"User cancelled video recording", Toast.LENGTH_SHORT)
.show();
} else {
// failed to record video
Toast.makeText(getApplicationContext(),
"Sorry! Failed to record video", Toast.LENGTH_SHORT)
.show();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
public void publishImage() {
// statusUpdates= new ContactsContract.StatusUpdates(getActivity().getApplicationContext());
// Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
BitmapFactory.Options options = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(fileUri.getPath(), options);
SharePhoto photo = new SharePhoto.Builder()
.setBitmap(bitmap)
.setCaption("Testing with android")
.build();
SharePhotoContent content = new SharePhotoContent.Builder()
.addPhoto(photo)
.build();
shareButton.setShareContent(content);
}
public void publishVideo() {
Uri videoFileUri = fileUri;
ShareVideo shareVideo = new ShareVideo.Builder()
.setLocalUrl(videoFileUri)
.build();
ShareVideoContent content = new ShareVideoContent.Builder()
.setVideo(shareVideo)
.build();
shareButton.setShareContent(content);
}
}
i want use compile 'com.facebook.android:facebook-android-sdk:4.1.0' this library thanks in advance

Two onActivityResult conflict android

I have two activities, TakePictureActivity and ChoosePicActivity, and they both lead to PuzzleActivity.
As you can see, 1st activity starts an intent to start the camera, allows you to take a picture and starts the PuzzleActivity.
The 2nd activity accesses to the gallery, allows you to choose a picture and starts the PuzzleActivity.
In the PuzzleActivity the method createScaledBitmap is called to generate a bitmap.
Here is TakePictureActivity:
public class TakePictureActivity extends Activity {
String mCurrentPhotoPath;
static final int REQUEST_TAKE_PHOTO = 1;
public static final int DIALOG_PICASA_ERROR_ID = 0;
private static String DEBUG_TAG1 = "TakePictureA";
private Bitmap bitmap;
public static Uri imageUri;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.takepicture);
dispatchTakePictureIntent();
}
//TODO createImageFile
/* (non-Javadoc)
* Creates a file for the picture with a collision-resistant name using date-time stamp.
* Additionally, it saves the path to the picture in a member variable, mCurrentPhotoPath.
*/
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date(0));
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
Log.d(DEBUG_TAG1,"Current photo Path" + mCurrentPhotoPath);
galleryAddPic();
return image;
}
//TODO dispatchTakePictureIntent
/* (non-Javadoc)
* Starts an intent for the camera application.
*/
private void dispatchTakePictureIntent() {
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (i.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
Log.d(DEBUG_TAG1,"try create iamge file");
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
Log.d(DEBUG_TAG1,"error");
}
// Continue only if the File was successfully created
if (photoFile != null) {
Log.d(DEBUG_TAG1,"photo file not null");
i.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(i, REQUEST_TAKE_PHOTO);
}
}
}
private void galleryAddPic() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
#Override
protected final void onActivityResult(final int requestCode, final int resultCode, final Intent i) {
//super.onActivityResult(requestCode, resultCode, i);
if (resultCode == RESULT_OK) {
Log.d(DEBUG_TAG1,"TakePicture onActivityResult ");
switch (requestCode) {
case REQUEST_TAKE_PHOTO:
imageUri = i.getData();
Log.d(DEBUG_TAG1,"intent take pic: " + i);
Intent i1 = new Intent(this, PuzzleActivity.class);
startActivity(i1);
break;
} // end switch
} // end if
}
}
And here is ChoosePicActivity:
public class ChoosePicActivity extends Activity {
String mCurrentPhotoPath;
public static final int IMAGEREQUESTCODE = 8242008;
static final int REQUEST_TAKE_PHOTO = 1;
public static final int DIALOG_PICASA_ERROR_ID = 0;
private static String DEBUG_TAG1 = "ChoosePicA";
private Bitmap bitmap;
public static Uri imageUri;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
selectImageFromGallery();
}
/* (non-Javadoc)
* Will start an intent for external Gallery app.
* Image returned via onActivityResult().
*/
private void selectImageFromGallery() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, IMAGEREQUESTCODE);
}
//TODO onActivityResult
/* (non-Javadoc)
* Run when Gallery app returns selected image.
*/
#Override
protected final void onActivityResult(final int requestCode, final int resultCode, final Intent i) {
//super.onActivityResult(requestCode, resultCode, i);
if (resultCode == RESULT_OK) {
Log.d(DEBUG_TAG1,"ChoosePic onActivityResult ");
switch (requestCode) {
case IMAGEREQUESTCODE:
imageUri = i.getData();
Log.d(DEBUG_TAG1,"intent choose pic: " + i);
Intent i1 = new Intent(this, PuzzleActivity.class);
startActivity(i1);
break;
} // end switch
} // end if
}
}
And here is the PuzzleActivity:
public final class PuzzleActivity extends Activity implements OnClickListener{
private Bitmap bitmap; // temporary holder for puzzle picture
public static Chronometer chrono;
static TextView tv1;
static EditText et1;
Button button;
private static Context mContext;
//TODO onCreate
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.board);
mContext = this;
tv1 = (TextView) findViewById(R.id.movecount_display);
if(DecidePicActivity.choosepic){
try {
bitmap = createScaledBitmap(ChoosePicActivity.imageUri);
} catch (FileNotFoundException e) {
showDialog(DIALOG_PICASA_ERROR_ID);
} catch (IOException e) {
e.printStackTrace();
finish();
} catch (IllegalArgumentException e) {
showDialog(DIALOG_PICASA_ERROR_ID);
}
createGameBoard(getGridSize());
}
else if(DecidePicActivity.takepic){
try {
bitmap = createScaledBitmap(TakePictureActivity.imageUri);
} catch (FileNotFoundException e) {
showDialog(DIALOG_PICASA_ERROR_ID);
} catch (IOException e) {
e.printStackTrace();
finish();
} catch (IllegalArgumentException e) {
showDialog(DIALOG_PICASA_ERROR_ID);
}
createGameBoard(getGridSize());
}
TileView.moveDetector = new GestureDetectorCompat(this, new MyGestureListener());
Button pauseButton = (Button) findViewById(R.id.pause_button);
pauseButton.setOnClickListener(this);
}
The issue is:
I get to ChoosePicActivity, I choose a pic from the gallery, start intent to go to PuzzleActivity and creates the scaled bitmap with the chosen picture.
All good until here.
then, PuzzleActivity gets finished and i get to TakePictureActivity, camera starts, i take a pic, start intent to go PuzzleActivity and THEN the scaled bitmap generated uses the image previously chosen in the ChoosePicActivity, leaving the recently taken picture behind, which is the picture that it should have been used to generate the scaled bitmap.
On the other hand, if TakePictureActivity is started without ChoosePicActivity previously started, the taken picture is used to generate the scaled bitmap, as expected.
I hope I explained myself enough good for you to understand my problem. Could somebody give some light?
I'm not sure if having 2 times the method onActivityResult is correct, or if there are different threads conflicting, or maybe the method i.getdata() is having trouble to get the proper Intent id... I'm a bit lost.
The problem was caused by DecidePicActivity.choosepic and DecidePicActivity.takepic.
Previously, DecidePicActivity activity was like this:
public class DecidePicActivity extends Activity implements OnClickListener{
static boolean takepic = false;
static boolean choosepic = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.decidepic);
findViewById(R.id.take_pic_button).setOnClickListener(this);
findViewById(R.id.choose_pic_button).setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.take_pic_button:
takepic = true;
Intent i1 = new Intent(this, TakePictureActivity.class);
startActivity(i1);
break;
case R.id.choose_pic_button:
choosepic = true;
Intent i2 = new Intent(this, ChoosePicActivity.class);
startActivity(i2);
break;
}
}
}
takepic and choosepic they were not properly reinitialized.
Now onClick in DecidePicActivity activity is like this:
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.take_pic_button:
takepic = true;
choosepic = false;
Intent i1 = new Intent(this, TakePictureActivity.class);
startActivity(i1);
break;
case R.id.choose_pic_button:
choosepic = true;
takepic = false;
Intent i2 = new Intent(this, ChoosePicActivity.class);
startActivity(i2);
break;
}
}
and problem solved!

Categories