this is my code it store captured picture form camera and save it on the SDcard but Now i want to enhance this code to taking pictures every 5 seconds If any body having an idea how to do this ,please share
public class MainActivity extends ActionBarActivity {
private final int requestCode = 20;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int pictureCounter = 10;
imageHolder = (ImageView)findViewById(R.id.captured_photo);
Button capturedImageButton = (Button)findViewById(R.id.photo_button);
capturedImageButton.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent photoCaptureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(photoCaptureIntent, requestCode);
}
});
}
#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");
String partFilename = currentDateFormat();
storeCameraPhotoInSDCard(bitmap, partFilename);
}
}
private String currentDateFormat(){
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HH_mm_ss");
String currentTimeStamp = dateFormat.format(new Date());
return currentTimeStamp;
}
private void storeCameraPhotoInSDCard(Bitmap bitmap, String currentDate){
File outputFile = new File(Environment.getExternalStorageDirectory(), "photo_" + currentDate + ".jpg");
try {
FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
You should implement a runnable interface that uses threads. This way you could call the function on the OnClick method, then call Thread.sleep(timeinmilliseconds), then call the function inside the onClick method again, as many times as needed.
Here is an example of how to use threads:
http://www.wideskills.com/java-tutorial/java-threads-tutorial
Related
I am trying to upload a video to parse server using the camera intent to capture the videos.
the code is as follows. Now my problem is that the video is getting played in the videoView using the videoUri, BUT its not getting uploaded to the server. I am getting a FileNotFoundException saying that "there exists no such file or directory",
Example:-
I/info: content://media/external/video/media/57463 //this is the Log output for videoUri//
W/System.err: java.io.FileNotFoundException: /external/video/media/57463 (No such file or directory)
Can somebody please help with this issue??
public class VideoActivity extends AppCompatActivity {
static final int REQUEST_VIDEO_CAPTURE = 1;
Uri videoUri,vUri;
ParseUser currentUser;
VideoView videoView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);
currentUser=ParseUser.getCurrentUser();
Button captureVideo = (Button) findViewById(R.id.captureVideo);
videoView=(VideoView) findViewById(R.id.videoView);
Button saveButton=(Button) findViewById(R.id.saveButton);
//save Button clicks handled here.
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(videoUri!=null){
Log.i("info", ""+videoUri);
byte[] bytes = convertVideoToBytes(videoUri);
//now lets try and add this uri file to the parse server in a parsefile.
ParseFile parseVideoFile = new ParseFile("video.mp4", bytes);
parseVideoFile.saveInBackground();
currentUser.put("video", parseVideoFile);
currentUser.saveInBackground();
}else{
Toast.makeText(VideoActivity.this,"No Video to save",Toast.LENGTH_LONG).show();
}
}
});
//capture video button click is handled here.
captureVideo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
if (takeVideoIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takeVideoIntent, REQUEST_VIDEO_CAPTURE);
}
}
});
}
//onActivityResult is shown here.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (requestCode == REQUEST_VIDEO_CAPTURE && resultCode == RESULT_OK) {
videoUri = intent.getData();
videoView.setVideoURI(videoUri);
videoView.start();
}
}
//this is to convert the videoUri to byte[] arrays.
public static byte[] convertVideoToBytes( Uri videoUri) {
byte[] videoBytes = null;
File inputFile=new File(videoUri.getPath());
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
FileInputStream fis = new FileInputStream(inputFile);
byte[] buf = new byte[(int)inputFile.length()];
int n;
while (-1 != (n = fis.read(buf)))
baos.write(buf, 0, n);
videoBytes = baos.toByteArray();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return videoBytes;
}
}
here is my code..sorry for posting it as an answer but i didnt know how to post the code.
public class ViewActivity extends AppCompatActivity {
VideoView finalView;
Button button_play;
ParseUser currentUser;
String videoString;
Uri videoUri,contentUri, fileProvider;
File videoFile;
public final String APP_TAG = "MyCustomApp";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view);
finalView=(VideoView) findViewById(R.id.finalview);
button_play=(Button) findViewById(R.id.button_play);
// Create a File reference for future access
videoFile = getVideoFileUri();
fileProvider = FileProvider.getUriForFile(ViewActivity.this,
"com.codepath.fileprovider", videoFile);
currentUser= ParseUser.getCurrentUser();
ParseFile parseFile = (ParseFile)currentUser.get("videos");
parseFile.getDataInBackground(new GetDataCallback() {
#Override
public void done(byte[] data, ParseException e) {
try {
videoUri=convertBytesToUri(data,fileProvider);
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
button_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finalView.setVideoURI(videoUri);
finalView.start();
}
});
}
public Uri convertBytesToUri(byte[] data,Uri fileProvider) throws IOException {
OutputStream os=getContentResolver().openOutputStream(fileProvider);
os.write(data);
os.flush();
return fileProvider;
}
// Returns the File for a photo stored on disk given the fileName
public File getVideoFileUri() {
// Get safe storage directory for photos
// Use `getExternalFilesDir` on Context to access package-specific directories.
// This way, we don't need to request external read/write runtime permissions.
File mediaStorageDir = new File(getExternalFilesDir(Environment.DIRECTORY_MOVIES),
APP_TAG);
//Let's create a unique fileName.
String timeStamp=new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String fileName=timeStamp+".mp4";
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists() && !mediaStorageDir.mkdirs()){
Log.d(APP_TAG, "failed to create directory");
}
// Return the file target for the photo based on filename
File file = new File(mediaStorageDir.getPath() + File.separator + fileName);
return file;
}
How to Save Image in Internal Storage and show image in imageView in another acitivity ,please tell me how to save that image in internal storage because many phones have only internal storage not sd card
this is my first acitivity
//camera
camera = (ImageView) findViewById(R.id.takePic);
camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File pictureDirectory=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String pictureName=getPictureName();
File imageFile=new File(pictureDirectory,pictureName);
pictureUri=Uri.fromFile(imageFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT,pictureUri);
startActivityForResult(intent,CAMERA_REQUEST_CODE);
}
});
private String getPictureName() {
SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd_HHmmss");
String timestamp=sdf.format(new Date());
return "Plane place image"+timestamp+".jpg";
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==RESULT_OK){
if (resultCode==CAMERA_REQUEST_CODE)
{
pictureUri = data.getData();
if (pictureUri!=null) {
Intent intent = new Intent(this, PictureActivity.class);
intent.setData(pictureUri);
intent.putExtra("imgUrl", pictureUri.toString());
startActivity(intent);
}
}
}
}
this is my second activity
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
Log.e("ashish", bundle.getString("imgUrl") + "");
path = Uri.parse(bundle.getString("imgUrl"));
}
ImageView selfiiii = (ImageView) findViewById(R.id.mySelfie);
selfiiii.setImageURI(path);
i am store image in emulator internal storage used below code...
private String saveToInternalStorage(Bitmap bitmapImage){
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to /data/data/yourapp/app_data/imageDir
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
// Create imageDir
File mypath=new File(directory,"profile.jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
// Use the compress method on the BitMap object to write image to the OutputStream
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return directory.getAbsolutePath();
}
make changes in opencamera method like used below code...
private void OpenCamera(){
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Bitmap thumbnail = null;
if (resultCode==RESULT_OK){
if (requestCode==CAMERA_REQUEST_CODE)
{
thumbnail = (Bitmap) data.getExtras().get("data");
Intent intent = new Intent(this, DbInsert.class);
intent.putExtra("name", thumbnail);
startActivity(intent);
}
}
}
second Activity...
Bitmap bitmap = getIntent().getExtras().getParcelable("name");
imageView.setImageBitmap(bitmap);
The main theme of my app is, user has to select images from his device gallery, and those selected images are turned into a GIF. I'm converting those selected images into bitmap and I am using this GIFEncoder.java file to converted selected images into a GIF, and I have achieved it. when I check it in my folder, GIF was created but when I open the GIF is was not animating just a black screen was appeared.
Here is my MainActivity looks like:
public class MainActivity extends AppCompatActivity {
private static final int SELECT_PHOTO = 102;
private FileOutputStream outStream;
ArrayList<Bitmap> bitmaps = new ArrayList<>();
private Button generateImageGIF, selectImages;
String BASE_PATH = Environment.getExternalStorageDirectory().toString() + File.separator + "ImagesToGif";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
File mydir = new File(BASE_PATH);
if (!mydir.exists()) {
mydir.mkdirs();
}
generateImageGIF = (Button) findViewById(R.id.generate_image_gif);
selectImages = (Button) findViewById(R.id.select_images);
selectImages.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
}
});
generateImageGIF.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
Toast.makeText(getApplicationContext(), "gif creation started", Toast.LENGTH_LONG).show();
outStream = new FileOutputStream(BASE_PATH + File.separator + getString(R.string.app_name) + ".gif");
outStream.write(generateGIF());
outStream.close();
Toast.makeText(getApplicationContext(), "gif creation ended", Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SELECT_PHOTO && resultCode == RESULT_OK && data != null) {
Bitmap bitmap1 = BitmapFactory.decodeFile(String.valueOf(data.getData()));
bitmaps.add(bitmap1);
}
}
public byte[] generateGIF() {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
AnimatedGifEncoder encoder = new AnimatedGifEncoder();
encoder.start(bos);
for (Bitmap bitmap : bitmaps) {
encoder.addFrame(bitmap);
}
encoder.finish();
return bos.toByteArray();
}
}
In my app, i can take a picture and save in gallery(folder 'camera').But i need save it in a specific folder in external memory.This is my code.How i can do it?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.get_pic);
init();
getPic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 0);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
Bundle ex = data.getExtras();
bitmap = (Bitmap) ex.get("data");
myPic.setImageBitmap(bitmap);
}
}
This should do it:
private void createDirectoryAndSaveFile(Bitmap imgSave, String fileName) {
File direct = new File(Environment.getExternalStorageDirectory() + "/DirName");
if (!direct.exists()) {
File imageDirectory = new File("/sdcard/DirName/");
imageDirectory.mkdirs();
}
File file = new File(new File("/sdcard/DirName/"), fileName);
if (file.exists()) {
file.delete();
}
try {
FileOutputStream out = new FileOutputStream(file);
imgSave.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
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);
}