ورود

View Full Version : خطا هنگام دانلود فایل



ho3ein.3ven
دوشنبه 06 مرداد 1393, 17:10 عصر
سلام
من یه برنامه نوشتم که یک فایل رو دانلود می کنه . بعضی وقتا تو حین دانلود فایل کرش می کنه . چطور می تونم به جای کرش کردن یک پیغام مناسب نشون بدم ؟

package com.example.downloader;import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;


import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore.Video;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.VideoView;


public class MainActivity extends Activity {


// button to show progress dialog
Button btnShowProgress;


// Progress Dialog
private ProgressDialog pDialog;
VideoView my_image;
// Progress dialog type (0 - for Horizontal progress bar)
public static final int progress_bar_type = 0;


// File url to download
private static String file_url = "";


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);


// show progress bar button
btnShowProgress = (Button) findViewById(R.id.btnProgressBar);
// Image view to show image after downloading
my_image = (VideoView) findViewById(R.id.my_image);


my_image.setMediaController(new MediaController(this));


/**
* Show Progress bar click event
* */
btnShowProgress.setOnClickListener(new View.OnClickListener() {


@Override
public void onClick(View v) {
// starting new Async Task
new DownloadFileFromURL().execute(file_url);
}
});
}


/**
* Showing Dialog
* */
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type: // we set this to 0
pDialog = new ProgressDialog(this);
pDialog.setMessage("Downloading file. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORI ZONTAL);
pDialog.setCancelable(true);
pDialog.show();
return pDialog;
default:
return null;
}
}


/**
* Background Async Task to download file
* */
class DownloadFileFromURL extends AsyncTask<String, String, String> {


/**
* Before starting background thread
* Show Progress Bar Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}


/**
* Downloading file in background thread
* */
@Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// this will be useful so that you can show a tipical 0-100% progress bar
int lenghtOfFile = conection.getContentLength();


// download the file
InputStream input = new BufferedInputStream(url.openStream(), 8192);


// Output stream
OutputStream output = new FileOutputStream("/sdcard/downloadedfile.3gp");


byte data[] = new byte[1024];


long total = 0;


while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress(""+(int)((total*100)/lenghtOfFile));


// writing data to file
output.write(data, 0, count);
}


// flushing output
output.flush();


// closing streams
output.close();
input.close();


} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}


return null;
}


/**
* Updating progress bar
* */
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialog.setProgress(Integer.parseInt(progress[0]));
}


/**
* After completing background task
* Dismiss the progress dialog
* **/
@Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
dismissDialog(progress_bar_type);


// Displaying downloaded image into image view
// Reading image path from sdcard
//String imagePath = Environment.getExternalStorageDirectory().toString () + "/downloadedfile.jpg";

//Uri vidFile = Uri.parse(
// Environment.getExternalStorageDirectory().getAbsol utePath()+"filename");


// setting downloaded into image view
//my_image.setImageDrawable(Drawable.createFromPath( imagePath));

// my_image.setVideoURI(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/" + "downloadedfile.3gp")));
my_image.setVideoPath("/sdcard/downloadedfile.3gp");

my_image.requestFocus();




my_image.start();
}


}
}

ho3ein.3ven
سه شنبه 07 مرداد 1393, 11:09 صبح
کسی نتونست این مشکل رو حل کنه ؟

spiderman200700
سه شنبه 07 مرداد 1393, 12:40 عصر
کل حلقه while رو توی یه try catch قرار یده و در catch پیغام رو نشون بده

ho3ein.3ven
سه شنبه 07 مرداد 1393, 13:39 عصر
خیلی ممنون از پاسختون

یک مشکل دیگه هم با این کد دارم . اونم اینه که بعضی وقتا در حالی که فایل دانلود نشده تابع onPostExecute فراخوانی میشه . من توی برنامم فراخوانی این تابع رو مبنی بر تمام شدن دانلود میدونم که همین باعث اختلال تو برنامه میشه . آیا راهی هست این مورد رو رفع کنم ؟

akbar8298
سه شنبه 07 مرداد 1393, 16:20 عصر
خیلی ممنون از پاسختون

یک مشکل دیگه هم با این کد دارم . اونم اینه که بعضی وقتا در حالی که فایل دانلود نشده تابع onPostExecute فراخوانی میشه . من توی برنامم فراخوانی این تابع رو مبنی بر تمام شدن دانلود میدونم که همین باعث اختلال تو برنامه میشه . آیا راهی هست این مورد رو رفع کنم ؟


شما بعد از حلقه while چک کنید ببینید که سایز فایل دانلود شده با فایل اصلی برابر هست یا نه. اگر بود که مقدار برگشتی رو null کنید. اگبر نبود یعنی کامل دانلود نشده و یه مقداری به جز null برگردانید (return کنید) توی متد protected void onPostExecute(String file_url) متغیر file_url همون مقدار برگشتی هست که متد doinBackground برگردانده. این متغیر رو چک کنید اگر null بود یعنی کامل دانلود شده.

موفق باشید

ho3ein.3ven
چهارشنبه 08 مرداد 1393, 00:05 صبح
شما بعد از حلقه while چک کنید ببینید که سایز فایل دانلود شده با فایل اصلی برابر هست یا نه. اگر بود که مقدار برگشتی رو null کنید. اگبر نبود یعنی کامل دانلود نشده و یه مقداری به جز null برگردانید (return کنید) توی متد protected void onPostExecute(String file_url) متغیر file_url همون مقدار برگشتی هست که متد doinBackground برگردانده. این متغیر رو چک کنید اگر null بود یعنی کامل دانلود شده.

موفق باشید

سلام

ممنون به خاطر راهنمایی که کردین .
مراحلی که فرمودین رو انجام دادم ولی جواب نگرفتم .

package com.example.downloader;import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;


import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore.Video;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.Toast;
import android.widget.VideoView;


public class MainActivity extends Activity {


// button to show progress dialog
Button btnShowProgress;


// Progress Dialog
private ProgressDialog pDialog;
VideoView my_image;
// Progress dialog type (0 - for Horizontal progress bar)
public static final int progress_bar_type = 0;


// File url to download
private static String file_url = "";


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);


// show progress bar button
btnShowProgress = (Button) findViewById(R.id.btnProgressBar);
// Image view to show image after downloading
my_image = (VideoView) findViewById(R.id.my_image);


my_image.setMediaController(new MediaController(this));


/**
* Show Progress bar click event
* */
btnShowProgress.setOnClickListener(new View.OnClickListener() {


@Override
public void onClick(View v) {
// starting new Async Task
new DownloadFileFromURL().execute(file_url);
}
});
}


/**
* Showing Dialog
* */
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type: // we set this to 0
pDialog = new ProgressDialog(this);
pDialog.setMessage("Downloading file. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORI ZONTAL);
pDialog.setCancelable(true);
pDialog.show();
return pDialog;
default:
return null;
}
}


/**
* Background Async Task to download file
* */
class DownloadFileFromURL extends AsyncTask<String, String, String> {


/**
* Before starting background thread
* Show Progress Bar Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}


/**
* Downloading file in background thread
* */
@Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// this will be useful so that you can show a tipical 0-100% progress bar
int lenghtOfFile = conection.getContentLength();


// download the file
InputStream input = new BufferedInputStream(url.openStream(), 8192);


// Output stream
OutputStream output = new FileOutputStream("/sdcard/downloadedfile.3gp");


byte data[] = new byte[1024];


long total = 0;
try{
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress(""+(int)((total*100)/lenghtOfFile));


// writing data to file
output.write(data, 0, count);
}
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(), ".",Toast.LENGTH_SHORT).show();
}


// flushing output
output.flush();


// closing streams
output.close();
input.close();


if(lenghtOfFile==total)
{
return null;
}
else
{
return "salam";
}

} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}


return null;
}


/**
* Updating progress bar
* */
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialog.setProgress(Integer.parseInt(progress[0]));
}


/**
* After completing background task
* Dismiss the progress dialog
* **/
@Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
dismissDialog(progress_bar_type);


// Displaying downloaded image into image view
// Reading image path from sdcard
//String imagePath = Environment.getExternalStorageDirectory().toString () + "/downloadedfile.jpg";

//Uri vidFile = Uri.parse(
// Environment.getExternalStorageDirectory().getAbsol utePath()+"filename");


// setting downloaded into image view
//my_image.setImageDrawable(Drawable.createFromPath( imagePath));

// my_image.setVideoURI(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/" + "downloadedfile.3gp")));

if (file_url==null)
{
my_image.setVideoPath("/sdcard/downloadedfile.3gp");

my_image.requestFocus();




my_image.start();


}
else
{
Toast.makeText(getApplicationContext(), " .", Toast.LENGTH_SHORT).show();
}
}


}
}




اگر امکانش هست کد ها رو بررسی کنید ببینید درست انجام دادم .
با تشکر

ho3ein.3ven
چهارشنبه 08 مرداد 1393, 12:07 عصر
هنوز بعضی وقتا برنامه کرش می کنه . اینم log cat :

07-30 04:08:48.322: W/dalvikvm(832): threadid=11: thread exiting with uncaught exception (group=0x41465700)
07-30 04:08:48.332: E/AndroidRuntime(832): FATAL EXCEPTION: AsyncTask #1
07-30 04:08:48.332: E/AndroidRuntime(832): java.lang.RuntimeException: An error occured while executing doInBackground()
07-30 04:08:48.332: E/AndroidRuntime(832): at android.os.AsyncTask$3.done(AsyncTask.java:299)
07-30 04:08:48.332: E/AndroidRuntime(832): at java.util.concurrent.FutureTask.finishCompletion(F utureTask.java:352)
07-30 04:08:48.332: E/AndroidRuntime(832): at java.util.concurrent.FutureTask.setException(Futur eTask.java:219)
07-30 04:08:48.332: E/AndroidRuntime(832): at java.util.concurrent.FutureTask.run(FutureTask.jav a:239)
07-30 04:08:48.332: E/AndroidRuntime(832): at java.util.concurrent.ThreadPoolExecutor.runWorker( ThreadPoolExecutor.java:1080)
07-30 04:08:48.332: E/AndroidRuntime(832): at java.util.concurrent.ThreadPoolExecutor$Worker.run (ThreadPoolExecutor.java:573)
07-30 04:08:48.332: E/AndroidRuntime(832): at java.lang.Thread.run(Thread.java:841)
07-30 04:08:48.332: E/AndroidRuntime(832): Caused by: java.lang.NullPointerException: println needs a message
07-30 04:08:48.332: E/AndroidRuntime(832): at android.util.Log.println_native(Native Method)
07-30 04:08:48.332: E/AndroidRuntime(832): at android.util.Log.e(Log.java:231)
07-30 04:08:48.332: E/AndroidRuntime(832): at com.example.p.PVideoPlayer$DownloadFileFromURL.doI nBackground(PVideoPlayer.java:327)
07-30 04:08:48.332: E/AndroidRuntime(832): at com.example.p.PVideoPlayer$DownloadFileFromURL.doI nBackground(PVideoPlayer.java:1)
07-30 04:08:48.332: E/AndroidRuntime(832): at android.os.AsyncTask$2.call(AsyncTask.java:287)
07-30 04:08:48.332: E/AndroidRuntime(832): at java.util.concurrent.FutureTask.run(FutureTask.jav a:234)
07-30 04:08:48.332: E/AndroidRuntime(832): ... 3 more
07-30 04:08:48.942: I/Choreographer(832): Skipped 461 frames! The application may be doing too much work on its main thread.

akbar8298
چهارشنبه 08 مرداد 1393, 23:25 عصر
07-30 04:08:48.332: E/AndroidRuntime(832): Caused by: java.lang.NullPointerException: println needs a message

ببین این کد داره می گه که شما یه جایی توی doInBackground یه چیزی رو می خوای چاپ کنید که اون چیز (متغیر) مقدا نداره. شما محض اطمینان هر جا چیزی رو دارید چاپ می کنید (print , pringln , log ,...) کد ""+ رو اول چیزی که می خواید چاپ کنید بزارید. به این ترتیب مطمئنیم که حداقل مقدا "" چاپ خواهد شد. یه تست بزنید.