I have already tried this code, but i didn't saw photo shared in my account.
File file = new File("sdcard/1346249742258.jpg");
String photoUri = null;
photoUri = file.getAbsolutePath();
Intent shareIntent = ShareCompat.IntentBuilder.from(this)
.setText("Sharing an image on Google!").setType("image/jpeg")
.setStream(Uri.parse(photoUri)).getIntent()
.setPackage("com.google.android.apps.plus");
startActivity(shareIntent);
The Google+ app only supports content:// URIs. You will need to use the MediaStore API for this purpose.
File tmpFile = new File("/path/to/image");
final String photoUri = MediaStore.Images.Media.insertImage(
getContentResolver(), tmpFile.getAbsolutePath(), null, null);
Intent shareIntent = ShareCompat.IntentBuilder.from(this)
.setText("Hello from Google+!")
.setType("image/jpeg")
.setStream(Uri.parse(photoUri))
.getIntent()
.setPackage("com.google.android.apps.plus");
Integrate ForGooglePlus Activity in your code and put URL(imageUrl) ,Description(description text) and contentUrl(URL) for the same.
Note : bellow code also worked in my app.
public class ForGooglePlus extends Activity
{
private String imageUrl, description, contentUrl;
private Context mContext;
private int REQUEST_FOR_GOOGLE_PLUS = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
mContext = this;
imageUrl = getIntent().getStringExtra("URL");
description = getIntent().getStringExtra("Description");
contentUrl = getIntent().getStringExtra("contentUrl");
if (isPackageInstalled("com.google.android.apps.plus", mContext)) {
if (imageUrl == null) {
imageUrl = "";
}
if (description == null) {
description = "";
}
// Intent shareIntent = new PlusShare.Builder(this)
// .setType("image/jpeg")
// .setText(description)
// .setStream(getUriFromUrl(imageUrl))
// .setContentUrl(Uri.parse(contentUrl))
// .getIntent();
Uri uri = getUriFromUrl(imageUrl);
if (uri != null) {
Intent shareIntent = ShareCompat.IntentBuilder
.from(ForGooglePlus.this)
.setText(description + "\n" + contentUrl)
.setType("image/jpeg").setStream(uri).getIntent()
.setPackage("com.google.android.apps.plus");
startActivityForResult(shareIntent, REQUEST_FOR_GOOGLE_PLUS);
} else {
Intent shareIntent = ShareCompat.IntentBuilder
.from(ForGooglePlus.this)
.setText(description + "\n" + contentUrl)
.setType("image/jpeg").getIntent()
.setPackage("com.google.android.apps.plus");
startActivityForResult(shareIntent, REQUEST_FOR_GOOGLE_PLUS);
}
} else {
Toast.makeText(mContext, "Application not found", Toast.LENGTH_LONG)
.show();
finish();
}
}
public Uri getUriFromUrl(String thisUrl) {
try {
Bitmap inImage = ImageLoader.getInstance().loadImageSync(thisUrl);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = Images.Media.insertImage(
mContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
private boolean isPackageInstalled(String packagename, Context context) {
PackageManager pm = context.getPackageManager();
try {
pm.getPackageInfo(packagename, PackageManager.GET_ACTIVITIES);
return true;
} catch (NameNotFoundException e) {
return false;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_FOR_GOOGLE_PLUS) {
if (resultCode == RESULT_OK) {
finish();
} else {
Toast.makeText(mContext,
mContext.getString(R.string.msg_gp_cancel),
Toast.LENGTH_LONG).show();
finish();
}
}
}
}
I am also posting image on google plus through android using intent i am taking screen shot of device and posting it on google plus, i used your code i am getting exception FileNotFoundException() and as you mention to use absolute path i got error,
The method getAbsolutePath() is undefined for the type String
my code is given below
please suggest me correction in code
package com.testproject;
import java.io.File;
import java.io.FileNotFoundException;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RelativeLayout;
public class TestProjectActivity extends Activity {
private Button share_btn = null;
private String url=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
share_btn = (Button)findViewById(R.id.share_btn);
share_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent=new Intent(TestProjectActivity.this,ShareDialogActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivityForResult(intent, 1);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
String url =takeScreenShot();
super.onActivityResult(requestCode, resultCode, data);
switch (resultCode) {
case 1:
String share = data.getExtras().getString("NAME");
if(share!=null && share.equalsIgnoreCase("Share with Instagram")){
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("image/jpg");
i.putExtra(Intent.EXTRA_STREAM, Uri.parse(url));
startActivity(Intent.createChooser(i, "Share Image"));
}
if(share!=null && share.equalsIgnoreCase("Share with GooglePlus")){
Intent shareIntent = new Intent(Intent.ACTION_SEND);
File tmpFile = new File(url);
String photoUri=null;
photoUri = url.getAbsolutePath();
try {
photoUri = MediaStore.Images.Media.insertImage(
getContentResolver(), tmpFile.getAbsolutePath(), null, null);
shareIntent = ShareCompat.IntentBuilder.from(this)
.setText("Hello from Google+!")
.setType("image/jpeg")
.setStream(Uri.parse(photoUri))
.getIntent()
.setPackage("com.google.android.apps.plus");
startActivity(shareIntent);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
break;
}
}
public String takeScreenShot(){
try{
RelativeLayout view = (RelativeLayout)findViewById(R.id.icflag_layout);
View v1 = view.getRootView();
System.out.println("Root View : "+v1);
v1.setDrawingCacheEnabled(true);
Bitmap bm = v1.getDrawingCache();
url =MediaStore.Images.Media.insertImage(getContentResolver(), bm,"screeshot.jpg", 1233+ ".jpg Card Image");
}
catch(OutOfMemoryError e){
}
return url;
}
}
Thank you and regards
Nitin
Don't use absolute path.
OnActivityResult() use this after capturing image from camera.
Uri photoUri = intent.getData();
Intent shareIntent = ShareCompat.IntentBuilder.from(this)
.setText("Hello From Google+!")
.setType("image/jpeg")
.setStream(photoUri)
.getIntent()
.setPackage("com.google.android.apps.plus");
startActivity(shareIntent);
This is working for me.
HEy Deepika you are getting file nor found exception because that google plus app is not present on the device the way you have coded is just to start the native app from the device
it will work only if the native ap is actully present
otherway is to have google plus sdk which is small jar file with that you can share image
https://developers.google.com/+/mobile/android/
You can share image using below api's. For detailed steps check tutorial
http://androidsrc.net/integrating-google-plus-sign-in-into-your-android-application/
/**
* API to process media post request start activity with MIME type as video
* and image
*/
private void processShareMedia() {
Intent photoPicker = new Intent(Intent.ACTION_PICK);
photoPicker.setType("video/*, image/*");
startActivityForResult(photoPicker, PICK_MEDIA_REQUEST_CODE);
}
/**
* Handle results for your startActivityForResult() calls. Use requestCode
* to differentiate.
*/
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PICK_MEDIA_REQUEST_CODE) {
// If picking media is success, create share post using
// PlusShare.Builder
if (resultCode == RESULT_OK) {
Uri selectedImage = data.getData();
ContentResolver cr = this.getContentResolver();
String mime = cr.getType(selectedImage);
PlusShare.Builder share = new PlusShare.Builder(this);
share.setText("Hello from AndroidSRC.net");
share.addStream(selectedImage);
share.setType(mime);
startActivityForResult(share.getIntent(),
SHARE_MEDIA_REQUEST_CODE);
}
}
}
Related
I need to send an attachment along with some basic information by mail using my app. But the attachment is blank when I'm trying to invoke the mail activity using intent.
Here's the code for getting filepath and then sending the attachment
public class Pickafile extends AppCompatActivity {
TextView textFile;
static String FilePath;
private static final int PICKFILE_RESULT_CODE = 1;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery);
Button buttonPick = (Button) findViewById(R.id.buttonpick);
Button bp = (Button) findViewById(R.id.proceed);
textFile = (TextView) findViewById(R.id.textfile);
buttonPick.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("file/*");
startActivityForResult(intent, PICKFILE_RESULT_CODE);
}
});
bp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_SENDTO);
//intent.setType("text/plain");
intent.setData(Uri.parse("mailto:"));
intent.putExtra(Intent.EXTRA_SUBJECT, " Report Particulars for " + MainActivity.name);
/*File root = Environment.getExternalStorageDirectory();
File file = new File(root, FilePath);
if (!file.exists() || !file.canRead()) {
return;
}*/
/*if(FilePath!=null)
{
intent.putExtra(Intent.EXTRA_STREAM, FilePath);
}*/
intent.putExtra(Intent.EXTRA_TEXT, MainActivity.testfunc());
intent.putExtra(Intent.EXTRA_STREAM, FilePath);
//startActivity(Intent.createChooser(intent, "Pick an Email provider"));
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
switch (requestCode) {
case PICKFILE_RESULT_CODE:
if (resultCode == RESULT_OK) {
FilePath = data.getData().getPath();
textFile.setText(FilePath);
}
break;
}
}
}
testfunc() is used to get body of the mail (name, age, phone,etc.)
Thanks in advance!
You should check the log if there is any error.
Possible case:
1. The file is too large, exceed maximum size of email attachment (20Mb for Gmail)
2. Missing READ_EXTERNAL_STORAGE permission if the file is saved in external storage.
3. Missing file_provider in manifest
I want to share the edited photo to a social media site after editing it using PhotoEditorSDK Android version, so I created a shareImage() function.
However I am not sure how to reference the edited image from the PhotoEditorSDK in the share function. Currently the code listed below I just add a dummy image of the image taken from drawable resources.
Also currently the share button I placed in PhotoEditorSDK photoeditor view keeps crashing on press.
public class PhotoEditorActivity extends Activity implements PermissionRequest.Response {
private static final String FOLDER = "ArtCam";
public static int CAMERA_PREVIEW_RESULT = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
protected void onResume() {
super.onResume();
SettingsList settingsList = new SettingsList();
settingsList.getSettingsModel(EditorLoadSettings.class)
.setImageSourcePath(selectedImagePath, true) // Load with delete protection true!
.getSettingsModel(EditorSaveSettings.class)
.setExportDir(Directory.DCIM, FOLDER)
.setExportPrefix("result_")
.setSavePolicy(
EditorSaveSettings.SavePolicy.KEEP_SOURCE_AND_CREATE_ALWAYS_OUTPUT
);
new PhotoEditorBuilder(this)
.setSettingsList(settingsList)
.startActivityForResult(this, CAMERA_PREVIEW_RESULT);
shareImage();
}
private void shareImage() {
Intent shareIntent;
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/Share.png";
OutputStream out = null;
File file = new File(path);
try {
out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
path = file.getPath();
Uri bmpUri = Uri.parse("file://" + path);
shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
shareIntent.putExtra(Intent.EXTRA_TEXT, "#" + getPackageName());
shareIntent.setType("image/png");
startActivity(Intent.createChooser(shareIntent, "Share with"));
}
Please look at the demo code here https://github.com/imgly/pesdk-android-demo/blob/master/app/src/main/java/com/photoeditorsdk/android/app/MainActivity.java
You have to wait for onActivityResult to get the resultPath
#Override
protected void onActivityResult(int requestCode, int resultCode, android.content.Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == CAMERA_PREVIEW_RESULT) {
String resultPath = data.getStringExtra(ImgLyIntent.RESULT_IMAGE_PATH);
if (resultPath != null) {
// Add result file to Gallery
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(resultPath))));
}
//TODO: Share the resultPath file
} else if (resultCode == RESULT_CANCELED && requestCode == CAMERA_PREVIEW_RESULT && data != null) {
String sourcePath = data.getStringExtra(ImgLyIntent.SOURCE_IMAGE_PATH);
Toast.makeText(PESDK.getAppContext(), "Editor canceled, sourceType image is:\n" + sourcePath, Toast.LENGTH_LONG).show();
}
}
So I have a button, which makes the camera intent to appear to take a picture.
I will be using that picture to display it.
The problem is the code after the new Intent continues executing and breaks because I have no image back yet until I take the pic.
public class WebViewActivity extends Activity {
private WebView webView;
private Uri picUri;
private String finalEncodedImage;
private byte[] finaldata;
FileInputStream finall = null;
private Handler handler = new Handler();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new MyWebViewClient());
String otherPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).toString() + "/Camera/IMG_20140213_142815.jpg";
File imagefile = new File(otherPath);
FileInputStream fis = null;
try {
fis = new FileInputStream(imagefile);
finall = fis;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Bitmap bi = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bi.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] data = baos.toByteArray();
finaldata = data;
String image64 = Base64.encodeToString(data, Base64.DEFAULT);
finalEncodedImage = image64;
webView.loadUrl("http://myhtml.html");
}
private class MyWebViewClient extends WebViewClient {
public Intent CameraTakesPic ()
{
//OPEN CAMERA AND TAKE PICTURE
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, 1);
}
return takePictureIntent;
}
#Override
public WebResourceResponse shouldInterceptRequest (final WebView view, String url) {
if (url.contains("img03"))
{
//%%%
//OPEN CAMERA AND TAKE PICTURE
Intent picIntent = new Intent();
picIntent = CameraTakesPic();
//WITH THE PICTURE
Bundle extras = picIntent.getExtras();
if (extras != null)
{
Bitmap imageBitmap = (Bitmap) extras.get("data");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
//MAKE IT A BYTE ARRAY
byte[] data = baos.toByteArray();
finaldata = data;
InputStream is = new ByteArrayInputStream(finaldata);
//%%%
return new WebResourceResponse("text/html", "UTF-8", is);
}
else
{
return null;
}
}
else
{
return null;
}
// convert String into InputStream
//return super.shouldInterceptRequest(view, url);
//return super.shouldInterceptRequest(view, "<img src=\"data:image/jpeg;base64," + finalEncodedImage + "\" /></img>");
}
}
public class CameraContentDemoActivity extends WebViewActivity {
private static final int CONTENT_REQUEST=1337;
private File output=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent i=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File dir=
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
output=new File(dir, "CameraContentDemo.jpeg");
i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(output));
startActivityForResult(i, CONTENT_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
if (requestCode == CONTENT_REQUEST) {
if (resultCode == RESULT_OK) {
Intent i=new Intent(Intent.ACTION_VIEW);
i.setDataAndType(Uri.fromFile(output), "image/jpeg");
startActivity(i);
finish();
}
}
}
}
}
So I don't want to let the code running until I have my picture taken.
What am I doing wrong?
I guess opening a new Intent does not mean the rest of the code stops.
So which is my solution?
I guess opening a new Intent does not mean the rest of the code stops
startActivity() and startActivityForResult() are asynchronous.
So which is my solution?
Process the results of the picture in onActivityResult(). You can see an example of how to do this in the developer documentation and in this sample app:
package com.commonsware.android.camcon;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import java.io.File;
public class CameraContentDemoActivity extends Activity {
private static final int CONTENT_REQUEST=1337;
private File output=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent i=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File dir=
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
output=new File(dir, "CameraContentDemo.jpeg");
i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(output));
startActivityForResult(i, CONTENT_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
if (requestCode == CONTENT_REQUEST) {
if (resultCode == RESULT_OK) {
Intent i=new Intent(Intent.ACTION_VIEW);
i.setDataAndType(Uri.fromFile(output), "image/jpeg");
startActivity(i);
finish();
}
}
}
}
I ended up creating a boolean and a loop, so my code loops on a sleep while the boolean is false and when I have the picture saved and returned, I set the boolean to true and it exits the loop.
I know is not ideal solution, but works for now.
I am implementing an MMS application for that i am using camera also.Main theme of main application was take picture using device camera ater that send that image as MMS to specified number.But while attahing the image i am getting error warning like
Unable to attach File not support
Please help to resolve my problem.
Thanks,
public class MMS extends Activity implements OnClickListener {
int TAKE_PHOTO_CODE = 0;
public static int count=0;
EditText preLoc,comeby;
Button ok,capture;
String photo;
String dir;
boolean GPS,flag;
String cityName=null;
String SubThorugh = null;
Intent i;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.mms);
preLoc = (EditText)findViewById(R.id.etPreLoc1);
comeby = (EditText)findViewById(R.id.etComing1);
ok = (Button)findViewById(R.id.bOK1);
capture = (Button) findViewById(R.id.btnCapture);
capture.setOnClickListener(this);
ok.setOnClickListener(this);
i = getIntent();
GPS = i.getBooleanExtra("GPSneed", false);
ok.setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch(arg0.getId())
{
case R.id.btnCapture:
capturePicture();
break;
case R.id.bOK1:
sendMMS();
preLoc.setText(cityName+SubThorugh);
break;
}
}
private void sendMMS() {
// TODO Auto-generated method stub
try {
Uri uri = Uri.parse(photo);
Intent i = new Intent(Intent.ACTION_SEND);
//i.putExtra("address",etnum.getText().toString());
//i.putExtra("sms_body",etmsg.getText().toString());
i.putExtra(Intent.EXTRA_STREAM,uri);
i.setType("image/*");
startActivity(i);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == TAKE_PHOTO_CODE && resultCode == RESULT_OK) {
Log.d("CameraDemo", "Pic saved");
Toast.makeText(getApplicationContext(), "photo saved as: "+photo, Toast.LENGTH_LONG).show();
}
}
private void capturePicture() {
//here,we are making a folder named picFolder to store pics taken by the camera using this application
final String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/picFolder/";
File newdir = new File(dir);
newdir.mkdirs();
// here,counter will be incremented each time,and the picture taken by camera will be stored as 1.jpg,2.jpg and likewise.
count++;
String file = dir+count+".jpg";
photo = file;
File newfile = new File(file);
try {
newfile.createNewFile();
} catch (IOException e) {}
Uri outputFileUri = Uri.fromFile(newfile);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cameraIntent, TAKE_PHOTO_CODE);
}
In my app, I have a button1 which calls camera, and after capturing the image, it must be saved to the device gallery. When I click on button2, it must open the gallery, and ask to select a picture. When selected, it must be shown on the imageView below these buttons.
Here is my code:
package com.android.imageuploading;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class ImageUploadingActivity extends Activity {
private static final int REQUEST_CODE = 1;
private Bitmap bitmap;
private ImageView imageView;
private Button button_1;
public int TAKE_PICTURE = 1;
private Button button_2;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imageView = (ImageView) findViewById(R.id.image);
button_1 = (Button) findViewById(R.id.button1);
button_1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, TAKE_PICTURE);
}
});
button_2 = (Button) findViewById(R.id.button2);
button_2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
pickImage(getCurrentFocus());
}
});
}
public void pickImage(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(intent, REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK)
try {
// We need to recyle unused bitmaps
if (bitmap != null) {
bitmap.recycle();
}
InputStream stream = getContentResolver().openInputStream(
data.getData());
bitmap = BitmapFactory.decodeStream(stream);
stream.close();
imageView.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
super.onActivityResult(requestCode, resultCode, data);
}
public static boolean isIntentAvailable(Context context, String action) {
final PackageManager packageManager = context.getPackageManager();
final Intent intent = new Intent(action);
List<ResolveInfo> list = packageManager.queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
}
The problem is, when I capture the image, it asks for save or discard. When I click on save, my app crashes, saying:
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { act=inline-data (has extras) }} to activity {com.android.imageuploading/com.android.imageuploading.ImageUploadingActivity}: java.lang.NullPointerException
Where do I need to change the code?
in my case i use this: when i click on save button pic is save and return me path in filePath variable.
String filePath =
Environment.getExternalStorageDirectory() +"/your_image_name.jpeg";
File file = new File(filePath);
Uri output = Uri.fromFile(file);
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, output);
and in onactivityresul() i use this "filePath" .
Capture Image:
public class Camera extends Activity
{
private static final int CAMERA_REQUEST = 1888;
private String selectedImagePath;
WebView webview;
String fileName = "capturedImage.jpg";
private static Uri mCapturedImageURI;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Intent cameraIntent = new Intent(ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == RESULT_OK) {
if (requestCode == CAMERA_REQUEST)
{
Bitmap photo = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
Random randomGenerator = new Random();randomGenerator.nextInt();
String newimagename=randomGenerator.toString()+".jpg";
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + newimagename);
try {
f.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//write the bytes in file
try {
fo = new FileOutputStream(f.getAbsoluteFile());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
fo.write(bytes.toByteArray());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
uri=f.getAbsolutePath();
//this is the url that where you are saved the image
}
}
Choose Image:
public class ChoosePicture extends Activity
{
private static final int SELECT_PICTURE = 1;
private String selectedImagePath;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
webview=(WebView)findViewById(R.id.webView1);
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(intent, SELECT_PICTURE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE)
{
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
try {
FileInputStream fileis=new FileInputStream(selectedImagePath);
BufferedInputStream bufferedstream=new BufferedInputStream(fileis);
byte[] bMapArray= new byte[bufferedstream.available()];
bufferedstream.read(bMapArray);
Bitmap bMap = BitmapFactory.decodeByteArray(bMapArray, 0, bMapArray.length);
//this is the image that you are choosen
if (fileis != null)
{
fileis.close();
}
if (bufferedstream != null)
{
bufferedstream.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
}