我正在创建一个正在下载文件的应用,然后将其加载到imageview但我收到此错误
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageBitmap(android.graphics.Bitmap)' on a null object reference
这是我的下载代码
class DownloadFileFromURL extends AsyncTask<String, String, String> {
// Show Progress bar before downloading Music
@Override
protected void onPreExecute() {
super.onPreExecute();
// Shows Progress Bar Dialog and then call doInBackground method
showDialog(progress_bar_type);
}
// Download File from Internet
@Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// Get Music file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(),10*1024);
// Output stream to write file in SD card
int imageNr = sharedPreferences.getInt("ImageNr", 1);
OutputStream output = new FileOutputStream(getApplicationInfo().dataDir+"/files/"+imageNr+".jpg");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
output.write(data, 0, count);
total += count;
// Publish the progress which triggers onProgressUpdate method
publishProgress("" + (total));
// Write data to file
}
// Flush output
output.flush();
// Close streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
// While Downloading Music File
protected void onProgressUpdate(String... progress) {
// Set progress percentage
prgDialog.setProgress(Integer.parseInt(progress[0]));
}
// Once File is downloaded
@Override
protected void onPostExecute(String file_url) {
// Dismiss the dialog after the Music file was downloaded
dismissDialog(progress_bar_type);
int imageNr = sharedPreferences.getInt("ImageNr", 1);
File imgFile = new File(getApplicationInfo().dataDir+"/files/"+imageNr+".jpg");
imageNr++;
SharedPreferences.Editor editorsave = sharedPreferences.edit();
editorsave.putInt("ImageNr", imageNr);
editorsave.apply();
if(imgFile.exists()){
Toast.makeText(getApplicationContext(), "Bild laddad!", Toast.LENGTH_LONG).show();
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
imageView.setImageBitmap(myBitmap);
}else{
Toast.makeText(getApplicationContext(), "Bild ej hittad!", Toast.LENGTH_LONG).show();
}
// Do stuff here
}
}
是的,它使用了一些弃用的代码,但这在我的其他应用程序中对我有用,虽然我没有在那个中使用位图,但是AsyncTask有效。
答案 0 :(得分:1)
您的imageView
为空
远离异常本身
if(imgFile.exists() && imageView != null) {
....
检查您的imageView
参考分配。似乎没有正确分配imageView
引用,因此返回null