iam using mediarecorder to record video in android application. I will start and stop recording video multiple times i will start recording on Action_down and stop on Action_up this is going on well and iam able to store and play video file in mobile .
my problem is that since i have to start and stop recording video multiple times i can't use single output file becuase everytime it will get over written so everytime iam passing new file name and iam appending that to one outputfile everytime.iam getting every individual file and final outputfile in mobile but final file is having only what i have recorded for the first time because from second tab if see the file.mp4.length()is zero why it is ? anyone please try to help me. my code is as follows
package com.example.longtouch;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.net.rtp.AudioGroup;
import android.net.rtp.AudioStream;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Handler.Callback;
import android.provider.MediaStore.Audio;
import android.provider.MediaStore.Files;
import android.provider.MediaStore.Video;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;
import android.support.v4.app.NavUtils;
public class MainActivity extends Activity implements OnTouchListener{
int i=1;
File outputFile;
File f1;
File f2;
MediaRecorder mediaRecorder;
ThreadProgress mThreadProgress;
ThreadProgress2 mThreadProgress2;
public int eventAction;
Handler handler;
Handler mHandler;
Button myButton;
FrameLayout myCameraPreview;
Button submit;
Button submit1;
LinearLayout ll;
ProgressBar progressBar;
int progressStatus=0;
MyCameraSurfaceView myCameraSurfaceView;
Camera myCamera;
boolean recording;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recording=false;
myButton=(Button)findViewById(R.id.button_capture);
submit=(Button)findViewById(R.id.submit);
submit1=(Button)findViewById(R.id.submit1);
progressBar=(ProgressBar)findViewById(R.id.progress_bar);
progressBar.setMax(10000);
myCamera = getCameraInstance();
if(myCamera == null){
Toast.makeText(MainActivity.this,
"Fail to get Camera",
Toast.LENGTH_LONG).show();
}
// else
// myCamera.unlock();
myCameraSurfaceView = new MyCameraSurfaceView(this, myCamera);
myCameraPreview=(FrameLayout)findViewById(R.id.camera_preview);
myCameraPreview.addView(myCameraSurfaceView);
ll=(LinearLayout)findViewById(R.id.ll);
myCameraPreview.setOnTouchListener(this);
outputFile=new File("/sdcard/myvideo.mp4");
if(outputFile.exists()){
outputFile.delete();
outputFile=new File("/sdcard/myvideo.mp4");
try {
outputFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else{
try {
outputFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
f1=new File("/sdcard/myvideo1.mp4");
if(f1.exists()){
f1.delete();
f1=new File("/sdcard/myvideo1.mp4");
try{
f1.createNewFile();
}
catch(Exception e){
e.printStackTrace();
}
}
else{
try{
f1.createNewFile();
}
catch(Exception e){
e.printStackTrace();
}
}
f2=new File("/sdcard/myvideo2.mp4");
if(f2.exists()){
f2.delete();
f2=new File("/sdcard/myvideo2.mp4");
try{
f2.createNewFile();
}
catch(Exception e){
e.printStackTrace();
}
}
else{
try{
f2.createNewFile();
}
catch(Exception e){
e.printStackTrace();
}
}
}
/* public int getFrontCameraId() {
CameraInfo ci = new CameraInfo();
for (int i = 0 ; i < Camera.getNumberOfCameras(); i++) {
Camera.getCameraInfo(i, ci);
if (ci.facing == CameraInfo.CAMERA_FACING_FRONT) return i;
}
return -1; // No front-facing camera found
}*/
private Camera getCameraInstance(){
// TODO Auto-generated method stub
Camera c = null;
try {
/* int index = getFrontCameraId();
if (index != -1)
c = Camera.open(index);*/
c = Camera.open(); // attempt to get a Camera instance
}
catch (Exception e){
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
}
public void submit(View v){
// stop recording and release camera
// mediaRecorder.stop(); // stop the recording
// releaseMediaRecorder(); // release the MediaRecorder object
Log.d("outputFile",""+f1.length());
progressStatus=progressBar.getProgress();
//Exit after saved
// finish();
myButton.setText("capture");
recording=false;
submit.setVisibility(View.GONE);
}
public void submit1(View v){
// stop recording and release camera
// mediaRecorder.stop(); // stop the recording
// releaseMediaRecorder(); // release the MediaRecorder object
progressBar.setProgress(0);
progressStatus=0;
//Exit after saved
// finish();
myButton.setText("capture");
recording=false;
submit1.setVisibility(View.GONE);
}
public void display(View v){
Intent i=new Intent(this,VideoPlayer.class);
startActivity(i);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public boolean onTouch(View arg0, final MotionEvent event) {
// TODO Auto-generated method stub
eventAction=event.getAction();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
{
i=i+1;
Toast.makeText(getApplicationContext(),"action_down",Toast.LENGTH_SHORT).show();
//releaseCamera();
if(!prepareMediaRecorder()){
Toast.makeText(MainActivity.this,
"Fail in prepareMediaRecorder()!\n - Ended -",Toast.LENGTH_LONG).show();
finish();
}
progressBar.setProgress(progressStatus);
myButton.setText("STOP");
try{
mediaRecorder.start();
}
catch(Exception e){
e.printStackTrace();
Log.d("vd","exception at start method");
}
if(f1.exists()){
long l=f1.length();
Log.d("start","started"+l);
}
if(f2.exists()){
long m=f2.length();
Log.d("start","started"+m);
}
recording = true;
if(progressBar.getProgress()>=5000){
mThreadProgress2=new ThreadProgress2();
mThreadProgress2.start();
}
mHandler = new Handler(new Callback() {
public boolean handleMessage(final Message msg) {
runOnUiThread(new Runnable() {
public void run() {
if( event.getAction()!=MotionEvent.ACTION_UP){
progressBar.setProgress(msg.arg1);
}
if(progressBar.getProgress()==10000){
Log.d("unicorn","1000");
submit1.setVisibility(View.VISIBLE);
}
}
});
return false;
}
});
mThreadProgress=new ThreadProgress();
mThreadProgress.start();
handler = new Handler(new Callback() {
public boolean handleMessage(final Message msg) {
runOnUiThread(new Runnable() {
public void run() {
if( event.getAction()!=MotionEvent.ACTION_UP)
progressBar.setProgress(msg.arg1);
if(progressBar.getProgress()==5000){
submit.setVisibility(View.VISIBLE);
}
}
});
return false;
}
});
return true;
}
case MotionEvent.ACTION_UP:
{ // nothing to do
Toast.makeText(getApplicationContext(),"action_up",Toast.LENGTH_SHORT).show();
myButton.setText("capture");
mediaRecorder.stop(); // stop the recording
releaseMediaRecorder(); // release the MediaRecorder object
try {
myCamera.reconnect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Exit after saved
// finish();
recording=false;
progressStatus=progressBar.getProgress();
if(i%2==0){
long len=f1.length();
Log.d("length",""+f1.getPath()+len);
Combine1 c1=new Combine1();
c1.start();
}
else{
long len=f2.length();
Log.d("length",""+f2.getPath()+len);
Combine2 c2=new Combine2();
c2.start();
}
break;
}
default:
return false;
}
return true;
}
private boolean prepareMediaRecorder(){
// myCamera = getCameraInstance();
mediaRecorder = new MediaRecorder();
myCamera.stopPreview();
myCamera.unlock();
mediaRecorder.setCamera(myCamera);
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
// mediaRecorder.setVideoSize(400,400);
if(i%2==0){
Log.d("outputfile",""+f1.getPath()+f1.length());
mediaRecorder.setOutputFile(f1.getPath());
Log.d("outputfile",""+f1.getPath()+f1.length());
}
else{
Log.d("outputfile",""+f2.getPath()+f2.length());
mediaRecorder.setOutputFile(f2.getPath());
Log.d("outputfile",""+f2.getPath()+f2.length());
}
mediaRecorder.setMaxDuration(10000); // Set max duration 10 sec.
mediaRecorder.setMaxFileSize(5000000); // Set max file size 5M
// mediaRecorder.setOnInfoListener(this);
mediaRecorder.setPreviewDisplay(myCameraSurfaceView.getHolder().getSurface());
try {
mediaRecorder.prepare();
} catch (IllegalStateException e) {
Log.d("prepare","illegalstateexception");
e.printStackTrace();
releaseMediaRecorder();
Toast.makeText(getApplicationContext(),"illegal state exception",Toast.LENGTH_SHORT).show();
return false;
} catch (IOException e) {
Log.d("prepare","ioexception");
e.printStackTrace();
releaseMediaRecorder();
Toast.makeText(getApplicationContext(),"IOexception",Toast.LENGTH_SHORT).show();
return false;
}
Log.d("after prepare","after prepare f1"+f1.length());
Log.d("after prepare","after prepare f2"+f2.length());
return true;
}
public void combine(String file){
Log.d("combine","combining"+file);
try{
File inputFile=new File(file);
FileInputStream fis=new FileInputStream(inputFile);
long inputlen=inputFile.length();
Log.d("combine","lengthbefore write"+inputlen);
File outputFile = new File("/sdcard/myvideo.mp4");
FileOutputStream fos = new FileOutputStream(outputFile,true);
byte fileContent[]= new byte[(int)inputFile.length()];
fis.read(fileContent);
long len=outputFile.length();
Log.d("combine","lenth"+len);
fos.write(fileContent);
fis.close();
fos.close();
inputlen=inputFile.length();
len=outputFile.length();
Log.d("combine","inputlength"+inputlen);
Log.d("combine","lenth"+len);
/* File f= new File(file);
boolean deleted = f.delete();
if(deleted){
Log.d("combine","deleted"+file);
} */
}
catch(Exception e){
e.printStackTrace();
}
}
#Override
protected void onPause() {
super.onPause();
releaseMediaRecorder(); // if you are using MediaRecorder, release it first
releaseCamera(); // release the camera immediately on pause event
}
private void releaseMediaRecorder(){
if (mediaRecorder != null) {
mediaRecorder.reset(); // clear recorder configuration
mediaRecorder.release(); // release the recorder object
mediaRecorder = null;
// myCamera.lock(); // lock camera for later use
}
}
private void releaseCamera(){
if (myCamera != null){
myCamera.release(); // release the camera for other applications
myCamera = null;
}
}
public class MyCameraSurfaceView extends SurfaceView implements SurfaceHolder.Callback{
private SurfaceHolder mHolder;
private Camera mCamera;
public MyCameraSurfaceView(Context context, Camera camera) {
super(context);
mCamera = camera;
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
mHolder = getHolder();
mHolder.addCallback(this);
// deprecated setting, but required on Android versions prior to 3.0
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceChanged(SurfaceHolder holder, int format, int weight,
int height) {
// If your preview can change or rotate, take care of those events here.
// Make sure to stop the preview before resizing or reformatting it.
if (mHolder.getSurface() == null){
// preview surface does not exist
return;
}
// stop preview before making changes
try {
mCamera.stopPreview();
} catch (Exception e){
// ignore: tried to stop a non-existent preview
}
// make any resize, rotate or reformatting changes here
// start preview with new settings
try {
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (Exception e){
}
}
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
// The Surface has been created, now tell the camera where to draw the preview.
try {
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
} catch (IOException e) {
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
}
public class ThreadProgress extends Thread implements Runnable {
int progressValue=progressStatus;
public void run() {
while( progressBar.getProgress()<5000 && eventAction!=MotionEvent.ACTION_UP ) {
Log.d("unicorn","in while loop"+progressValue);
progressValue++;
Message message = new Message();
message.arg1 = progressValue;
if(progressValue<=5000 && eventAction!=MotionEvent.ACTION_UP)
handler.sendMessage(message);
}
}
}
public class ThreadProgress2 extends Thread implements Runnable {
int progressValue=progressStatus;
#Override
public void run() {
while( progressBar.getProgress()<10000 && eventAction!=MotionEvent.ACTION_UP ) {
// try{
Log.d("unicorn2","in while loop"+progressValue);
progressValue++;
Message message = new Message();
message.arg1 = progressValue;
if(progressValue<=10000 && eventAction!=MotionEvent.ACTION_UP)
mHandler.sendMessage(message);
//Thread.sleep(1000);
//} catch (InterruptedException e){
// e.printStackTrace();
// break;
// }
}
}
}
public class Combine1 extends Thread implements Runnable{
public void run(){
try{
int c;
FileInputStream fin=new FileInputStream(f1);
FileOutputStream fout=new FileOutputStream(outputFile,true);
long len1=f1.length();
Log.d("length","myvideo1.mp4"+len1);
long len2=outputFile.length();
Log.d("length","myvideo.mp4"+len2);
while((c=fin.read())!=-1){
fout.write(c);
}
len2=outputFile.length();
Log.d("length","myvideo.mp4"+len2);
fin.close();
fout.flush();
fout.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
public class Combine2 extends Thread implements Runnable{
public void run(){
try{
int j=0;
FileInputStream fin=new FileInputStream(f2);
FileOutputStream fout=new FileOutputStream(outputFile,true);
long len1=f2.length();
Log.d("length","myvideo2.mp4"+len1);
long len2=outputFile.length();
Log.d("length","myvideo.mp4"+len2);
while((j=fin.read())!=-1){
fout.write(j);
}
len2=outputFile.length();
Log.d("length","myvideo.mp4"+len2);
fin.close();
fout.flush();
fout.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
}
In order to combine multiple video files you should use mp4parser library : https://mp4parser.googlecode.com/svn/trunk/examples/src/main/java/com/googlecode/mp4parser/AppendExample.java
Related
Hi i need to download a file from url and save in internal storage,so the download process run in async task.
First, I have tried to write a string in a file with async task but give me error: Failed to create oat file.
The same code work without task, so my question is i must download the file in external storage and after move in internal?
private void writeInFile() {
FileOutputStream output = null;
String text = "TEXT";
try {
output = openFileOutput("nameFile.abc",Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
output.write(text.getBytes());
output.flush();
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
But if i call this function in doInBackground of class that extend AsyncTask i receive the error.
LicenzaTask mt = new LicenzaTask(this);
mt.execute();
public class LicenzaTask extends AsyncTask<Void, Void, Void> {
private Context mContext;
public LicenzaTask(MainActivity mainActivity) {
mContext = mainActivity;
}
#Override
protected Void doInBackground(Void... voids) {
modifyFile();
return null;
}
private void modifyFile() {
File file = new File(mContext.getFilesDir() + "nome.abc");
String text = "text";
BufferedWriter output = null;
try {
output = new BufferedWriter(new FileWriter(file));
output.write(text);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
}
}
}
}
package com.email.test;
import java.util.Arrays;
import java.util.Properties;
import javax.mail.BodyPart;
import javax.mail.Flags;
import javax.mail.Flags.Flag;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.search.FlagTerm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class SampleEmailReader {
public static final int SUCCESS = 0;
public static final int FAILURE = -1;
private transient static final Logger logger = LoggerFactory.getLogger(SampleEmailReader.class);
public SampleEmailReader() {
}
public void processEmailAttachements() {
try {
logger.info("Started processEmailAttachements ");
Properties emailProperties = new Properties();
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
emailProperties.setProperty("mail.imaps.socketFactory.class", SSL_FACTORY);
emailProperties.setProperty("mail.imaps.socketFactory.fallback", "false");
emailProperties.setProperty("mail.imaps.port", "993");
emailProperties.setProperty("mail.imaps.socketFactory.port", "993");
emailProperties.setProperty("mail.imaps.auth", "true");
emailProperties.setProperty("mail.imaps.host", "outlook.office365.com");
emailProperties.setProperty("mail.imaps.auth.plain.disable", "true");
emailProperties.setProperty("mail.imaps.auth.gssapi.disable", "true");
emailProperties.setProperty("mail.imaps.auth.ntlm.disable", "true");
emailProperties.setProperty("mail.imaps.ssl.enable", "true");
Session session = Session.getInstance(emailProperties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("test#outlook.com", "password#2016");
}
});
Store store = session.getStore("imaps");
store.connect();
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_WRITE);
logger.info("Inbox MessageCount-->" + inbox.getMessageCount());
Message messages[] = inbox.search(new FlagTerm(
new Flags(Flag.SEEN), false));
logger.info("Number of UnRead Mails = " + messages.length);
for (Message inboxMessage : messages) {
int status = processMessageBody(inboxMessage);
if (status == SUCCESS) {
inboxMessage.setFlag(Flag.SEEN, true);
} else {
inboxMessage.setFlag(Flag.SEEN, false);
}
}
inbox.close(true);
store.close();
} catch (Exception ex) {
ex.printStackTrace();
logger.error("Error in processEmailAttachements", ex);
}
}
private int processMessageBody(Message message) {
int status = FAILURE;
try {
logger.info("Started processMessageBody*******");
logger.info("Message Subject******" + message.getSubject());
logger.info("From Address *******"
+ Arrays.toString(message.getFrom()));
Object content = message.getContent();
if (content instanceof String) {
logger.error("Invalid Content Type.No need to process the Mail with Subject "
+ message.getSubject());
} else if (content instanceof Multipart) {
Multipart multiPart = (Multipart) content;
try {
for (int i = 0; i < multiPart.getCount(); i++) {
BodyPart bodyPart = multiPart.getBodyPart(i);
if (bodyPart.getDisposition() != null
&& bodyPart.getDisposition().equalsIgnoreCase(
Part.ATTACHMENT)
&& bodyPart.getFileName() != null) {
status = readExcel(bodyPart);
}
}
} catch (Exception e) {
e.printStackTrace();
logger.error("BatchException in procesMultiPart", e);
}
}
} catch (Exception e) {
e.printStackTrace();
logger.error("Exception in processMessageBody", e);
}
return status;
}
public abstract int readExcel(BodyPart bodyPart);
}
Executing
package EmailTable;
import javax.mail.BodyPart;
public class Email {
public static void main(String[] args) {
// TODO Auto-generated method stub
SampleEmailReader reader = new SampleEmailReader() {
#Override
public int readExcel(BodyPart bodyPart) {
// TODO Auto-generated method stub
return 0;
}
};
reader.processEmailAttachements();
}
}
Getting Autheticate Failed.. But username password is correct. and i am able to login outlook 365 with the username and password. ONLY difference I am seeing there is certitificate displayed on the browser.. Do I need to use any certificate to read the mail?
javax.mail.AuthenticationFailedException: LOGIN failed.
at com.sun.mail.imap.IMAPStore.protocolConnect
I am at the point of abandoning using codenameone to build an app that allows me to play video from storage or to capture and play. Its either it is playing but no video is showing (most common ) or it plays only once and thats it - the fast forward and rewind buttons not working. I don't know if this is a simulator problem/limitation or whether I just don't know what I am doing.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.ixzdore.ziem.renderer.widgets;
import com.codename1.capture.Capture;
import com.codename1.components.ImageViewer;
import com.codename1.components.MediaPlayer;
import com.codename1.io.FileSystemStorage;
import com.codename1.io.Log;
import static com.codename1.io.Log.e;
import com.codename1.media.Media;
import com.codename1.media.MediaManager;
import com.codename1.ui.Container;
import com.codename1.ui.Display;
import com.codename1.ui.Image;
import com.codename1.ui.Label;
import com.codename1.ui.events.ActionEvent;
import com.codename1.ui.events.ActionListener;
import com.codename1.ui.geom.Dimension;
import com.codename1.ui.layouts.BorderLayout;
import com.ixzdore.ziem.models.DocumentElement;
import com.ixzdore.ziem.models.ReportDocument;
import java.io.IOException;
/**
*
* #author jamesagada
*/
public class NVideo extends Widget {
private final Label _imageLabel = new Label();
private MediaPlayer _mPlayer;
private Container imageVideoContainer;
public NVideo(DocumentElement element, ReportDocument doc, Boolean isEditing) {
super(element, doc, isEditing);
imageVideoContainer = new Container(new BorderLayout(BorderLayout.CENTER_BEHAVIOR_SCALE)) {
protected Dimension calcPreferredSize() {
return new Dimension(Display.getInstance().getDisplayWidth(), Display.getInstance().getDisplayWidth());
}
};
_mPlayer = new MediaPlayer();
setupWidgetFromProperty();
}
#Override
public void renderEdit() {
//super.initLayout();
super.setEnabled(true);
}
public void renderSummary() {
//super.initLayout();
super.setEnabled(false);
getIconContainer().remove();
revalidate();
}
#Override
public void renderView() {
//find the
//super.initLayout();
super.setEnabled(false);
getIconContainer().remove();
revalidate();
}
#Override
public void setupWidgetFromProperty() {
super.setupWidgetFromProperty();
String videoFile = documentElement.getVideoFileFromValue(documentElement.getPropertyValue());
if (videoFile != null) {
try {
Media video = MediaManager.createMedia(videoFile, true);
if (_mPlayer == null) {
_mPlayer = new MediaPlayer();
}
_mPlayer.setDataSource(videoFile);
_mPlayer.setAutoplay(true);
if (imageVideoContainer == null) {
imageVideoContainer = new Container(new BorderLayout(BorderLayout.CENTER_BEHAVIOR_SCALE)) {
protected Dimension calcPreferredSize() {
return new Dimension(Display.getInstance().getDisplayWidth(), Display.getInstance().getDisplayWidth() );
}
};
}
getWidgetContainer().removeAll();
imageVideoContainer.add(BorderLayout.CENTER, _mPlayer);
imageVideoContainer.revalidate();
getWidgetContainer().add(imageVideoContainer);
getWidgetContainer().revalidate();
getWidgetContainer().repaint();
documentElement.setPropertyValue(videoFile);
} catch (Exception err) {
Log.e(err);
}
}
}
#Override
public void setupPropertyButtons() {
super.setupPropertyButtons();
//add a capture button and a browse button for gallery
//save captured picture and put the URL value in the propertyValue
final Widget _this = this;
_captureButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
//open the capture button and take a video
String photoFile = Capture.captureVideo();
if (photoFile != null) {
try {
_mPlayer.setDataSource(photoFile);
_mPlayer.setAutoplay(false);
_mPlayer.revalidate();
_mPlayer.repaint();
imageVideoContainer.revalidate();
_this.revalidate();
documentElement.setPropertyValue(photoFile);
} catch (Exception err) {
Log.e(err);
}
}
}
});
_captureButton.setText("");
getIconContainer().add(_captureButton);
getIconContainer().revalidate();
getIconContainer().repaint();
getLabelContainer().repaint();
_findButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
Display.getInstance().openGallery(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ev) {
if (ev != null && ev.getSource() != null) {
String file = (String) ev.getSource();
try {
_mPlayer.setDataSource(file);
_mPlayer.setAutoplay(false);
_mPlayer.revalidate();
_mPlayer.repaint();
imageVideoContainer.revalidate();
imageVideoContainer.repaint();
_this.revalidate();
documentElement.setPropertyValue(file);
} catch (Exception err) {
Log.e(err);
}
}
}
}, Display.GALLERY_VIDEO);
}
});
_findButton.setText("");
getIconContainer().add(_findButton);
getIconContainer().revalidate();
getIconContainer().repaint();
getLabelContainer().repaint();
this.revalidate();
}
public void render(boolean editing) {
if (isEditing) {
renderEdit();
}
if (!isEditing) {
renderSummary();
}
}
}
`
What am I doing wrong or show me working code sample to achieve what I am trying to achieve.
In this class a mp3 file played from sd card, but if mp3 file not available
app give "force close"
i want cods that show toast if mp3 there was not in SD card(Not download) and back to previous activity.plase help me
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getInit();
seekUpdation();
}
public void getInit() {
seek_bar = (SeekBar) findViewById(R.id.seek_bar);
play_button = (Button) findViewById(R.id.play_button);
pause_button = (Button) findViewById(R.id.pause_button);
text_shown = (TextView) findViewById(R.id.text_shown);
play_button.setOnClickListener(this);
pause_button.setOnClickListener(this);
String filePath = Environment.getExternalStorageDirectory() + "/Android/music.mp3";
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(filePath);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
}
});
mediaPlayer.prepareAsync();
seek_bar.setMax(mediaPlayer.getDuration());
}
Runnable run = new Runnable() {
#Override
public void run() {
seekUpdation();
}
};
public void seekUpdation() {
seek_bar.setProgress(mediaPlayer.getCurrentPosition());
seekHandler.postDelayed(run, 1000);
seek_bar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seek_bar) {
// TODO Auto-generated method stub
}
#Override
public void onStartTrackingTouch(SeekBar seek_bar) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged(SeekBar seek_bar, int progress, boolean fromUser) {
if(fromUser){
mediaPlayer.seekTo(progress);
seek_bar.setProgress(progress);
}
}
});
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.play_button:
text_shown.setText("Playing...");
mediaPlayer.start();
break;
case R.id.pause_button:
mediaPlayer.pause();
text_shown.setText("Paused...");
}
}
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if(fromUser){
mediaPlayer.seekTo(progress);
seekBar.setProgress(progress);
}
}
In IOException catch block place this code:
Toast.makeText(context,'No mp3 file found',Toast.LENGTH_SHORT).show();
this.finish()
finish() will complete current activity and backs to the previous activity.
I am parsing below jsong String and able to parse also and set in listview but while clicking on particular list item it get hang and doesn't fire any error or doesn't perform any action. What will be the possible solution for that?
thanks.
Json String
try {
output= httpObject.OpenHttpConnection(HomesUrl);
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
parseJsonResponse(output);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mEditorialList.setOnItemClickListener( new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v,
int position, long id) {
System.out.println("clicked");
//Intent mEditorialIntent = new Intent(Homes.this, BrowseDetailsPage.class);
//startActivity(mEditorialIntent);
System.out.println("clicked");
}
});
parserClass:
public void parseJsonResponse(String output) throws JSONException {
// TODO Auto-generated method stub
if(output!=null){
try {
mFeaturedArraylist = new JSONArray();
mFeaturedArraylist=new JSONObject(output).getJSONObject("Data").getJSONArray("Featured");
for (int i = 0; i < mFeaturedArraylist.length(); i++) {
JSONObject headObject = mFeaturedArraylist.getJSONObject(i);
mTextViewHead.setText(headObject.optString("Title"));
}
mEditorialArraylist = new JSONArray();
mEditorialArraylist = new JSONObject(output).getJSONObject("Data").getJSONArray("Editorials");
globalAdapter = new EditorialAdapter(Homes.this, mEditorialArraylist);
mEditorialList.setAdapter(globalAdapter);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
EditorialAdapter:
public class EditorialAdapter extends BaseAdapter{
private LayoutInflater mInflater;
JSONArray mEditorial;
public EditorialAdapter(Context context, JSONArray arrList){
mEditorial = arrList;
mInflater = LayoutInflater.from(context);
}
public int getCount() {
// TODO Auto-generated method stub
return mEditorial.length();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class ViewHolder{
TextView twtdata;
ImageView twtimg;
TextView twtnm;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
View vi= convertView;
if(convertView==null){
vi= mInflater.inflate(R.layout.home_listrow, null);
holder = new ViewHolder();
holder.twtdata = (TextView) vi.findViewById(R.id.txtlistby);
holder.twtnm = (TextView) vi.findViewById(R.id.txtlisttitle);
holder.twtimg = (ImageView) vi.findViewById(R.id.avatar);
vi.setTag(holder);
}
else{
holder = (ViewHolder) vi.getTag();
}
try {
JSONObject jObj = mEditorial.optJSONObject(position);
holder.twtnm.setText(jObj.getString("Title"));
holder.twtdata.setText("By "+jObj.getString("AuthorName"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return vi;
}
}