Activity 的 SetAdapter 崩溃原因

SetAdapter Crash Coz of Activity

我的 activity 崩溃了 - 我想这可能是因为我的适配器找不到 activity。我想在 activity 中看到我的 ListView,但我看不到它。

这是我的 HacibabaActivity.java:

package arslan.aybars.menudroid.hacibaba;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.ListView;
import android.widget.Toast;
import arslan.aybars.menudroid.MainActivity;
import arslan.aybars.menudroid.R;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;

    public class HacibabaActivity extends Activity {
        // Log tag
        private static final String TAG = HacibabaActivity.class.getSimpleName();
        // Movies json url
        private static final String url = "http://api.androidhive.info/json/movies.json";
        private ProgressDialog pDialog;
        private List<Movie> movieList = new ArrayList<Movie>();
        private ListView listView;
        private CustomListAdapter adapter;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_hacibaba);

            listView = (ListView) findViewById(R.id.list);
            adapter = new CustomListAdapter(this, movieList);
            listView.setAdapter(adapter);

            pDialog = new ProgressDialog(this);
            // Showing progress dialog before making http request
            pDialog.setMessage("Loading...");
            pDialog.show();

            // changing action bar color
            getActionBar().setBackgroundDrawable(
                    new ColorDrawable(Color.parseColor("#D1D1D4")));

            // Creating volley request obj
            JsonArrayRequest movieReq = new JsonArrayRequest(url,
                    new Response.Listener<JSONArray>() {
                        @Override
                        public void onResponse(JSONArray response) {
                            Log.d(TAG, response.toString());
                            hidePDialog();

                            // Parsing json
                            for (int i = 0; i < response.length(); i++) {
                                try {

                                    JSONObject obj = response.getJSONObject(i);
                                    Movie movie = new Movie();
                                    movie.setTitle(obj.getString("title"));
                                    movie.setThumbnailUrl(obj.getString("image"));

                                    // adding movie to movies array
                                    movieList.add(movie);

                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }

                            }

                            // notifying list adapter about data changes
                            // so that it renders the list view with updated data
                            adapter.notifyDataSetChanged();
                        }
                    }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            VolleyLog.d(TAG, "Error: " + error.getMessage());
                            hidePDialog();
                        }
                    });

            // Adding request to request queue
            AppController.getInstance().addToRequestQueue(movieReq);
        }

        @Override
        public void onDestroy() {
            super.onDestroy();
            hidePDialog();
        }

        private void hidePDialog() {
            if (pDialog != null) {
                pDialog.dismiss();
                pDialog = null;
            }
        }   
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.main, menu);
            return true;
        }
    }

这是我的适配器:

package arslan.aybars.menudroid.hacibaba;

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import arslan.aybars.menudroid.R;

import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;

public class CustomListAdapter extends BaseAdapter {
    private Activity activity;
    private LayoutInflater inflater;
    private List<Movie> movieItems;
    ImageLoader imageLoader = AppController.getInstance().getImageLoader();

    public CustomListAdapter(Activity activity, List<Movie> movieItems) {
        this.activity = activity;
        this.movieItems = movieItems;
    }

    @Override
    public int getCount() {
        return movieItems.size();
    }

    @Override
    public Object getItem(int location) {
        return movieItems.get(location);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        if (inflater == null)
            inflater = (LayoutInflater) activity
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (convertView == null)
            convertView = inflater.inflate(R.layout.list_row, null);

        if (imageLoader == null)
            imageLoader = AppController.getInstance().getImageLoader();
        NetworkImageView thumbNail = (NetworkImageView) convertView
                .findViewById(R.id.thumbnail);
        TextView title = (TextView) convertView.findViewById(R.id.title);

        // getting movie data for the row
        Movie m = movieItems.get(position);

        // thumbnail image
        thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);
        // title

        title.setText(m.getTitle());
        return convertView;
    }
}

这是 LogCat 给我的错误:

01-13 03:18:56.470: D/AndroidRuntime(4970): Shutting down VM
01-13 03:18:56.470: W/dalvikvm(4970): threadid=1: thread exiting with uncaught exception (group=0xa4b62648)
01-13 03:18:56.474: E/AndroidRuntime(4970): FATAL EXCEPTION: main
01-13 03:18:56.474: E/AndroidRuntime(4970): java.lang.RuntimeException: Unable to start activity ComponentInfo{arslan.aybars.menudroid/arslan.aybars.menudroid.hacibaba.HacibabaActivity}: java.lang.NullPointerException
01-13 03:18:56.474: E/AndroidRuntime(4970):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
01-13 03:18:56.474: E/AndroidRuntime(4970):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
01-13 03:18:56.474: E/AndroidRuntime(4970):     at android.app.ActivityThread.access0(ActivityThread.java:141)
01-13 03:18:56.474: E/AndroidRuntime(4970):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
01-13 03:18:56.474: E/AndroidRuntime(4970):     at android.os.Handler.dispatchMessage(Handler.java:99)
01-13 03:18:56.474: E/AndroidRuntime(4970):     at android.os.Looper.loop(Looper.java:137)
01-13 03:18:56.474: E/AndroidRuntime(4970):     at android.app.ActivityThread.main(ActivityThread.java:5103)
01-13 03:18:56.474: E/AndroidRuntime(4970):     at java.lang.reflect.Method.invokeNative(Native Method)
01-13 03:18:56.474: E/AndroidRuntime(4970):     at java.lang.reflect.Method.invoke(Method.java:525)
01-13 03:18:56.474: E/AndroidRuntime(4970):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
01-13 03:18:56.474: E/AndroidRuntime(4970):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
01-13 03:18:56.474: E/AndroidRuntime(4970):     at dalvik.system.NativeStart.main(Native Method)
01-13 03:18:56.474: E/AndroidRuntime(4970): Caused by: java.lang.NullPointerException
01-13 03:18:56.474: E/AndroidRuntime(4970):     at arslan.aybars.menudroid.hacibaba.CustomListAdapter.<init>(CustomListAdapter.java:21)
01-13 03:18:56.474: E/AndroidRuntime(4970):     at arslan.aybars.menudroid.hacibaba.HacibabaActivity.onCreate(HacibabaActivity.java:45)
01-13 03:18:56.474: E/AndroidRuntime(4970):     at android.app.Activity.performCreate(Activity.java:5133)
01-13 03:18:56.474: E/AndroidRuntime(4970):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
01-13 03:18:56.474: E/AndroidRuntime(4970):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
01-13 03:18:56.474: E/AndroidRuntime(4970):     ... 11 more

AppController.class

package arslan.aybars.menudroid.hacibaba;

import android.app.Application;
import android.text.TextUtils;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;

public class AppController extends Application {

    public static final String TAG = AppController.class.getSimpleName();

    private RequestQueue mRequestQueue;
    private ImageLoader mImageLoader;

    private static AppController mInstance;

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
    }

    public static synchronized AppController getInstance() {
        return mInstance;
    }

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }

        return mRequestQueue;
    }

    public ImageLoader getImageLoader() {
        getRequestQueue();
        if (mImageLoader == null) {
            mImageLoader = new ImageLoader(this.mRequestQueue,
                    new LruBitmapCache());
        }
        return this.mImageLoader;
    }

    public <T> void addToRequestQueue(Request<T> req, String tag) {
        // set the default tag if tag is empty
        req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
        getRequestQueue().add(req);
    }

    public <T> void addToRequestQueue(Request<T> req) {
        req.setTag(TAG);
        getRequestQueue().add(req);
    }

    public void cancelPendingRequests(Object tag) {
        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(tag);
        }
    }
}

我 运行 应用程序在这里崩溃了:adapter = new CustomListAdapter(this, movieList);

我不知道该怎么做。我需要使用 asynTask 还是什么?

看起来问题出在您的适配器中的这一行:

ImageLoader imageLoader = AppController.getInstance().getImageLoader();

getInstance() 返回 null,看起来您的 AppController 中的 mInstance 尚未初始化。

您是否在 Manifest.xml 文件中指定了自定义应用程序 class 的名称?

<application android:icon="@drawable/icon" android:label="@string/app_name"
android:name="arslan.aybars.menudroid.hacibaba.AppController">