How to call camera intent in CustomAdapter class in android? - java

I have Adapter class called CustomListAdapter class i written like this,so here i get a problem class cast exception Any one suggest me
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null)
convertView = inflater.inflate(R.layout.myplace, null);
final ImageView ivCamera = (ImageView)convertView.findViewById(R.id.ivCamera);
ivCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder adb = new AlertDialog.Builder(v.getRootView().getContext());
adb.setTitle("Do u Want to Take Photo");
adb.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
count++;
String file = dir+count+".jpg";
File newfile = new File(file);
try {
newfile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
Uri outputFileUri = Uri.fromFile(newfile);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
((Activity) context).startActivityForResult(cameraIntent, TAKE_PHOTO_CODE);
}
});
adb.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
adb.show();
}
});
}
I get class cast exception please suggest me how to resolve this issue
in My Activity i call This method
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
customListAdapter.onActivityResult(requestCode, resultCode, data);
Bitmap bp = (Bitmap) data.getExtras().get("data");
ivCamera.setImageBitmap(bp);
}

Try this :
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case TAKE_PHOTO_CODE:
if(resultCode == Activity.RESULT_OK) {
customListAdapter.onActivityResult(requestCode, resultCode, data);
Bitmap bp = (Bitmap) data.getExtras().get("data");
ivCamera.setImageBitmap(bp);
}
break;
}
}

http://developer.android.com/training/camera/photobasics.html
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
mImageView.setImageBitmap(imageBitmap);
}
}
1) you have no check - probably onActivityResult() fires after some other activities started for result
2) resultCode == RESULT_OK && extras != null && extras.get("data") != null could be critical
3) try to run the receiving code in debug mode - some devices may not pass the bitmap (because it's very big, for example). if so - try to supply photoURI and then resize the photo before showing it
4) try to find libraries for getting photo

Yes, there are 2 types of Context in Android. 1 of them is Activity-type, the other - application Context.
Obviously, you should pass to adapter ref to your Activity, i.e. new Adapter(YourActivity.this), rather than new Adapter(getApplicationContext())
Answer the question - what activity should perform onActivityResult(), if you start activity for result using just getApplicationContext().startActivityForResult()? - And all become obvious.

Related

How to use onAcitivtyResult into some fragments int Android

In my application i have one activity (MainActivity) and some fragments (ServicesFragment , NewAddressFragment).
ServicesFragment used in viewPager and NewAddressFragment used getFragmentManager().replace ... for show this fragments!
in this fragments i used onActivityResult, but get conflict in one of fragments not call codes of onActivityResult codes in one of fragments.
I write below codes, please see this.
MainActivity :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Fragment servicesFrag = bottomNavAdapter.getItem(mainViewPager.getCurrentItem());
if (servicesFrag instanceof ServicesFragment) {
((ServicesFragment) servicesFrag).onActivityResult(requestCode, resultCode, data);
}
}
ServiceFragment :
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.e("BazaarPaymentLog", "Result");
Log.e("BazaarPaymentLog", "bazaarRequestCode : " + bazaarRequestCode);
if (iabHelper == null) return;
if (requestCode == bazaarRequestCode) {
String purchaseData = data.getStringExtra("INAPP_PURCHASE_DATA");
if (resultCode == RESULT_OK) {
try {
JSONObject jo = new JSONObject(purchaseData);
purchaseToken = jo.getString("purchaseToken");
productId = jo.getString("productId");
packageName = jo.getString("packageName");
Log.e("BazaarPaymentLog", "purchaseToken : " + purchaseToken);
if (iabHelper != null) {
iabHelper.handleActivityResult(requestCode, resultCode, data);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
NewAddressFragment :
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_TAKE_PHOTO || requestCode == REQUEST_PICK_PHOTO) {
if (data != null) {
// Get the Image from data
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getContentResolver().query(selectedImage, filePathColumn, null, null, null);
assert cursor != null;
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
mediaPath = cursor.getString(columnIndex);
cursor.close();
postPath = mediaPath;
uploadImageToServer(postPath);
}
} else if (requestCode == CAMERA_PIC_REQUEST) {
if (Build.VERSION.SDK_INT > 21) {
postPath = mImageFileLocation;
} else {
postPath = fileUri.getPath();
}
uploadImageToServer(postPath);
}
} else if (resultCode != RESULT_CANCELED) {
Toast.makeText(getActivity(), "Failed", Toast.LENGTH_LONG).show();
}
}
When write onActivityResult code in MainActivity, in ServicesFragment call onActivityResult codes and in NewAddressFragment not call onActivityResult codes.
But When remove onActivityResult code in MainActivity, in ServicesFragment not call onActivityResult codes and in NewAddressFragment call onActivityResult codes.
How can i fix it?
Inside onActivityResult of MainActivity use this :
Instead of this :-
#Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Fragment servicesFrag = bottomNavAdapter.getItem(mainViewPager.getCurrentItem());
if (servicesFrag instanceof ServicesFragment) {
((ServicesFragment) servicesFrag).onActivityResult(requestCode, resultCode, data);
}
}
Use this :-
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
for(Fragment fragment : getSupportFragmentManager().getFragments()){
fragment.onActivityResult(requestCode,resultCode,data);
}
}
let me know if it is working or not
please add this line to onActivityResult in activity
Fragment servicesFrag = bottomNavAdapter.getItem(mainViewPager.getCurrentItem());
Fragment addressFrag = findFragmentByTag("NewAddressFragmentTag");
if (servicesFrag instanceof ServicesFragment) {
((ServicesFragment) servicesFrag).onActivityResult(requestCode, resultCode, data);
}
if (addressFrag instanceof NewAddressFragment) {
((NewAddressFragment) addressFrag).onActivityResult(requestCode, resultCode, data);
}
}
I can resolved my problem!
Change MainActivity codes with below codes :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Fragment servicesFrag = bottomNavAdapter.getItem(mainViewPager.getCurrentItem());
Fragment addressFrag = getSupportFragmentManager().findFragmentByTag("NewAddressFragmentTag");
if (servicesFrag instanceof ServicesFragment) {
((ServicesFragment) servicesFrag).onActivityResult(requestCode, resultCode, data);
}
if (addressFrag instanceof NewAddressFragment) {
super.onActivityResult(requestCode, resultCode, data);
}
}
I hope help this for another dear developers

multiple Onactivityresult method in Android

I added onClick() button in fragment to display the result. I also added onActivityResult() method in MyActivity. I want to add onClick() button in more fragments and also show results.
In that case how I should write multiple onActivityResult() method in activity?
Below is my code for OnActivityResultmethod:
button = (Button) view.findViewById(R.id.zing);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
IntentIntegrator scanIntegrator = new IntentIntegrator(getActivity());
scanIntegrator.initiateScan();
}
});
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
//super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode,
data);
Fragment fragment = this.getFragmentManager().findFragmentById(R.id.total_frame_content);
if (fragment instanceof CustomerIdFragment) {
if (scanResult != null) {
if (scanResult.getContents() == null) {
Toast.makeText(this, "Cancelled", Toast.LENGTH_SHORT).show();
} else {
//String customerSno = scanResult.getContents().substring(0, 10),
// passCode = scanResult.getContents().substring(10, 14);
Toast.makeText(this, " " + scanResult.getContents(), Toast.LENGTH_SHORT).show();
// System.out.println("Result" + scanResult.getContents());
}
}
}
}
Try This u can not overide method multiple time so u pas int value
startActivityForResult(intent,1);
in on activity result
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1){
if(resultCode == RESULT_OK){
//do somthing
}
}
if(requestCode == 2){
if(resultCode == RESULT_OK){
//do somthing
}
}
if(requestCode == 3){
if(resultCode == RESULT_OK){
//do somthing
}
}
}
Edited Answer
In Your Fragment java File
private int PICK_IMAGE_REQUEST_CODE = 1;
btChoseFile = (Button)view.findViewById(R.id.btChoseFile);
btStar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("*/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST_CODE);
}
});
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == PICK_IMAGE_REQUEST_CODE){
Toast.makeText(getActivity(),"On Activity Result in fragment",Toast.LENGTH_LONG).show();
}
}
You just need to use switch case for that like below:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
switch (requestCode) {
case REQUEST_CODE_CAPTURE_IMAGE:
if (requestCode == REQUEST_CODE_CAPTURE_IMAGE && resultCode == Activity.RESULT_OK ) {
//your code
break;
case PHOTO_PICKER_ID:
if (requestCode == PHOTO_PICKER_ID && resultCode == Activity.RESULT_OK && null != data) {
//your code
}
break;
}
} catch (Exception e)
{
Log.d("krvrrusbviuritiribtr", e.getMessage());
}
}
When you call startActivityForResult(intent,requestCode);, you just need to use different requestCode. This number will be send to the onActivityResult(requestCode, resultCode, intent)
Create some constants for the request in your activity (call it MyActivity).
public class MyActivity{
private static final int REQUEST_ONE = 1;
private static final int REQUEST_TWO = 2;
...
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
//Management of the result, see below
}
}
Use the constant corresponding to the request calling.
//startActivityForResult(intent,REQUEST_CODE);
In you first fragment, you will use
public void clickButton(View v){
startActivityForResult(intent,MyActivity.REQUEST_ONE);
}
In the second fragment, you will use
public void clickButton(View v){
startActivityForResult(intent,MyActivity.REQUEST_TWO);
}
Then you just need to implements the result method in the activity to take care of the requestCode value to execute the correct code. Using a switch or if else conditions. There are more possibilities (using some pattern) but the easiest are those.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if(requestCode == REQUEST_ONE){
// the code for request one
} else if(requestCode == REQUEST_TWO){
// the code for request two
} else {
super.onActivityResult(requestCode, resultCode, intent);
}
}
or with a switch
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
switch(requestCode)
case REQUEST_ONE:
// the code for request one
break;
case REQUEST_TWO:
// the code for request two
break;
default:
super.onActivityResult(requestCode, resultCode, intent);
}
}
If you have too much request, create one method for each requests, this will keep the result method more readable.

ImageView not showing image selected from gallery

So I have a button that loads the gallery, and selects an image using this code...
public void getGalleryImage(View v){
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivityForResult(intent, 1);
}
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();
galleryImage.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
But when it goes back to the original activity, the ImageView still doesn't show anything. It doesn't give me any errors, or anything like that. Here the XML for the ImageView...
<ImageView
android:id="#+id/galleryImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
How can I get it to show?
I ended up figuring something out. I just did...
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
galleryImage.setImageURI(selectedImage);
}
This worked for what I was trying to accomplish.
Try this:
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();
galleryImage.setImageBitmap(MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri));
}
}
public class MainActivity extends AppCompatActivity{
ImageView image;
Button pick;
int TAG_IMAGE = 100;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
image = (ImageView) findViewById(R.id.imageView);
pick = (Button) findViewById(R.id.button);
pick.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Intent intent = new Intent(Intent.ACTION_GET_CONTENT, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("*/*");
startActivityForResult(Intent.createChooser(intent,"Select Image "),TAG_IMAGE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == TAG_IMAGE && resultCode == RESULT_OK )
{
Uri selectedImage = data.getData();
try
{
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,filePath,null,null,null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePath[0]);
String images = cursor.getString(columnIndex);
image.setImageURI(selectedImage);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}

How to process image once selected?

I'm retriving image from a IO file manager (one's installed). Anyhow when I try to retrieve an image I'm not sure where it's gone? Or how to save it as a bitmap?
Code below:
public void onClick(View v)
{
if(v.getId() == R.id.facebook_icon || v.getId() == R.id.facebook_text)
{
//Facebook
}
if(v.getId() == R.id.camera_icon || v.getId() == R.id.camera_text)
{
//Camera
}
if(v.getId() == R.id.folder_icon || v.getId() == R.id.folder_text)
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), MODE_WORLD_READABLE);
}
}
protected void onActivityForResult()
{
//Where is the image? How to get?
System.out.println("Image gotton");
}
First of all, you are not overriding onActivityResult. Note the method signature: http://developer.android.com/reference/android/app/Activity.html#onActivityResult(int, int, android.content.Intent)
You should be using #Override annotations so you know when something's wrong.
Try something like:
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK)
{
Uri imageUri = data.getData();
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
}
}

capturing image using camera in Android

Hi stackoverflow friends,
I need to take a picture using camera and after takin the picture go to next activity without showing the first activity. And display it in an imageview.
Below is the flow of my application
first activity-> there is button for camera intent->go to the next activity(without showing the fist activity) second activity->there i need to show the image in imageview.
I saw a lot of examples of camera intent nobody explains how to go to the next activity without showing the first and display it in imageview of second.
Any outofmemeory problem occurs while displaying images in imageview repeatedly?
Thanks in advance
In First activity :
Button b=(Button)findViewByid(R.id.button);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
doTakePhotoAction();
}
});
private void doTakePhotoAction() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
mUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
"pic_" + String.valueOf(System.currentTimeMillis()) + ".jpg"));
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mUri);
try {
intent.putExtra("return-data", true);
startActivityForResult(intent, CAMERA_RESULT);
// finish();
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
}
protected void onActivityResult(int requestCode,
int resultCode, Intent data) {
if (resultCode != RESULT_OK) {
return;
}
if (requestCode == CAMERA_RESULT) {
Intent intent = new Intent(this, nextimage.class);
// here you have to pass absolute path to your file
intent.putExtra("image-path", mUri.getPath());
intent.putExtra("scale", true);
startActivity(intent);
finish();
}
}
In nextimage.class you can set one image view and get the imagepath from putExtra and place it in imageview.
String mImagePath = extras.getString("image-path");
Bitmap mBitmap = getBitmap(mImagePath);
private Uri getImageUri(String path) {
return Uri.fromFile(new File(path));
}
private Bitmap getBitmap(String path) {
Uri uri = getImageUri(path);
InputStream in = null;
try {
in = mContentResolver.openInputStream(uri);
return BitmapFactory.decodeStream(in);
} catch (FileNotFoundException e) {
Log.e(TAG, "file " + path + " not found");
}
return null;
}
place the bitmap in the imageview.you have to create imageview in secondActivity.
use a camera intent....here's a simple code
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.widget.ImageView;
public class CameraIntent extends Activity {
final static int CAMERA_RESULT = 0;
ImageView imv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, CAMERA_RESULT);
}
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (resultCode == RESULT_OK)
{
Get Bundle extras = intent.getExtras();
Bitmap bmp = (Bitmap) extras.get("data");
imv = (ImageView) findViewById(R.id.ReturnedImageView);
imv.setImageBitmap(bmp);
}
}
}
Use Following Code for that, it will solve your problem.
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
onActivityResult() Method:-
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == CAMERA_PIC_REQUEST) {
bmpImage = (Bitmap) data.getExtras().get("data");
drawable = new BitmapDrawable(bmpImage);
mImageview.setImageDrawable(drawable);
}
}
}

Categories

Resources