我有一个方法,我从给定的URL下载并保存图像,此方法返回一个文件,然后我使用此文件(图像)获取它的路径并使用它来共享此图像。 我的测试结果如下:
我的方法:
private class getImgDownloadedPath extends AsyncTask<Void, Void, File> {
private String urlImage;
private String imageName;
private Context context;
private ProgressDialog dialog;
short max=100;
public getImgDownloadedPath(Context context,String urlImage,String imageName){
this.urlImage = urlImage;
this.imageName = imageName;
this.context = context;
dialog = new ProgressDialog(context);
dialog.setTitle("Share");
dialog.setMax(max);
dialog.setCancelable(false);
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setMessage("Please Wait...");
}
protected void onPreExecute() {
// TODO Auto-generated method stub
dialog.show();
}
protected File doInBackground(Void... params) {
String filepath = null;
File fileToReturn = null;
try
{
URL url = new URL(urlImage);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
String SDCardRoot = Environment.getExternalStorageDirectory().toString(); //.getAbsoluteFile();
new File(SDCardRoot + "/Pictures/Pubit").mkdirs();
String filename= imageName + ".png";
Log.i("Local filename:",""+filename);
File file = new File(SDCardRoot + "/Pictures/myapp",filename);
if(file.createNewFile()) {
file.createNewFile();
}
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
int totalSize = urlConnection.getContentLength();
int downloadedSize = 0;
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer)) > 0 )
{
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
Log.i("Progress:","downloadedSize:"+downloadedSize+"totalSize:"+ totalSize) ;
}
fileOutput.close();
if(downloadedSize==totalSize){
filepath=file.getPath();
fileToReturn = file;
}
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
filepath=null;
e.printStackTrace();
}
Log.i("filepath:"," "+fileToReturn.getPath()) ;
dialog.dismiss();
return fileToReturn;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(File filepath)
{
Toast.makeText(activity,"This is url: " + filepath.getPath(), Toast.LENGTH_LONG).show();
Intent sendIntent = new Intent();
sendIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.setType("image/png");
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(filepath));
context.startActivity(Intent.createChooser(sendIntent, "Share Image!"));
}
}
这是我的日志错误
12-07 16:54:01.754: E/AndroidRuntime(896): FATAL EXCEPTION: AsyncTask #1
12-07 16:54:01.754: E/AndroidRuntime(896): java.lang.RuntimeException: An error occured while executing doInBackground()
12-07 16:54:01.754: E/AndroidRuntime(896): at android.os.AsyncTask$3.done(AsyncTask.java:266)
12-07 16:54:01.754: E/AndroidRuntime(896): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
12-07 16:54:01.754: E/AndroidRuntime(896): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
12-07 16:54:01.754: E/AndroidRuntime(896): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
12-07 16:54:01.754: E/AndroidRuntime(896): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
12-07 16:54:01.754: E/AndroidRuntime(896): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1081)
12-07 16:54:01.754: E/AndroidRuntime(896): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:574)
12-07 16:54:01.754: E/AndroidRuntime(896): at java.lang.Thread.run(Thread.java:1020)
12-07 16:54:01.754: E/AndroidRuntime(896): Caused by: java.lang.NullPointerException
12-07 16:54:01.754: E/AndroidRuntime(896): at me.devy.myapp.adapter.FeedListAdapter$getImgDownloadedPath.doInBackground(FeedListAdapter.java:360)
12-07 16:54:01.754: E/AndroidRuntime(896): at me.devy.myapp.adapter.FeedListAdapter$getImgDownloadedPath.doInBackground(FeedListAdapter.java:1)
12-07 16:54:01.754: E/AndroidRuntime(896): at android.os.AsyncTask$2.call(AsyncTask.java:252)
12-07 16:54:01.754: E/AndroidRuntime(896): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
12-07 16:54:01.754: E/AndroidRuntime(896): ... 4 more
12-07 16:54:04.976: E/WindowManager(896): Activity me.devy.myapp.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@40c9d2f8 that was originally added here
12-07 16:54:04.976: E/WindowManager(896): android.view.WindowLeaked: Activity me.devy.myapp.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@40c9d2f8 that was originally added here
12-07 16:54:04.976: E/WindowManager(896): at android.view.ViewRoot.<init>(ViewRoot.java:285)
12-07 16:54:04.976: E/WindowManager(896): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:152)
12-07 16:54:04.976: E/WindowManager(896): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:95)
12-07 16:54:04.976: E/WindowManager(896): at android.view.Window$LocalWindowManager.addView(Window.java:526)
12-07 16:54:04.976: E/WindowManager(896): at android.app.Dialog.show(Dialog.java:269)
12-07 16:54:04.976: E/WindowManager(896): at me.devy.myapp.adapter.FeedListAdapter$getImgDownloadedPath.onPreExecute(FeedListAdapter.java:302)
12-07 16:54:04.976: E/WindowManager(896): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:549)
12-07 16:54:04.976: E/WindowManager(896): at android.os.AsyncTask.execute(AsyncTask.java:499)
12-07 16:54:04.976: E/WindowManager(896): at me.devy.myapp.adapter.FeedListAdapter$2.onClick(FeedListAdapter.java:184)
12-07 16:54:04.976: E/WindowManager(896): at android.view.View.performClick(View.java:3110)
12-07 16:54:04.976: E/WindowManager(896): at android.view.View$PerformClick.run(View.java:11928)
12-07 16:54:04.976: E/WindowManager(896): at android.os.Handler.handleCallback(Handler.java:587)
12-07 16:54:04.976: E/WindowManager(896): at android.os.Handler.dispatchMessage(Handler.java:92)
12-07 16:54:04.976: E/WindowManager(896): at android.os.Looper.loop(Looper.java:132)
12-07 16:54:04.976: E/WindowManager(896): at android.app.ActivityThread.main(ActivityThread.java:4025)
12-07 16:54:04.976: E/WindowManager(896): at java.lang.reflect.Method.invokeNative(Native Method)
12-07 16:54:04.976: E/WindowManager(896): at java.lang.reflect.Method.invoke(Method.java:491)
12-07 16:54:04.976: E/WindowManager(896): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
12-07 16:54:04.976: E/WindowManager(896): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
12-07 16:54:04.976: E/WindowManager(896): at dalvik.system.NativeStart.main(Native Method)
12-07 16:54:10.164: D/dalvikvm(896): GC_EXPLICIT freed 4729K, 24% free 18062K/23495K, paused 24ms+8ms
由于app无法以某种方式创建存储图像所需的目录,是否会出现此问题?如果不是这样,请帮助谢谢
编辑:
在应用Greenapps的建议后,我做到了这一点:
private class getImgDownloadedPath extends AsyncTask<Void, Void, File> {
private String urlImage;
private String imageName;
private Context context;
private ProgressDialog dialog;
short max=100;
public getImgDownloadedPath(Context context,String urlImage,String imageName){
this.urlImage = urlImage;
this.imageName = imageName;
this.context = context;
dialog = new ProgressDialog(context);
dialog.setTitle("Pubit");
dialog.setMax(max);
dialog.setCancelable(false);
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setMessage("Please Wait...");
}
protected void onPreExecute() {
// TODO Auto-generated method stub
dialog.show();
Log.i("Dialog:","Dialog is Shown");
}
protected File doInBackground(Void... params) {
Log.i("Do In Background:","Do In Background Started");
String filepath = null;
File fileToReturn = null;
boolean success = false;
String state = Environment.getExternalStorageState();
try
{
if (state.equals(Environment.MEDIA_MOUNTED)) {
Log.i("Phase 1:"," Available: True - Writable: True ");
URL url = new URL(urlImage);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
String SDCardRoot = Environment.getExternalStorageDirectory().toString(); //.getAbsoluteFile();
File f = new File(Environment.getExternalStorageDirectory() + "/Pictures/Pubit");
if(!f.isDirectory()) {
success = new File(SDCardRoot + "/Pictures/Pubit").mkdirs();
Log.i("MKDIRS:"," Creating /Pictures/Pubit ");
}
if (success) {
Log.i("Phase 2:"," MKDIRS Created /Pictures/Pubit ");
if (f.canWrite()) {
Log.i("Phase 3:"," /Pictures/Pubit is Writable ");
String filename= imageName + ".png";
Log.i("Local filename:",""+filename);
File file = new File(SDCardRoot + "/Pictures/Pubit",filename);
if(file.createNewFile()) {
file.createNewFile();
}
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
int totalSize = urlConnection.getContentLength();
int downloadedSize = 0;
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
Log.i("Progress:","downloadedSize:"+downloadedSize+"totalSize:"+ totalSize) ;
}
fileOutput.close();
if(downloadedSize==totalSize){
filepath=file.getPath();
fileToReturn = file;
}
}
else {
Toast.makeText(activity, "Folder: Pictures/Pubit Can't write", Toast.LENGTH_LONG).show();
Log.i("Cause Of Error:","Folder: Pictures/Pubit Can't write");
}
}
else {
Toast.makeText(activity, "Error Creating Folders", Toast.LENGTH_LONG).show();
Log.i("Cause Of Error:","Error Creating Folders");
}
}
else if (state.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
// Storage is only readable
Toast.makeText(activity, "Available: True - Writable - False ", Toast.LENGTH_LONG).show();
Log.i("Cause Of Error:","Available: True - Writable - False ");
}
else {
// Storage is neither readable nor writeable
Toast.makeText(activity, "Available: False - Writable - False ", Toast.LENGTH_LONG).show();
Log.i("Cause Of Error:","Available: False - Writable - False ");
}
}
catch (MalformedURLException e) {
Log.i("Problem is Malformed Url:","Starting -------------------------");
e.printStackTrace();
Log.i("Problem is Malformed Url:","Ending -------------------------");
}
catch (IOException e) {
Log.i("Problem is IO Exception: ","Starting -------------------------");
filepath=null;
e.printStackTrace();
Log.i("Problem is IO Exception: ","Ending -------------------------");
}
Log.i("filepath:"," "+fileToReturn.getPath()) ;
dialog.dismiss();
return fileToReturn;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(File filepath)
{
Log.i("filepath value:","Value of filepath is: " + filepath);
if (filepath == null) {
Toast.makeText(activity, "Can't Share, File is null", Toast.LENGTH_LONG);
Log.i("Cause Of Error:","Can't Share, File is null");
}
else{
Toast.makeText(activity,"This is url: " + filepath.getPath(), Toast.LENGTH_LONG).show();
Intent sendIntent = new Intent();
sendIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.setType("image/png");
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(filepath));
context.startActivity(Intent.createChooser(sendIntent, "Share Image!"));
}
}
}
仍然没有工作同样的问题任何建议??