how to crop image from gallery and set in imageview - android

I am cropping an image from the gallery but cannot able to set that cropped image in imageView, final image set as default image I mean without cropped so how to set Cropped image in ImageView
this is image Picker from gallery
newPostImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
galIntent=new Intent(Intent.ACTION_PICK,MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(Intent.createChooser(galIntent,"select image"),2);
}
});
This is for crop image
private void CropImage() {
try {
CropIntent = new Intent("com.android.camera.action.CROP");
CropIntent.setDataAndType(postImageUri,"image/*");
CropIntent.putExtra("crop","true");
CropIntent.putExtra("outputX",180);
CropIntent.putExtra("outputY",180);
CropIntent.putExtra("aspectX",3);
CropIntent.putExtra("aspectY",4);
CropIntent.putExtra("scaleUpIfNeeded",true);
CropIntent.putExtra("return-data",true);
startActivityForResult(CropIntent,1);
}
catch (ActivityNotFoundException ex)
{
}
}
This is onActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0&&resultCode ==RESULT_OK)
CropImage();
if (requestCode==2){
if (data!=null){
postImageUri=data.getData();
CropImage();
newPostImg.setImageURI(postImageUri);
}
}
}
And this is my permission
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA"/>
and this is imageView xml
<ImageView
android:layout_margin="10dp"
android:id="#+id/newPostImg"
android:layout_width="match_parent"
android:layout_height="250dp"
android:src="#drawable/default1" />

#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == 2) {
if (data != null) {
postImageUri = data.getData();
CropImage();
}
} else if (requestCode == 1) {
Bundle extras = data.getExtras();
Bitmap bitmap= extras.getParcelable("data");
newPostImg.setImageBitmap(bitmap);
}
}
}
}
You should set Image on CropIntent's result and not on cameraIntent's result.

Uri imageUri = Uri.parse(mCurrentPhotoPath);
Intent intent = new Intent(mContext, Crop_Activity.class);
intent.putExtra("imageUri", imageUri.toString());
startActivityForResult(intent, 105);
Here is the code for crop activity
public class Crop_Activity extends BaseActivity implements CropImageView.OnSetImageUriCompleteListener, CropImageView.OnCropImageCompleteListener, View.OnClickListener {
private CropImageView mCropImageView;
private ProgressDialog dialog;
int type;
private Uri imageUri;
private Bitmap cropped;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.crop_activity);
setScreenName("Crop Image screen");
Bundle extras = getIntent().getExtras();
if (extras != null) {
imageUri = Uri.parse(getIntent().getStringExtra("imageUri"));
}
//====Initialize Here====//
init();
//====Set CropImageView Here====//
setCropImageView();
}
void init() {
dialog = new ProgressDialog(Crop_Activity.this);
dialog.setCancelable(false);
dialog.setMessage("Cropping Image...");
Func.set_title_to_actionbar("Crop Image", "", "", Crop_Activity.this, (Toolbar) findViewById(R.id.toolbar), true, 8, 8, Crop_Activity.this);
mCropImageView = (CropImageView) findViewById(R.id.CropImageView);
}
void setCropImageView() {
mCropImageView.setOnSetImageUriCompleteListener(this);
mCropImageView.setOnCropImageCompleteListener(this);
mCropImageView.setFixedAspectRatio(true);
mCropImageView.setImageUriAsync(imageUri);
mCropImageView.setShowProgressBar(false);
mCropImageView.setFixedAspectRatio(true);
mCropImageView.setAspectRatio(10, 10);
}
#Override
public boolean onCreateOptionsMenu(final Menu menu) {
getMenuInflater().inflate(R.menu.menu_crop, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
onBackPressed();
finish();
return true;
}
if (id == R.id.btn_ok) {
mCropImageView.getCroppedImageAsync();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onSetImageUriComplete(CropImageView view, Uri uri, Exception error) {
}
#Override
public void onClick(View view) {
}
class CropingImageAsync extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog.show();
}
#Override
protected Void doInBackground(Void... params) {
Constants.Photo = cropped;
Intent i = new Intent();
setResult(RESULT_OK, i);
finish();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
dialog.dismiss();
Intent intent = new Intent();
setResult(RESULT_OK, intent);
finish();
}
}
#Override
public void onCropImageComplete(CropImageView view, CropImageView.CropResult result) {
handleCropResult(result);
}
private void handleCropResult(CropImageView.CropResult result) {
if (result.getError() == null) {
Bitmap bitmap = result.getBitmap();
if (bitmap != null) {
cropped = bitmap;
if (cropped != null) {
new CropingImageAsync().execute();
}
}
} else {
Log.e("AIC", "Failed to crop image", result.getError());
}
}
}
Here is the XML for crop activity
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:local="http://schemas.android.com/apk/res-auto"
android:id="#+id/line1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.theartofdev.edmodo.cropper.CropImageView
android:id="#+id/CropImageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:cropInitialCropWindowPaddingRatio="0" />
</LinearLayout>
Dependency for cropping
compile 'com.theartofdev.edmodo:android-image-cropper:2.3.+'

Related

button with image view problems

I have created a fragment which a button and an image view in it. on button click the camera opens when I take a picture then I want that picture to appear in the imageView.
how can I activate this task?
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootview = inflater.inflate(R.layout.fragment_new_visitor, container, false);
capture=rootview.findViewById(R.id.capture);
capture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivity(intent);
}
});
return rootview;
please help
Just try this one,
Declare this before on create method
private final int requestCode = 20;
inside onclick event, do this
Intent photoCaptureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(photoCaptureIntent, requestCode);
then override oncreate method
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(this.requestCode == requestCode && resultCode == RESULT_OK){
Bitmap bitmap = (Bitmap)data.getExtras().get("data");
imageview.setImageBitmap(bitmap);
}
}
public class BlankFragment extends Fragment {
Button btnGallery,btnCamera;
public static final int GALLEY_REQUEST_CODE = 10;
private static final int CAMERA_REQUEST = 100;
private String TAG = MainActivity.class.getSimpleName();
ImageView image;
private Uri realUri;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_blank, container, false);
}
#Override
public void onStart() {
super.onStart();
btnGallery = (Button)getView().findViewById(R.id.btnGallery);
btnCamera = (Button)getView().findViewById(R.id.btnCamera);
image = (ImageView)getView().findViewById(R.id.image);
btnGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent openGallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(Intent.createChooser(openGallery, "Open Gallery"), GALLEY_REQUEST_CODE);
}
});
btnCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLEY_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
image.setImageURI(data.getData()); // set image to image view
try{
// Get real path to make File
realUri = Uri.parse(getRealPathFromURI(data.getData()));
Log.d(TAG,"Image path :- "+realUri);
}
catch (Exception e){
Log.e(TAG,e.getMessage());
}
}
if(requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK){
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
image.setImageBitmap(photo);
}
}
}
public String getRealPathFromURI(Uri contentUri) {
String res = null;
String[] proj = { MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getApplicationContext().getContentResolver().query(contentUri, proj, null, null, null);
assert cursor != null;
if(cursor.moveToFirst()){;
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
res = cursor.getString(column_index);
}
cursor.close();
return res;
}
}

Not set image from camera to imageview in android [duplicate]

This question already has answers here:
Capture Image from Camera and Display in Activity
(19 answers)
Closed 5 years ago.
I am trying to display a image captured from camera inside imageview in android
Selecting a photo from the correct gallery works
But the camera fails: "app has stopped"
images.get(2).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
current_image = 2;
if (!fill_images[current_image]) {
show_dialog();
}else {
show_delete_dialog();
};
}
});
public void show_dialog() {
final ArrayList<String> list = new ArrayList<String>();
list.add("select from gallery");
list.add("take a photo");
AlertDialog.Builder builder = new AlertDialog.Builder(NewAdActivity.this);
builder.setAdapter(new ArrayAdapter<String>(NewAdActivity.this, R.layout.row, R.id.mytext, list)
, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if (i == 0) {//gallery Intent gallery_intent=new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI) ; startActivityForResult(Intent.createChooser(gallery_intent,"select image"),2);
}
else if (i == 1){//camera
Intent camera_intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file=new File(Environment.getExternalStorageDirectory(),"file"+String.valueOf(System.currentTimeMillis()+".jpg"));
uri= Uri.fromFile(file);
camera_intent.putExtra(MediaStore.EXTRA_OUTPUT,uri);
camera_intent.putExtra("return-data",true);
startActivityForResult(camera_intent,1);
}
}
});
builder.show();
}
At first make sure that you declared all necessary permission on manifest.xml file. Then try with it -
public class MainActivity extends AppCompatActivity {
private static final int SELECTED_PICTURE=1;
private ImageView iv;
private Button btnClick;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
iv=(ImageView)findViewById(R.id.imageView1);
btnClick = (Button) findViewById(R.id.btnClick);
btnClick.setOnClickListener(new View.OnCLickListener(){
public void onClick(View view) {
btnClick(view);
}
});
}
public void btnClick(View v){
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, SELECTED_PICTURE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
iv.setImageBitmap(photo);
}
}
}
And dont forget to add permission to manifest.xml -
<uses-feature
android:name="android.hardware.camera"
android:required="true" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
new Camera.PictureCallback() {
#Override
public void onPictureTaken(final byte[] data, Camera camera) {
bytes = data;
}
}
Then convert the bytes to bitmap
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
Then set imageview
imageView.setImageBitmap(bitmap);

Customized Camera view in ZXING code reader to show detection

I am using the ZXING QR Code Reader. It is working fine. Detecting codes etc but it does not shows any detection progress(Like red line) while it is scanning the QR Code. Here is Screenshot
And my ScanActivity is,
ScanCode.Java
public class ScanCode extends Activity implements OnClickListener {
Button btnScan;
TextView scanResult;
String text;
Bitmap bmp;
ImageView ivPic;
#Override
public void onCreate(Bundle icicle) {
// TODO Auto-generated method stub
super.onCreate(icicle);
setContentView(R.layout.scan_code);
initViews();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.btnScanCode) {
Intent intent = new Intent(
"com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(intent, 1);
}
}
private void initViews() {
scanResult = (TextView) findViewById(R.id.scanResult);
ivPic = (ImageView) findViewById(R.id.capturedImg);
btnScan = (Button) findViewById(R.id.btnScanCode);
btnScan.setOnClickListener(this);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1)
if (resultCode == Activity.RESULT_OK) {
String contents = data.getStringExtra("SCAN_RESULT");
String format = data.getStringExtra("SCAN_RESULT_FORMAT");
Toast.makeText(getApplicationContext(), contents,
Toast.LENGTH_SHORT).show();
scanResult.setText(contents);
}// if result_ok
}// onActivityResult
}
I know this answer is bit late but I've just used Zxing barcode/QR-Code scanner recently in my app, if anyone has issue implementing it just follow the steps below (Using Android Studio Official IDE for android).
First add dependencies in app --> build.gradle file
dependencies {
compile 'com.journeyapps:zxing-android-embedded:3.2.0#aar'
compile 'com.google.zxing:core:3.2.1'
}
Activity Usage:
public class MainActivity extends AppCompatActivity {
Button btnScan;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnScan = (Button) findViewById(R.id.btnScan);
btnScan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
scanBarcode();
}
});
}
private void scanBarcode()
{
new IntentIntegrator(this).initiateScan();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if(result != null) {
if(result.getContents() == null) {
Log.d("MainActivity", "Cancelled scan");
Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
} else {
Log.d("MainActivity", "Scanned");
Toast.makeText(this, "Scanned: " + result.getContents(), Toast.LENGTH_LONG).show();
}
}
}
}
If you want to use custom callback and BarCodeView. Zxing provide this functionality simply make layout file
<com.journeyapps.barcodescanner.CompoundBarcodeView
android:id="#+id/barcode_scanner"
android:layout_width="match_parent"
android:layout_height="match_parent">
</com.journeyapps.barcodescanner.CompoundBarcodeView>
<TextView
android:id="#+id/tvScanResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Scan Results will be shown here"
android:textColor="#android:color/white"
android:textStyle="bold"/>
In Activity use the following code
public class MainActivity extends AppCompatActivity
{
CompoundBarcodeView barcodeView;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
barcodeView = (CompoundBarcodeView) findViewById(R.id.barcode_scanner);
barcodeView.decodeContinuous(callback);
barcodeView.setStatusText("");
}
#Override
protected void onResume()
{
super.onResume();
barcodeView.resume();
isScanned = false;
}
#Override
protected void onPause()
{
super.onPause();
barcodeView.pause();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
return barcodeView.onKeyDown(keyCode, event) || super.onKeyDown(keyCode, event);
}
private BarcodeCallback callback = new BarcodeCallback()
{
#Override
public void barcodeResult(BarcodeResult result)
{
if (result.getText() != null)
{
barcodeView.setStatusText(result.getText());
tvscanResult.setText("Data found: " + result.getText());
}
//you can also Add preview of scanned barcode
//ImageView imageView = (ImageView) findViewById(R.id.barcodePreview);
//imageView.setImageBitmap(result.getBitmapWithResultPoints(Color.YELLOW));
}
#Override
public void possibleResultPoints(List<ResultPoint> resultPoints)
{
System.out.println("Possible Result points = " + resultPoints);
}
};
}
Source zxing-android-embedded. Hope someone get help from this solution

onActivityResult is not being called

I'm using Activitygroup concept to handle multiple activities under single tab. What I am doing in first activity of tab, I fetch image from gallery and camera, and after that when user selects image that image should move to second activity but those both activities must remain under the same tab. Here is my code...
TabGroupActivity.java
public class TabGroupActivity extends ActivityGroup {
private ArrayList<String> mIdList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (mIdList == null) mIdList = new ArrayList<String>();
}
#Override
public void finishFromChild(Activity child) {
LocalActivityManager manager = getLocalActivityManager();
int index = mIdList.size()-1;
if (index < 1) {
finish();
return;
}
manager.destroyActivity(mIdList.get(index), true);
mIdList.remove(index); index--;
String lastId = mIdList.get(index);
Intent lastIntent = manager.getActivity(lastId).getIntent();
Window newWindow = manager.startActivity(lastId, lastIntent);
setContentView(newWindow.getDecorView());
}
public void startChildActivity(String Id, Intent intent) {
Window window = getLocalActivityManager().startActivity(Id,intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT));
if (window != null) {
mIdList.add(Id);
setContentView(window.getDecorView());
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
//preventing default implementation previous to android.os.Build.VERSION_CODES.ECLAIR
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
onBackPressed();
return true;
}
return super.onKeyUp(keyCode, event);
}
public void onBackPressed() {
int length = mIdList.size();
if ( length > 1) {
Activity current = getLocalActivityManager().getActivity(mIdList.get(length-1));
current.finish();
}
}
}
MainActivity.java
Intent intentPics = new Intent().setClass(this, GalleryPic_First.class);
TabSpec tabPics = tabHost
.newTabSpec("Photo")
.setIndicator("Photo", ressources.getDrawable(R.drawable.icon_apple_config))
.setContent(intentPics);
GalleryPic_First .java
public class GalleryPic_First extends TabGroupActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startChildActivity("EditActivity", new Intent(this,GalleryPic.class));
}
}
GalleryPic.java
public class GalleryPic extends Activity {
private static final int TAKE_PICTURE = 0;
private static final int REQUEST_ID = 1;
private static final int HALF = 2;
private Uri mUri;
private Bitmap mPhoto;
ImageView ivGallery, ivCamera;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gallery_pic);
ivGallery = (ImageView)findViewById(R.id.gallery);
ivCamera = (ImageView)findViewById(R.id.snap);
ivGallery.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
getParent().startActivityForResult(intent, REQUEST_ID);
}
});
ivCamera.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent("android.media.action.IMAGE_CAPTURE");
File f = new File(Environment.getExternalStorageDirectory(), "photo.jpg");
i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
mUri = Uri.fromFile(f);
getParent().startActivityForResult(i, TAKE_PICTURE);
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case TAKE_PICTURE:
if (resultCode == Activity.RESULT_OK && data != null)
{
getContentResolver().notifyChange(mUri, null);
ContentResolver cr = getContentResolver();
try
{
mPhoto = android.provider.MediaStore.Images.Media.getBitmap(cr, mUri);
GalleryPic_Second.bmp = mPhoto;
}
catch (Exception e)
{
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
break;
case REQUEST_ID :
InputStream stream = null;
if (resultCode == Activity.RESULT_OK && data != null) {
try
{
stream = getContentResolver().openInputStream(data.getData());
Bitmap original = BitmapFactory.decodeStream(stream);
GalleryPic_Second.bmp = Bitmap.createScaledBitmap(original, original.getWidth()/HALF, original.getHeight()/HALF, true);
Intent in = new Intent(GalleryPic.this, GalleryPic_Second.class);
TabGroupActivity parent = (TabGroupActivity)getParent();
parent.startChildActivity("ArrowsActivity", in);
}
catch (Exception e)
{
e.printStackTrace();
}
if (stream != null) {
try {
stream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
break;
}
}
#Override
public void onBackPressed() {
// this.getParent().onBackPressed();
TabViewLayout parentTab = (TabViewLayout) this.getParent();
parentTab.switchTabBar(1);
}
}
GalleryPic_Second.java
public class GalleryPic_Second extends Activity {
public static Bitmap bmp;
Button btnUpload;
ImageView iv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.transparent_dialog);
View viewToLoad = LayoutInflater.from(this.getParent()).inflate(R.layout.transparent_dialog, null);
this.setContentView(viewToLoad);
setResult(RESULT_OK);
iv = (ImageView)viewToLoad.findViewById(R.id.photo_holder);
btnUpload = (Button)viewToLoad.findViewById(R.id.upload);
iv.setImageBitmap(bmp);
btnUpload.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
}
#Override
public void onBackPressed() {
// this.getParent().onBackPressed();
finish();
}
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
}
}
But the image is not being displayed in second activity. How to do this?
call this way
GalleryPic.this.startActivityForResult(intent, REQUEST_ID);

setResult doesn't call onActivityResult

I have two activities which starts the same sub-activity for result.
But in only one of them onActivityResult works.
Here are parts of my code
This is my first Activity. As you can see it calls NewCommentActivity in startActivityForResult and this part works fine
public class OfferActivity extends ListActivity implements View.OnClickListener {
...
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.offer_menu_comment:
Intent commentIntent = new Intent(this, NewCommentActivity.class);
commentIntent.putExtra(Offer.OFFER, offer);
startActivityForResult(commentIntent, COMMENT_REQUEST_CODE);
return true;
...
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case COMMENT_REQUEST_CODE:
if (resultCode == RESULT_OK) {
Integer commentCnt = offer.getCommentCnt() + 1;
offer.setCommentCnt(commentCnt);
commentButton.setText(getString(R.string.offer_comments, offer.getCommentCnt()));
}
break;
}
}
...
}
Here is my second activity which calls NewCommentActivity too, but here onActivityResult is not called
public class CommentsActivity extends ListActivity{
...
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
...
case COMMENT_ITEM_ID:
Intent commentIntent = new Intent(this, NewCommentActivity.class);
commentIntent.putExtra(Offer.OFFER, offer);
startActivityForResult(commentIntent, COMMENT_REQUEST_CODE);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case COMMENT_REQUEST_CODE:
if (resultCode == RESULT_OK) {
Integer commentCnt = offer.getCommentCnt() + 1;
offer.setCommentCnt(commentCnt);
Comment comment = data.getParcelableExtra(Comment.COMMENT);
commentImageListAdapter.addItemAtFront(comment);
}
break;
}
}
...
}
And here is code for NewCommentActivity :
public class NewCommentActivity extends Activity implements View.OnClickListener {
private static final String TAG = "Gift/NewCommentActivity";
private Offer offer;
private EditText editText;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_comment);
offer = getIntent().getParcelableExtra(Offer.OFFER);
editText = (EditText) findViewById(R.id.new_comment_text);
Button button = (Button) findViewById(R.id.new_comment_button);
button.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (editText.getText().length() > 0) {
new AddCommentAsyncTask().execute(offer, editText.getText().toString());
}
}
private class AddCommentAsyncTask extends AsyncTask<Object, Void, Comment> {
private String errorString;
private ProgressDialog progressDialog;
#Override
protected Comment doInBackground(Object... objects) {
Offer offer = (Offer) objects[0];
String text = (String) objects[1];
Comment comment = null;
try {
comment = ServiceContainer.getService().addComment(offer, text);
} catch (OfferException e) {
Log.e(TAG, "exception in comment", e);
int id;
if ((id = e.getErrorStringId()) != -1) {
errorString = getString(id);
} else {
errorString = e.getLocalizedMessage();
}
cancel(false);
}
return comment;
}
#Override
protected void onPreExecute() {
progressDialog = Utils.newSpinnerDialog(NewCommentActivity.this, R.string.sending);
}
#Override
protected void onCancelled() {
progressDialog.dismiss();
AlertDialog.Builder builder = Utils.newAlertDialog(NewCommentActivity.this, errorString, true);
builder.setPositiveButton(R.string.dialog_ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
new AddCommentAsyncTask().execute(offer, editText.getText().toString());
}
})
.setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
setResult(RESULT_CANCELED);
finish();
}
})
.create()
.show();
}
#Override
protected void onPostExecute(Comment comment) {
progressDialog.dismiss();
Intent intent = new Intent();
intent.putExtra(Comment.COMMENT, comment);
setResult(RESULT_OK, intent);
finish();
}
}
And finally AndroidManifest for all activities:
<activity android:name=".activity.OfferActivity"
android:configChanges="orientation"/>
<activity android:name=".activity.CommentsActivity"
android:configChanges="orientation"
android:label="#string/comment_activity_title"/>
<activity android:name=".activity.NewCommentActivity"
android:windowSoftInputMode="adjustResize"
android:configChanges="orientation"
android:label="#string/new_comment_activity_title"/>
</application>
Please help me.
Thanks.

Categories

Resources