我在Asynch中拥有所有代码。更具体地说,它是导致此错误的上下文吗?我的logcat指向FileCache,ImageLoader和我的LazyAdapter中的错误。究竟出了什么问题? NullPointerException是如何导致的?
logcat的:
11-29 19:41:38.368: E/AndroidRuntime(1074): FATAL EXCEPTION: main
11-29 19:41:38.368: E/AndroidRuntime(1074): Process: com.example.clinicbooker, PID: 1074
11-29 19:41:38.368: E/AndroidRuntime(1074): java.lang.NullPointerException
11-29 19:41:38.368: E/AndroidRuntime(1074): at com.example.functionalities.FileCache.<init>(FileCache.java:15)
11-29 19:41:38.368: E/AndroidRuntime(1074): at com.example.functionalities.ImageLoader.<init>(ImageLoader.java:33)
11-29 19:41:38.368: E/AndroidRuntime(1074): at com.example.clinicbooker.LazyAdapter.<init>(LazyAdapter.java:31)
11-29 19:41:38.368: E/AndroidRuntime(1074): at com.example.clinicbooker.BookScreen$DownloadXML.onPostExecute(BookScreen.java:93)
11-29 19:41:38.368: E/AndroidRuntime(1074): at com.example.clinicbooker.BookScreen$DownloadXML.onPostExecute(BookScreen.java:1)
11-29 19:41:38.368: E/AndroidRuntime(1074): at android.os.AsyncTask.finish(AsyncTask.java:632)
11-29 19:41:38.368: E/AndroidRuntime(1074): at android.os.AsyncTask.access$600(AsyncTask.java:177)
11-29 19:41:38.368: E/AndroidRuntime(1074): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
11-29 19:41:38.368: E/AndroidRuntime(1074): at android.os.Handler.dispatchMessage(Handler.java:102)
11-29 19:41:38.368: E/AndroidRuntime(1074): at android.os.Looper.loop(Looper.java:137)
11-29 19:41:38.368: E/AndroidRuntime(1074): at android.app.ActivityThread.main(ActivityThread.java:4998)
11-29 19:41:38.368: E/AndroidRuntime(1074): at java.lang.reflect.Method.invokeNative(Native Method)
11-29 19:41:38.368: E/AndroidRuntime(1074): at java.lang.reflect.Method.invoke(Method.java:515)
11-29 19:41:38.368: E/AndroidRuntime(1074): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
11-29 19:41:38.368: E/AndroidRuntime(1074): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
11-29 19:41:38.368: E/AndroidRuntime(1074): at dalvik.system.NativeStart.main(Native Method)
FileCache:
public class FileCache {
private File cacheDir;
public FileCache(Context context){
//Find the dir to save cached images
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"LazyList");
else
cacheDir=context.getCacheDir();
if(!cacheDir.exists())
cacheDir.mkdirs();
}
public File getFile(String url){
//I identify images by hashcode. Not a perfect solution, good for the demo.
String filename=String.valueOf(url.hashCode());
//Another possible solution (thanks to grantland)
//String filename = URLEncoder.encode(url);
File f = new File(cacheDir, filename);
return f;
}
public void clear(){
File[] files=cacheDir.listFiles();
if(files==null)
return;
for(File f:files)
f.delete();
}
}
ImageLoader类:
public class ImageLoader {
MemoryCache memoryCache=new MemoryCache();
FileCache fileCache;
private Map<ImageView, String> imageViews=Collections.synchronizedMap(new WeakHashMap<ImageView, String>());
ExecutorService executorService;
public ImageLoader(Context context){
fileCache=new FileCache(context);
executorService=Executors.newFixedThreadPool(5);
}
final int stub_id = R.drawable.no_image;
public void DisplayImage(String url, ImageView imageView)
{
imageViews.put(imageView, url);
Bitmap bitmap=memoryCache.get(url);
if(bitmap!=null)
imageView.setImageBitmap(bitmap);
else
{
queuePhoto(url, imageView);
imageView.setImageResource(stub_id);
}
}
private void queuePhoto(String url, ImageView imageView)
{
PhotoToLoad p=new PhotoToLoad(url, imageView);
executorService.submit(new PhotosLoader(p));
}
private Bitmap getBitmap(String url)
{
File f=fileCache.getFile(url);
//from SD cache
Bitmap b = decodeFile(f);
if(b!=null)
return b;
//from web
try {
Bitmap bitmap=null;
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is=conn.getInputStream();
OutputStream os = new FileOutputStream(f);
Utils.CopyStream(is, os);
os.close();
bitmap = decodeFile(f);
return bitmap;
} catch (Exception ex){
ex.printStackTrace();
return null;
}
}
//decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f){
try {
//decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f),null,o);
//Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE=70;
int width_tmp=o.outWidth, height_tmp=o.outHeight;
int scale=1;
while(true){
if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
break;
width_tmp/=2;
height_tmp/=2;
scale*=2;
}
//decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {}
return null;
}
//Task for the queue
private class PhotoToLoad
{
public String url;
public ImageView imageView;
public PhotoToLoad(String u, ImageView i){
url=u;
imageView=i;
}
}
class PhotosLoader implements Runnable {
PhotoToLoad photoToLoad;
PhotosLoader(PhotoToLoad photoToLoad){
this.photoToLoad=photoToLoad;
}
@Override
public void run() {
if(imageViewReused(photoToLoad))
return;
Bitmap bmp=getBitmap(photoToLoad.url);
memoryCache.put(photoToLoad.url, bmp);
if(imageViewReused(photoToLoad))
return;
BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad);
Activity a=(Activity)photoToLoad.imageView.getContext();
a.runOnUiThread(bd);
}
}
boolean imageViewReused(PhotoToLoad photoToLoad){
String tag=imageViews.get(photoToLoad.imageView);
if(tag==null || !tag.equals(photoToLoad.url))
return true;
return false;
}
//Used to display bitmap in the UI thread
class BitmapDisplayer implements Runnable
{
Bitmap bitmap;
PhotoToLoad photoToLoad;
public BitmapDisplayer(Bitmap b, PhotoToLoad p){bitmap=b;photoToLoad=p;}
public void run()
{
if(imageViewReused(photoToLoad))
return;
if(bitmap!=null)
photoToLoad.imageView.setImageBitmap(bitmap);
else
photoToLoad.imageView.setImageResource(stub_id);
}
}
public void clearCache() {
memoryCache.clear();
fileCache.clear();
}
}
LazyAdapter:
public class LazyAdapter extends BaseAdapter {
Context context;
HashMap<String, String> resultp = new HashMap<String, String>();
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater = null;
public ImageLoader imageLoader;
public LazyAdapter(Context contextActivity , ArrayList<HashMap<String, String>> d) {
this.context=context;
data=d;
imageLoader=new ImageLoader(context);
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
View vi=convertView;
inflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView=inflater.inflate(R.layout.book_list_row,parent,false);
resultp=data.get(position);
TextView title = (TextView)vi.findViewById(R.id.menu_name);
TextView description = (TextView)vi.findViewById(R.id.address);
TextView bookingDate = (TextView)vi.findViewById(R.id.book_date);
TextView bookingTime = (TextView)vi.findViewById(R.id.book_time);
ImageView thumb_image=(ImageView)vi.findViewById(R.id.list_image);
// Setting all values in listview
title.setText(resultp.get(BookScreen.KEY_TITLE));
description.setText(resultp.get(BookScreen.KEY_ADDRESS));
bookingDate.setText(resultp.get(BookScreen.KEY_DATE));
bookingTime.setText(resultp.get(BookScreen.KEY_TIME));
imageLoader.DisplayImage(resultp.get(BookScreen.KEY_THUMB_URL), thumb_image);
itemView.setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
resultp=data.get(position);
Intent intent=new Intent(context,SingleItemView.class);
intent.putExtra("title",resultp.get(BookScreen.KEY_TITLE));
intent.putExtra("address",resultp.get(BookScreen.KEY_ADDRESS));
intent.putExtra("date",resultp.get(BookScreen.KEY_DATE));
intent.putExtra("time",resultp.get(BookScreen.KEY_TIME));
intent.putExtra("thumbnail",resultp.get(BookScreen.KEY_THUMB_URL));
context.startActivity(intent);
}
});
return vi;
}
}
编辑:在BookScreen类中也有指向DownloadXML方法的错误,我想我可能会在这里说明:
public class BookScreen extends Activity {
//array
ArrayList<HashMap<String, String>> songsList;
ProgressDialog mProgressDialog;
// All static variables
static final String URL = "https://dl.dropboxusercontent.com/u/42241589/test.xml";
// XML node keys
static final String KEY_CLINIC = "clinic"; // parent node
static final String KEY_ID = "id";
static final String KEY_TITLE = "title";
static final String KEY_DATE = "date";
static final String KEY_TIME = "time";
static final String KEY_ADDRESS = "address";
static final String KEY_THUMB_URL = "thumbnail";
ListView list;
LazyAdapter adapter;
@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.book_main);
new DownloadXML().execute();
}
private class DownloadXML extends AsyncTask<Void, Void, Void> {
protected void OnPreExectute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(BookScreen.this);
mProgressDialog.setTitle("List is loading");
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
protected Void doInBackground(Void... params) {
songsList = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML from URL
Document doc = parser.getDomElement(xml); // getting DOM element
try {
NodeList nl = doc.getElementsByTagName(KEY_CLINIC);
// looping through all song nodes <song>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_ID, parser.getValue(e, KEY_ID));
map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
map.put(KEY_DATE, parser.getValue(e, KEY_DATE));
map.put(KEY_TIME, parser.getValue(e, KEY_TIME));
map.put(KEY_ADDRESS, parser.getValue(e, KEY_ADDRESS));
map.put(KEY_THUMB_URL, parser.getValue(e, KEY_THUMB_URL));
// adding HashList to ArrayList
songsList.add(map);
}
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void args) {
list = (ListView) findViewById(R.id.list);
// Getting adapter by passing xml data ArrayList
adapter = new LazyAdapter(BookScreen.this, songsList);
list.setAdapter(adapter);
//Close dialog
mProgressDialog.dismiss();
}
}
}
答案 0 :(得分:0)
LazyAdapter
课程中的这一行会将字段context
分配给自己,并将其保留为空:
this.context=context;
可能你打算:
this.context=contextActivity;
将不正确的null值作为构造函数参数传递给其他类,最终导致空指针异常。
在解决此问题之后,另外,在您的DownloadXML
课程中,您有一个名为OnPreExectute
的方法应该是onPreExecute
。由于此方法初始化mProgressDialog
,并且未调用该字段,因此该字段未初始化。
你真的应该学习如何使用调试器来找到这些东西。我可以从您的例外和代码检查中猜到这一点,但是