Can Async Task write in internal storage android? - file

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) {
}
}
}
}

Related

Codenameone closing a socket

There seems to be no way of disconnecting a socket without causing a connection reset error on the server side.
I'm using the com.codename1.io.Socket and com.codename1.io.SocketConnection implementations within a tester app. My code is as follows:
private SpanLabel lblStatus;
private SpanLabel lblIncoming;
private CustomSocketConnection con;
private Thread tIncoming;
public ConnectForm() {
con = getSocketConnection();
Button btnConnect = getConnectButton();
Button btnDisconnect = getDisconnectButton();
Button btnSendMessage = getSendMessageButton();
lblStatus = getInfoLabel();
lblIncoming = getIncomingLabel();
setLayout(new BoxLayout(BoxLayout.Y_AXIS));
addComponent(btnConnect);
addComponent(btnDisconnect);
addComponent(btnSendMessage);
addComponent(lblStatus);
addComponent(lblIncoming);
}
private Button getConnectButton() {
Button btn = new Button("Connect (localhost)");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
Socket.connect("localhost", 8687, con);
}
});
return btn;
}
private Button getDisconnectButton() {
Button btn = new Button("Disconnect");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
//??? I don't know how to do this
try {
tIncoming.join();
} catch (Exception e) {
e.printStackTrace();
tIncoming.interrupt();
}
}
});
return btn;
}
private Button getSendMessageButton() {
Button btn = new Button("Send Message");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
try {
con.os.write("Hello".getBytes());
con.os.write(Integer.parseInt("04", 16)); //end of transmit
con.os.flush();
lblStatus.setText("Message Sent");
} catch (Exception e) {
e.printStackTrace();
}
}
});
return btn;
}
private SpanLabel getInfoLabel() {
return new SpanLabel("Disconnected");
}
private SpanLabel getIncomingLabel() {
return new SpanLabel("...");
}
private CustomSocketConnection getSocketConnection() {
return new CustomSocketConnection();
}
class CustomSocketConnection extends SocketConnection {
public OutputStream os;
public InputStream is;
#Override
public void connectionError(int errorCode, String message) {
lblStatus.setText("Error Connecting. ErrorCode: " + errorCode + " Message: " + message);
}
#Override
public void connectionEstablished(InputStream is, OutputStream os) {
lblStatus.setText("Connected :)");
this.is = is;
this.os = os;
spawnIncomingMessageWatcher();
}
}
private void spawnIncomingMessageWatcher() {
tIncoming = new Thread(new Runnable() {
public void run() {
String s = "";
int eot = Integer.parseInt("04", 16);
while (con.isConnected()) {
try {
int temp;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while (((temp = con.is.read()) != -1) && (temp != eot)) {
baos.write(temp);
}
lblIncoming.setText(new String(baos.toByteArray()));
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
tIncoming.start();
}
With the getDisconnectButton() method, I do not know how to properly disconnect from the server, as the SocketConnection object does not seem to have an appropriate method for this.
If you call close() on either the Input- or OutputStream then you close the Socket, code from Socket.SocketInputStream class link.
public void close() throws IOException {
closed = true;
if(Util.getImplementation().isSocketConnected(impl)) {
Util.getImplementation().disconnectSocket(impl);
con.setConnected(false);
}
}
So first send close instruction to Server and then close a stream.
Hope this helps,

Show toast if mp3 file there was not in SD card

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.

java.io.IOException: closed error in a non-stop loop inside an asynctask

I try to create an asynctask that runs permanently (all the time my app is running). Thay task read every second a file on a server (status.xml).
My problem is that when I execute the app, I have an java.io.IOException: closed exception the second time I do :
reader.read(buffer); // HERE I HAVE AN IOException closed
(first loop is ok, then I have error each loop)
Thanks if someone can help me. I undesrtand the reason of the error, but I cannot find a solution...
Here is my code :
class StatusnAsync extends AsyncTask<Void, Void, Void> {
InputStream in = null;
int responseCode;
void Sleep(int ms) {
try {
Thread.sleep(ms);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onPreExecute() {
// inits for doInBackground thread
try {
URL url = new URL(address + "/status.xml");
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(5000 /* milliseconds */);
conn.setConnectTimeout(80000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected Void doInBackground(Void... arg0) {
while (not_end) {
try {
readStatus();
// Sleep 1 sec
Sleep(1000);
} catch (IOException e) {
e.printStackTrace ();
}
}
return null;
}
private void readStatus() throws IOException {
try {
conn.connect();
responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
in = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = readIt(in, 340);
// close the inputstream
in.close();
}
} catch (IOException e) {
e.printStackTrace ();
} finally {
if (in != null) in.close();
}
}
// Reads an InputStream and converts it to a String.
public String readIt(InputStream stream, int len) throws IOException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer); // HERE I HAVE AN IOException closed
return new String(buffer);
}
}
Thank you.
Sorry for my question, I found my error, a stupid error.
Of course I need to openConnection for each GET.
I give the corrected code if it can help someone :
class StatusnAsync extends AsyncTask<Void, Void, Void> {
InputStream in = null;
int responseCode;
URL url;
void Sleep(int ms) {
try {
Thread.sleep(ms);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onPreExecute() {
// inits for doInBackground thread
try {
url = new URL(address + "/file.xml");
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
#Override
protected Void doInBackground(Void... arg0) {
while (not_end) {
try {
readStatus();
// Sleep 1 sec
Sleep(1000);
} catch (IOException e) {
e.printStackTrace ();
}
}
return null;
}
private void readStatus() throws IOException {
try {
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(5000 /* milliseconds */);
conn.setConnectTimeout(80000 /* milliseconds */);
conn.connect();
responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
in = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = readIt(in, 340);
// close the inputstream
in.close();
}
} catch (IOException e) {
e.printStackTrace ();
} finally {
if (in != null) in.close();
}
}
// Reads an InputStream and converts it to a String.
public String readIt(InputStream stream, int len) throws IOException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
}
}

MediaRecorder-recording video using mediarecorder

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

data/data/com.package/databases folder isn't showed

I made an android dictionary application. I have created a database named "kamusJawa.sqlite" and copied it to the assets folder. I tried the code in this link Own Database in Assets Folder on Android Eclipse Project
This is my database manager class:
package com.kamusJI;
public class DBHelper extends SQLiteOpenHelper{
private static String DBPATH = "/data/data/com.kamusJI/databases/";
private static String DBNAME = "kamusJawa.sqlite";
private SQLiteDatabase DBSQ;
private final Context KJICtx;
public DBHelper(Context context) throws IOException {
super(context, DBNAME, null, 1);
this.KJICtx = context;
// TODO Auto-generated constructor stub
boolean dbexist = cekDB();
if (dbexist) {
//System.out.println("Database exists");
openDB();
} else {
System.out.println("Database doesn't exist");
createDB();
}
}
public void createDB() throws IOException{
boolean dbExist = cekDB();
if(!dbExist){
this.getReadableDatabase();
try{
salinDB();
}catch (IOException e){
throw new Error("Gagal menyalin database");
}
}
}
boolean cekDB() {
//SQLiteDatabase cekDatabase = null;
boolean cekdb = false;
try{
String path = DBPATH + DBNAME;
File dbfile = new File(path);
//cekDatabase = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);
cekdb = dbfile.exists();
}catch(SQLException e){
System.out.println("Database tidak ada");
}
return cekdb;
//return cekDatabase !=null ? true : false;
}
private void salinDB() throws IOException{
AssetManager AM = KJICtx.getAssets();
File DbFile = new File(DBPATH+DBNAME);
InputStream in = KJICtx.getAssets().open(DBNAME);
//OutputStream out = new FileOutputStream(DbFile);
OutputStream out = new FileOutputStream("/data/data/com.kamusJI/databases/kamusJawa.sqlite");
DbFile.createNewFile();
byte[] b = new byte[1024];
int i, r;
String[] Files = AM.list("");
Arrays.sort(Files);
i= 1;
String fdb = String.format("kamusJawa.db.00%d", i);
while(Arrays.binarySearch(Files, fdb)>=0){
//InputStream in = AM.open(fdb);
while(( r = in.read(b))>0)
out.write(b,0,r);
in.close();
i++;
fdb = String.format("kamusJawa.db.00%d", i);
}
out.flush();
out.close();
}
public void openDB() throws SQLException{
String path = DBPATH+DBNAME;
DBSQ = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);
}
public synchronized void close(){
if(DBSQ !=null)
DBSQ.close();
super.close();
}
#Override
public void onCreate(SQLiteDatabase arg0) {
// TODO Auto-generated method stub
}
#Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
}
}
and this is my main class:
package com.kamusJI;
public class KJI extends ListActivity {
private KJI this_class = this;
String[] Menu = {"Basa Jawa", "Bahasa Indonesia", "Tambah Data"};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setListAdapter(new ArrayAdapter<String>(this, R.layout.row, R.id.Cari, Menu));
ListView lv = getListView();
lv.setTextFilterEnabled(false);
/* Defines On Item Click callback method */
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Intent action = null;
switch(position) {
case 0:
case 1:
action = new Intent(getApplicationContext(), Cari.class);
action.putExtra("MODE", position);
break;
case 2:
action = new Intent(getApplicationContext(), Tambah.class);
action.putExtra("MODE", position);
break;
case 3:
finish();
return;
}
startActivity(action);
Toast.makeText(getApplicationContext(), ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});
}
public void InitDatabase() {
AsyncTask<String, Void, String> InitDB = new AsyncTask<String, Void, String>() {
Dialog progress = null;
String msg;
DBHelper dbhelper;
#Override
protected void onPreExecute() {
try {
dbhelper = new DBHelper(this_class);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (!dbhelper.cekDB())
progress = ProgressDialog.show(this_class, "", "Installing Database.\nPlease wait.");
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
dbhelper.createDB();
msg = "Database successfully installed.";
} catch (IOException ioe) {
msg = "Database installation failed.";
}
return msg;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (progress!=null) {
progress.dismiss();
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show();
}
}
};
InitDB.execute(new String());
}
}
When I run my application, then I go to file explorer, I can't find the data/data/com.kamusJI/databases. How it can be like that?
change your database name extension to .db
You need special permissions like root access to read the path:
/data/data/com.package/databases

Resources