我有一個應用程序必須下載一些生成的圖像(PNG)。將下載的文件保存到內部存儲器java/android失敗
我試過標準方法ImageDownloader extends AsyncTask
,doInBackground()
檢索圖像和onPostExecute()
將嘗試將其保存到內部圖像。
代碼(的部分)低於:
public class HandleImages extends AppCompatActivity {
String filename = "";
public boolean saveImageToInternalStorage(Bitmap image) {
try {
FileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE);
image.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public Bitmap retrieveImage(String url){
ImageDownloader task = new ImageDownloader();
Bitmap image = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888);
try {
image = task.execute(url).get();
} catch (InterruptedException e) {
MainActivity.debb("InterruptedException - " + e.getMessage() + " in " + new Object(){}.getClass().getEnclosingMethod().getName());
e.printStackTrace();
} catch (ExecutionException e) {
MainActivity.debb("ExecutionException - " + e.getMessage() + " in " + new Object(){}.getClass().getEnclosingMethod().getName());
e.printStackTrace();
}
return image;
}
public class ImageDownloader extends AsyncTask<String, Void, Bitmap> {
@Override
protected Bitmap doInBackground(String... urls) {
try {
String[] filenames = urls[0].split("/");
filename = filenames[filenames.length-1] + ".jpg";
URL url = new URL(urls[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream inputStream = connection.getInputStream();
return BitmapFactory.decodeStream(inputStream);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
if (bitmap != null)
saveImageToInternalStorage(bitmap);
}
}
}
和我得到的錯誤是:java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.FileOutputStream android.content.Context.openFileOutput(java.lang.String, int)' on a null object reference
。
看起來FileOutputStream fos = openFileOutput(..)
失敗,但不知道爲什麼。
還嘗試在文件名前添加路徑(sdCard.getPath() + "/" +
)。不出所料,它沒有任何區別。
圖像沒問題,我可以在瀏覽器中看到它們。還嘗試使用上傳的圖像 - 而不是生成的圖像,結果相同。
這很奇怪,有沒有人有任何想法?
謝謝!