install video in local memory and play in there in android - android

how can I install video from url in local memory and play in there in android? Can you share example code about this? I tried like below but I get error "Sorr,this video cannot played" Video cannot played,but code is installing to video file .I can see it "File Explorer"
public class VideoSaveSDCARD extends Activity {
private VideoView vView;
private static final String TAG = "UpdaterService";
File SDCardRoot;
Handler asyncHandler = new Handler();
String videoLink = "http://hurriyettv.cubecdn.net/2014/11/19/htv_99710_240p.mp4";
String name = "blaa.mp4";
private Updater updater;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
SDCardRoot = new File(getFilesDir() + "/videos");
File[] videos = SDCardRoot.listFiles();
vView = (VideoView) findViewById(R.id.vview);
try {
String[] fileArray = new String[videos.length];
for (int i = 1; i < 2; i++) {
fileArray[i] = videos[i].getName();
Log.i("#Tag:file[1]", "" + fileArray[i]);
vView.requestFocus();
vView.setVideoPath("" + fileArray[i]);
vView.start();
// MediaPlayer pl = new MediaPlayer();
// pl.setDataSource(fi.getFD());
// pl.prepare();
// pl.start();
//
}
} catch (Exception e) {
// TODO: handle exception
}
/*
* Log.i("fileeee", "" + videos[1]);
*
* vView = (VideoView) findViewById(R.id.vview);
*
* // use this to get touch events vView.requestFocus();
*
* // load video from SD card vView.setVideoPath(
* "/data/data/com.example.downlaodvideo/files/videos/blaa.mp4");
*
* // enable this if you want to enable video controllers, such as pause
* // and forward
*
* // plays the movie vView.start();
*/
File SDCardRoot = new File(VideoSaveSDCARD.this.getFilesDir() + "/"
+ "videos");
if (!SDCardRoot.exists()) {
SDCardRoot.mkdir();
}
// deleteDirectory(SDCardRoot);
updater = new Updater();
updater.start();
}
class Updater extends Thread {
#Override
public void run() {
super.run();
downloadFiles(videoLink, name);
}
}
synchronized boolean downloadFiles(String link, String videoName) {
try {
URL url = new URL(link); // you can write here any link
long startTime = System.currentTimeMillis();
Log.d("VideoManager", "download begining");
Log.d("VideoManager", "download url:" + url);
Log.d("VideoManager", "downloaded file name:" + videoName);
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
/*
* Define InputStreams to read from the URLConnection.
*/
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
/*
* Read bytes to the Buffer until there is nothing more to read(-1).
*/
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
/* Convert the Bytes read to a String. */
FileOutputStream fos = new FileOutputStream(new File(SDCardRoot,
videoName));
fos.write(baf.toByteArray());
fos.close();
Log.d("VideoManager",
"download ready in"
+ ((System.currentTimeMillis() - startTime) / 1000)
+ " sec");
return true;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
public String getDataFromPortal(String remoteUrl, String myString) {
String data = null;
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(remoteUrl + myString);
try {
HttpResponse response1 = httpclient.execute(httpGet);
InputStream is = response1.getEntity().getContent();
data = getStringFromInputStream(is);
return data;
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
Log.d(TAG, "................internet yok catch 1");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.d(TAG, "................internet yok catch 2");
e.printStackTrace();
}
// The underlying HTTP connection is still held by the response
// object
// to allow the response content to be streamed directly from the
// network socket.
// In order to ensure correct deallocation of system resources
// the user MUST either fully consume the response content or abort
// request
// execution by calling HttpGet#releaseConnection().
return data;
}
private String getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
public static boolean deleteDirectory(File path) {
if (path.exists()) {
File[] files = path.listFiles();
if (files == null) {
return true;
}
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
deleteDirectory(files[i]);
} else {
files[i].delete();
}
}
}
return (path.delete());
}
}

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("on create","on create");
setContentView(R.layout.activity_main);
new Asyntask().execute();
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
SDCardRoot = new File("/sdcard/videos");
Log.d("SDCARDGGHGHg",""+SDCardRoot);
File[] videos = SDCardRoot.listFiles();
//Log.d("Videos array ",""+videos[0].getName());
vView = (VideoView) findViewById(R.id.vview);
Log.d("before try cathc","testing");
File SDCardRoot = new File("/sdcard/videos");
Log.d("SDCardRoot",""+SDCardRoot);
if (!SDCardRoot.exists()) {
SDCardRoot.mkdir();
}
}
class Asyntask extends AsyncTask<Void,Void,Void>
{
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
Log.d("In background","in background");
URL url;
try {
url = new URL(videoLink);
long startTime = System.currentTimeMillis();
Log.d("VideoManager", "download begining");
Log.d("VideoManager", "download url:" + url);
Log.d("VideoManager", "downloaded file name:" + name);
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
FileOutputStream fos;
fos = new FileOutputStream(new File(SDCardRoot,
name));
fos.write(baf.toByteArray());
fos.close();
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
catch (Exception e) {
// TODO: handle exception
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
Log.d("In post","in post");
vView.setVideoPath(SDCardRoot+"/blaa.mp4");
vView.start();
Log.d("android","post execute");
super.onPostExecute(result);
}
}
This will run your code.

Related

Download files in android

I am trying to write an application that downloads files in the background. The code crashes when it tries to reenter doInBackground(). This happens when doing is set to false before returning. Code follows -
public class DownloadFile extends AsyncTask<String, Integer, String> {
private boolean doing;
private Activity activity;
private Intent intent;
private File beta;
private File alpha;
public DownloadFile(Activity act, Intent intent) {
this.activity = act;
this.intent = intent;
doing = false;
}
#Override
protected String doInBackground(String... sUrl) {
int fileCount = 0;
if (!download(sUrl[0] + "list.txt",
Environment.getExternalStorageDirectory() + "/alpha/list.txt")){
setDoing(false);
return "Download failed";//list.txt could not be downloaded. return error message.
}
fileCount++;
beta = new File(Environment.getExternalStorageDirectory() + "/beta/");
File betalist = new File(beta + "/list.txt");
alpha = new File(Environment.getExternalStorageDirectory() + "/alpha/");
File alphalist = new File(alpha + "/list.txt");
//verify that the file is changed.
if (alphalist.lastModified() == betalist.lastModified()// these two are
// never equal.
|| alphalist.length() == betalist.length()) { // better to check
// the length of
// the files.
setDoing(false);
return "Nothing to download.";
}
try {
FileReader inAlpha = new FileReader(alphalist);
BufferedReader br = new BufferedReader(inAlpha);
String s;
// read the name of each file in a loop
while ((s = br.readLine()) != null) {
// if(fileExistsInBeta(s)){
// copyFromBetaToAlpha(s);
// continue;
// }
// download the file.
//Url will truncate the trailing / so keep if statement as is.
if (!download(sUrl[0] + s,
Environment.getExternalStorageDirectory() + "/alpha/"
+ s)){
setDoing(false);
return "Failed at " + s;// the given file could not be downloaded. return error.
}
fileCount++;
}
br.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
Log.e("Pankaj", e.getMessage());
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("Pankaj", e.getMessage());
} catch (Exception e) {
Log.e("Pankaj", e.getMessage());
}
Log.d("Pankaj", "Download Done");
activity.overridePendingTransition(0, 0);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
activity.finish();
Log.d("Pankaj", "MainActivity Killed");
// rename alpha to beta
deleteSubFolders(beta.toString());
beta.delete();
alpha.renameTo(beta);
if (!alpha.exists()) {
alpha.mkdir();
}
File upper = new File(alpha + "/upper/");
if (!upper.exists())
upper.mkdirs();
File lower = new File(alpha + "/lower/");
if (!lower.exists())
lower.mkdirs();
// ConfLoader.getInstance().reload();//to refresh the settings
// restart the activity
activity.overridePendingTransition(0, 0);
activity.startActivity(intent);
Log.d("Pankaj", "MainActivity restarted");
// now reset done status so we can start again.
setDoing(false);
return "Download finished.";// return the status for onPostExecute.
}
private void copyFromBetaToAlpha(String fileName) {
File beta=new File(Environment.getExternalStorageDirectory()+"/beta/"+fileName);
File alpha=new File(Environment.getExternalStorageDirectory()+"/alpha/"+fileName);
try {
FileInputStream fis=new FileInputStream(beta);
FileOutputStream fos=new FileOutputStream(alpha);
byte[] buf=new byte[1024];
int len;
while((len=fis.read(buf))>0){
fos.write(buf, 0, len);
}
fis.close();
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(activity, result, Toast.LENGTH_LONG).show();
super.onPostExecute(result);
}
public boolean download(String url, String file) {
boolean successful = true;
try {
URL u = new URL(url);
URLConnection conn = u.openConnection();
conn.connect();
int filelen = conn.getContentLength();
File f = new File(file);
// skip download if lengths are same
// because the file has been downed fully.
if (f.exists() && filelen == f.length()) {
return successful;
}
InputStream is = u.openStream();
DataInputStream dis = new DataInputStream(is);
byte[] buffer = new byte[1024];
int length;
FileOutputStream fos = new FileOutputStream(f);
while ((length = dis.read(buffer)) > 0) {
fos.write(buffer, 0, length);
}
fos.close();
buffer = null;
dis.close();
} catch (MalformedURLException mue) {
Log.e("SYNC getUpdate", "malformed url error", mue);
successful = false;
} catch (IOException ioe) {
Log.e("SYNC getUpdate", "io error", ioe);
successful = false;
} catch (SecurityException se) {
Log.e("SYNC getUpdate", "security error", se);
successful = false;
}
return successful;
}
private void deleteSubFolders(String uri) {
File currentFolder = new File(uri);
File files[] = currentFolder.listFiles();
if (files == null) {
return;
}
for (File f : files) {
if (f.isDirectory()) {
deleteSubFolders(f.toString());
}
// no else, or you'll never get rid of this folder!
f.delete();
}
}
public static int getFilesCount(File file) {
File[] files = file.listFiles();
int count = 0;
for (File f : files)
if (f.isDirectory())
count += getFilesCount(f);
else
count++;
return count;
}
public boolean isDoing() {
return doing;
}
/**
* #param doing
*/
public void setDoing(boolean doing) {
this.doing = doing;
}
private boolean fileExistsInBeta(final String fileName){
boolean exists=false;
File beta=new File(Environment.getExternalStorageDirectory()+"/beta/"+fileName);
if(beta.exists()){
String[] ext=beta.getName().split(".");
String extName=ext[ext.length-1];
exists=(extName!="txt" && extName!="tmr" && extName!="conf");
}
return exists;
}
in the main activity -
public void run() {
if (!downloadFile.isDoing()) {
downloadFile.execute(ConfLoader.getInstance().getListUrl());
downloadFile.setDoing(true);
}
// change the delay so that it covers the time for download and
// doesn't overlap causing multiple downloads jamming the bandwidth.
h.postDelayed(this, 1000);//check after 60 sec.
}
in the onCreate() -
downloadFile = new DownloadFile(this, getIntent());
h = new Handler();
h.postDelayed(this, 1000);
Any help is appreciated. Thanks in advance.
EDIT:
The logcat error is Cannot execute task the task is already running.
Cannot execute task: Task has already been executed(A task can only be executed once).
EDIT:
Is it possible that the error is because I am trying to execute the asynchtask again in run(). Perhaps AsynchTask does not allow re-entry.
Try using this
1. First create a dialogue
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Downloading file..");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
The download async task
class DownloadFileAsync extends AsyncTask<String, String, String> {
#SuppressWarnings("deprecation")
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected String doInBackground(String... aurl) {
int count;
File root = android.os.Environment.getExternalStorageDirectory();
//
File dir = new File (root.getAbsolutePath()+"/Downl");
if(dir.exists()==false) {
dir.mkdirs();
}
File file = new File(dir, url.substring(url.lastIndexOf("/")+1)); //name of file
try {
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(file);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1)
{
total += count;
publishProgress(""+(int)((total*100)/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC",progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#SuppressWarnings("deprecation")
#Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
Toast.makeText(DisplayActivity.this,"Successfully downloaded in phone memory.", Toast.LENGTH_SHORT).show();
}
}
Call the async new DownloadFileAsync().execute(url); //pass ur url

Android send file between two phones using socket and progress bar

i want to make an application for transfer files using wifi direct, but my send and receiver progress bar won't update
my sender
public void Server () {
new Thread(new Runnable()
{
#Override
public void run() {
// TODO Auto-generated method stub
try {
//receive ip
serverSocket = new ServerSocket(port);
Socket socket = serverSocket.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
ClientIP = line;
}
in.close();
socket.close();
serverSocket.close();
socket = null;
serverSocket = null;
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//send file
socket = new Socket();
socket.bind(null);
socketAddress = new InetSocketAddress(ClientIP, portal);
socket.connect(socketAddress, SOCKET_TIMEOUT);
FragmentManager fm = getFragmentManager();
md = new MyDialog("Send to " + ClientIP );
md.setRetainInstance(true);
md.setCancelable(true);
md.show(fm, "Sender");
//reset progress bar status
progressBarStatus = 0;
//reset filesize
fileSize = 0;
byte buf[] = new byte[1024];
File myFile = new File (path);
filelength = file.length();
OutputStream os = socket.getOutputStream();
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
while ((len = bis.read(buf)) != -1) {
fileSize+=len;
os.write(buf, 0, len);
os.flush();
//count for progress bar
double d = (double) (fileSize * 100) / filelength;
progressBarStatus = (int) Math.round(d);
progressBarHandler.post(new Runnable() {
public void run() {
md.updateProgress(progressBarStatus);
}
});
}
os.close();
fis.close();
bis.close();
socket.close();
// ok, file is downloaded,
if (progressBarStatus >= 100) {
// sleep 2 seconds, so that you can see the 100%
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
isSent = true;
runOnUiThread(new Runnable() {
public void run() {
if(isSent) {
Toast.makeText(getApplicationContext(), "File Sent", Toast.LENGTH_SHORT).show();
}
}
});
md.dismiss();
}
} catch (IOException e) {
Log.e(TAG, "I/O Exception", e);
} finally {
if (socket != null) {
if (socket.isConnected()) {
try {
socket.close();
} catch (IOException e) {
// Give up
e.printStackTrace();
}
}
}
}
}
}).start();
}
my receiver
public void Client (final String hostAddress) {
socketAddress = new InetSocketAddress(hostAddress, port);
socket = new Socket();
new Thread(new Runnable()
{
#Override
public void run() {
// TODO Auto-generated method stub
try {
//sent ip
socket.bind(null);
socket.connect(socketAddress, SOCKET_TIMEOUT);
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
out.println(messsage);
out.flush();
out.close();
socket.close();
socket = null;
//receive file
socket = new Socket();
serverSocket = new ServerSocket(portal);
socket = serverSocket.accept();
final String name;
final String ext;
String[] tokens = filename.split("\\.(?=[^\\.]+$)");
name = tokens[0];
ext = tokens[1];
final File f = new File(Environment.getExternalStorageDirectory() + "/"
+ getPackageName() + "/" + name + System.currentTimeMillis()
+ "." + ext);
File dirs = new File(f.getParent());
if (!dirs.exists())
dirs.mkdirs();
f.createNewFile();
FragmentManager fm = getFragmentManager();
md = new MyDialog("Receive from " + HostIP);
md.setRetainInstance(true);
md.setCancelable(true);
md.show(fm, "Receiver");
//reset progress bar status
progressBarStatus = 0;
//reset filesize
fileSize = 0;
filelength = f.length();
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream(f);
BufferedOutputStream bos = new BufferedOutputStream(fos);
byte buf[] = new byte[1024];
while ((len = is.read(buf)) != -1) {
bos.write(buf, 0, len);
bos.flush();
fileSize+=len;
double d = (double) (fileSize * 100) / filelength;
progressBarStatus = (int) Math.round(d);
progressBarHandler.post(new Runnable() {
public void run() {
md.updateProgress(progressBarStatus);
}
});
}
is.close();
fos.close();
bos.close();
socket.close();
serverSocket.close();
if (progressBarStatus >= 100) {
// sleep 2 seconds, so that you can see the 100%
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
isSent = true;
// close the progress bar dialog
//progressBar.dismiss();
runOnUiThread(new Runnable() {
public void run() {
// some code #3 (that needs to be ran in UI thread)
if(isSent) {
Toast.makeText(getApplicationContext(), "File Received", Toast.LENGTH_SHORT).show();
btn.setEnabled(true);
}
}
});
md.dismiss();
}
} catch (IOException e) {
Log.e(TAG, "IO Exception.", e);
}
}
}).start();
}
and i use dialog fragment because i use API 14+
my dialog class
public class MyDialog extends DialogFragment {
ProgressBar mProgressBar;
String title;
public MyDialog (String title) {
this.title = title;
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.popup, container);
mProgressBar = (ProgressBar)view.findViewById(R.id.pb);
getDialog().setTitle(title);
getDialog().setCanceledOnTouchOutside(false);
return view;
}
#Override
public void onDestroyView()
{
if (getDialog() != null && getRetainInstance())
getDialog().setDismissMessage(null);
super.onDestroyView();
}
#Override
public void onCancel(DialogInterface dialog) {
// TODO Auto-generated method stub
super.onCancel(dialog);
Toast.makeText(getActivity().getApplicationContext(), "Connection lost. Retry", Toast.LENGTH_SHORT).show();
getActivity().finish();
}
public void updateProgress(int percent)
{
mProgressBar.setProgress(percent);
}
}
i don't know why my code isn't working, my progress bar won't update and file not send.
Anyone can help me? thx before
You've got a lot of code, but as long as I know, the receiver should use an AsyncTask, that's how I do it and it works for me. Instead of a thread use an Asynctask and the OnProgressUpdate method of the AsyncTask to update the ProgressDialog in the main thread.
For example:
public class getFile extends AsyncTask<Void, String, Void>
{
ProgressDialog pB;
String hostAddress=null;
InetSocketAddress socketAddress;
Socket socket=null;
ServerSocket serverSocket=null;
int port=3001;
int SOCKET_TIMEOUT = 3000;
public getFile(String _hostAddress, Context context)
{
this.pB = new ProgressDialog(context);
this.pB.setTitle(context.getText(R.string.sYourMessageText);
this.pB.setMessage(null);
this.pB.setProgressNumberFormat(null);
this.pB.setProgressPercentFormat(null);
this.pB.setCancelable(false);
Drawable d = getResources().getDrawable(R.drawable.x_greenprogress);
pB.setProgressDrawable(d);
pB.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
hostAddress=_hostAddress;
}
#Override
protected void onPreExecute()
{
this.pB.show();
}
#Override
protected Void doInBackground(Void... params)
{
try {
//sent ip
socketAddress = new InetSocketAddress(this.hostAddress, port);
socket = new Socket();
socket.bind(null);
socket.connect(socketAddress, SOCKET_TIMEOUT);
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
out.println(messsage);
out.flush();
out.close();
socket.close();
socket = null;
//receive file
socket = new Socket();
serverSocket = new ServerSocket(portal);
socket = serverSocket.accept();
final String name;
final String ext;
String[] tokens = filename.split("\\.(?=[^\\.]+$)");
name = tokens[0];
ext = tokens[1];
final File f = new File(Environment.getExternalStorageDirectory() + "/"
+ getPackageName() + "/" + name + System.currentTimeMillis()
+ "." + ext);
File dirs = new File(f.getParent());
if (!dirs.exists())
dirs.mkdirs();
f.createNewFile();
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream(f);
BufferedOutputStream bos = new BufferedOutputStream(fos);
byte buf[] = new byte[1024];
while ((len = is.read(buf)) != -1)
{
bos.write(buf, 0, len);
bos.flush();
fileSize+=len;
// to update the progress bar just call:
this.publishProgress("" + (int) ((fileSize * 100) / filelength));
}
is.close();
fos.close();
bos.close();
socket.close();
serverSocket.close();
}
#Override
protected void onProgressUpdate(String... progress)
{
this.pB.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(Void result)
{
if (this.pB.isShowing())
this.pB.dismiss();
}
}
EDIT:
By the way, why do you connect to the server, send an IP close the connection and wait for the server to connect? Why don't use the first socket to do the file transfer? The connection has already been established.

How to write XML file on Android, getting from remote server

I need sometimes read XML file from remote server, and replace data in XML on my Android device.
I read data through XmlPullParser:
XmlPullParser users;
try {
URL xmlUrl = new URL("http://xx.xx.xx.xx/1.xml");
users = XmlPullParserFactory.newInstance().newPullParser();
users.setInput(xmlUrl.openStream(), null);
}
How can I replace it on Android?
Simply use this code, it's overwrites the file with the new file you download from the internet.
public static boolean downloadFile(String fileToDownload, File newPath,
String newFileName) {
try {
URL url = new URL(fileToDownload);
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
if (!newPath.isDirectory()) {
CreateLog.createFolder(newPath.toString());
}
File file = new File(newPath.toString() + "/" + newFileName);
if (!file.isFile()) {
CreateLog.writeLogToFile(newPath.toString() + newFileName,
"%TEMP%");
}
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ((bufferLength = inputStream.read(buffer)) > 0) {
fileOutput.write(buffer, 0, bufferLength);
}
fileOutput.close();
return true;
} catch (MalformedURLException e) {
CreateLog.addToLog(e.toString());
return false;
} catch (IOException e) {
CreateLog.addToLog(e.toString());
return false;
}
}
public static void createFolder(String filePath) {
File createFolder = new File(filePath);
createFolder.mkdirs();
}
A cleaner method is to use a Asynctask, the code runs in a new thread. But it's a bit harder to code.
private class GetProblems extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
for (String myUrl : params) {
try {
URL url = new URL(myUrl);
URLConnection ucon = url.openConnection();
ucon.setRequestProperty("Accept", "application/xml");
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
String str = new String(baf.toByteArray(), "UTF8");
return str;
} catch (MalformedURLException e) {
CreateLog.addToLog("[GetProblems] " + e.toString());
} catch (IOException e) {
CreateLog.addToLog("[GetProblems] " + e.toString());
}
}
return "error";
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
// updateProgressBar(values[0]);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
...write result to a file
}
}
Run the AsyncTask code:
new GetProblems().execute("http://myurl.com/xmlfile.xml");

Getting a file size mismatch with android download code

I'm downloading a file from a server and for some reason i can't determine, the downloaded file size doesn't match the original file size. Here's my code.
private class dl extends AsyncTask<String,Integer,Void>
{
int size;
#Override
protected Void doInBackground(String... arg0) {
// TODO Auto-generated method stub
try{
URL myFileUrl = new URL("http://10.0.2.2:8080/testdlapps/chrome-beta.zip");
HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setConnectTimeout(5000);
conn.connect();
InputStream is = conn.getInputStream();
size = conn.getContentLength();
Log.v("INFO---------------------", "size is " +size);
FileOutputStream fout1 = new FileOutputStream(Environment.getExternalStorageDirectory()+"/"+"xyz.zip");
BufferedOutputStream bos = new BufferedOutputStream(fout1);
byte[] b = new byte[1024]; int i=0, count=0;
while((count = is.read(b)) != -1)
{
bos.write(b,0,count);
i+=count;
publishProgress(i);
Log.v("INFO----------------------------",""+count);
}
fout1.close();
}catch(Exception e){
Log.v("INFO--------------------------","Error!!");
Log.v("INFO--------------------------",e.getMessage());
e.printStackTrace();
}
return null;
}
protected void onProgressUpdate(Integer... progress) {
tv.setText("downloaded " + progress[0] + "/" + size ); //tv is a TextView
}
}
When i run the app, after the download completes, count and size are the same but the actual file size i.e /mnt/sdcard/xyz.zip is always less than size. Any ideas what going wrong?
override onPostExecute and check if actually it finishes, perhaps here a code to download with resume support,
pay attention because if you press back the download may still run:
if (isCancelled())
return false;
in the loop is needed because the close() on the socket will hang on exit without you noticeing it
here is the code:
class DownloaderTask extends AsyncTask<String, Integer, Boolean>
{
private ProgressDialog mProgress;
private Context mContext;
private Long mFileSize;
private Long mDownloaded;
private String mDestFile;
public DownloaderTask(Context context, String path)
{
mContext = context;
mFileSize = 1L;
mDownloaded = 0L;
mDestFile = path;
}
#Override
protected void onPreExecute()
{
mProgress = new ProgressDialog(mContext);
mProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgress.setMessage("Downloading...");
mProgress.setCancelable(true);
mProgress.setCanceledOnTouchOutside(false);
mProgress.setOnCancelListener(new DialogInterface.OnCancelListener()
{
#Override
public void onCancel(DialogInterface dialog)
{
DownloaderTask.this.cancel(true);
}
});
mProgress.show();
}
#Override
protected void onProgressUpdate(Integer... percent)
{
mProgress.setProgress(percent[0]);
}
#Override
protected Boolean doInBackground(String... urls)
{
FileOutputStream fos = null;
BufferedInputStream in = null;
BufferedOutputStream out = null;
AndroidHttpClient mClient = AndroidHttpClient.newInstance("AndroidDownloader");
try
{
HttpResponse response = null;
HttpHead head = new HttpHead(urls[0]);
response = mClient.execute(head);
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK)
return false;
Boolean resumable = response.getLastHeader("Accept-Ranges").getValue().equals("bytes");
File file = new File(mDestFile);
mFileSize = (long) Integer.parseInt(response.getLastHeader("Content-Length").getValue());
mDownloaded = file.length();
if (!resumable || (mDownloaded >= mFileSize))
{
Log.e(TAG, "Invalid size / Non resumable - removing file");
file.delete();
mDownloaded = 0L;
}
HttpGet get = new HttpGet(urls[0]);
if (mDownloaded > 0)
{
Log.i(TAG, "Resume download from " + mDownloaded);
get.setHeader("Range", "bytes=" + mDownloaded + "-");
}
response = mClient.execute(get);
if ((response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) && (response.getStatusLine().getStatusCode() != HttpStatus.SC_PARTIAL_CONTENT))
return false;
if (mDownloaded > 0)
publishProgress((int) ((mDownloaded / mFileSize) * 100));
in = new BufferedInputStream(response.getEntity().getContent());
fos = new FileOutputStream(file, true);
out = new BufferedOutputStream(fos);
byte[] buffer = new byte[8192];
int n = 0;
while ((n = in.read(buffer, 0, buffer.length)) != -1)
{
if (isCancelled())
return false;
out.write(buffer, 0, n);
mDownloaded += n;
publishProgress((int) ((mDownloaded / (float) mFileSize) * 100));
}
} catch (Exception e)
{
e.printStackTrace();
return false;
} finally
{
try
{
mClient.close();
if (in != null)
in.close();
if (out != null)
out.close();
if (fos != null)
fos.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
return true;
}
#Override
protected void onCancelled()
{
finish();
}
#Override
protected void onPostExecute(Boolean result)
{
if (mProgress.isShowing())
mProgress.dismiss();
if (result)
// done
else
// error
}
}
If it is a chunked response, the content-length in the header will be a guess at best.

How to receive data from the server?

I am trying to fetchg data from server like MP3 files, video files, etc. in my application. The application should show the list of video files received from the server.
How can I do this?
/** this function will download content from the internet */
static int writeData(String fileurl, boolean append, String path,
String filename, Activity mContext) throws CustomException {
URL myfileurl = null;
ByteArrayBuffer baf = null;
HttpURLConnection conn = null;
String mimeType="";
final int length;
try {
myfileurl = new URL(fileurl);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
conn = (HttpURLConnection) myfileurl
.openConnection();
conn.setDoInput(true);
conn.connect();
conn.setConnectTimeout(100000);
length = conn.getContentLength();
mimeType=conn.getContentType().toString();
System.out.println("Extension..."+mimeType);
if(mimeType.equalsIgnoreCase("application/vnd.adobe.adept+xml") || mimeType.equalsIgnoreCase("text/html; charset=utf-8"))
return 0;
if (length > 0) {
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
baf = new ByteArrayBuffer(1000);
int current = 0;
while ((current = bis.read()) != -1) {
try {
baf.append((byte) current);
mBufferError=false;
} catch (Exception e){
// TODO: handle exception
mBufferError=true;
e.printStackTrace();
throw new CustomException("### memory problem ", "Buffer Error");
}
}
}
} catch (IOException e) {
mBufferError=true;
e.printStackTrace();
}
try{
if(conn.getResponseCode()==200 && mBufferError==false)
{
path = path + "/" + filename;
boolean appendData = append;
FileOutputStream foutstream;
File file = new File(path);
boolean exist = false;
try {
if (appendData)
exist = file.exists();
else
exist = file.createNewFile();
} catch (IOException e) {
try {
return 1;
} catch (Exception err) {
Log.e("SAX", err.toString());
}
}
if (!appendData && !exist) {
} else if (appendData && !exist) {
} else {
try {
foutstream = new FileOutputStream(file, appendData);
foutstream.write(baf.toByteArray());
foutstream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}catch (Exception e) {
// TODO: handle exception
throw new CustomException("### I/O problem ", "I/O Error");
}
return 1;
}
once download complete search the file with extension(.3gp) for video
hope it helps
Check this link,
https://stackoverflow.com/search?q=how+to+download+mp3+%2Cvideos+from+server+in+android
Try this code
url = "your url name+filename.jpg,mp3,etc..."
FileName = "/sdcard/savefilename" // save in your sdcard
try{
java.io.BufferedInputStream in = new java.io.BufferedInputStream(new java.net.URL(url).openStream());
java.io.FileOutputStream fos = new java.io.FileOutputStream(FileName);
java.io.BufferedOutputStream bout = new BufferedOutputStream(fos,1024);
byte[] data = new byte[1024];
int x=0;
while((x=in.read(data,0,1024))>=0){
bout.write(data,0,x);
}
fos.flush();
bout.flush();
fos.close();
bout.close();
in.close();
}
catch (Exception ex)
{
}
and after you want to use MediaPlayer
and create object of mediaplayer in your activity
and play.
mp.reset();
mp.start();

Categories

Resources