无法启动活动ComponentInfo:尝试调用虚拟方法:' com.android.volley.toolbox.ImageLoader'

时间:2017-05-29 18:17:56

标签: android json listview android-volley android-logcat

我正在尝试创建一个应用程序,我将分享有关电影的评论。在这里,我使用volley从服务器获取数据并将其放入自定义listView。

MainActivity.java

public class MainActivity extends Activity 
{
    private static final String TAG = MainActivity.class.getSimpleName();

    private static final String url = "http://api.androidhive.info/json/movies.json";
    private ProgressDialog pDialog;
    private List<team.mrmalhotra.com.newmalayalamsmscollections.model.Movie> movieList = new ArrayList<team.mrmalhotra.com.newmalayalamsmscollections.model.Movie>();
    private ListView listView;
    private CustomListAdapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (ListView) findViewById(R.id.list);
        adapter = new CustomListAdapter(this, movieList);
        listView.setAdapter(adapter);
        pDialog = new ProgressDialog(this);

        pDialog.setMessage("Loading...");
        pDialog.show();

        getActionBar().setBackgroundDrawable(
                new ColorDrawable(Color.parseColor("#1b1b1b")));

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

                        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"));
                                movie.setRating(((Number) obj.get("rating"))
                                        .doubleValue());
                                movie.setYear(obj.getInt("releaseYear"));

                                JSONArray genreArry = obj.getJSONArray("genre");
                                ArrayList<String> genre = new ArrayList<String>();
                                for (int j = 0; j < genreArry.length(); j++) {
                                    genre.add((String) genreArry.get(j));
                                }
                                movie.setGenre(genre);

                                movieList.add(movie);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }

                        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;
    }
}

LruBitmapCache.java

public class LruBitmapCache extends LruCache<String, Bitmap> implements ImageLoader.ImageCache {
    public static int getDefaultLruCacheSize() {
        final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
        final int cacheSize = maxMemory / 8;
        return cacheSize;
    }
    public LruBitmapCache() {
        this(getDefaultLruCacheSize());
    }
    public LruBitmapCache(int sizeInKiloBytes) {
        super(sizeInKiloBytes);
    }
    @Override
    protected int sizeOf(String key, Bitmap value) {
        return value.getRowBytes() * value.getHeight() / 1024;
    }
    @Override
    public Bitmap getBitmap(String url) {
        return get(url);
    }
    @Override
    public void putBitmap(String url, Bitmap bitmap) {
        put(url, bitmap);
    }
}

Movie.java

public class Movie {
    private String title, thumbnailUrl;
    private int year;
    private double rating;
    private ArrayList<String> genre;

    public Movie() {
    }

    public Movie(String name, String thumbnailUrl, int year, double rating,
            ArrayList<String> genre) {
        this.title = name;
        this.thumbnailUrl = thumbnailUrl;
        this.year = year;
        this.rating = rating;
        this.genre = genre;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String name) {
        this.title = name;
    }

    public String getThumbnailUrl() {
        return thumbnailUrl;
    }

    public void setThumbnailUrl(String thumbnailUrl) {
        this.thumbnailUrl = thumbnailUrl;
    }

    public int getYear() {
        return year;
    }

    public void setYear(int year) {
        this.year = year;
    }

    public double getRating() {
        return rating;
    }

    public void setRating(double rating) {
        this.rating = rating;
    }

    public ArrayList<String> getGenre() {
        return genre;
    }

    public void setGenre(ArrayList<String> genre) {
        this.genre = genre;
    }

}

CustomAdapter

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);
        TextView rating = (TextView) convertView.findViewById(R.id.rating);
        TextView genre = (TextView) convertView.findViewById(R.id.genre);
        TextView year = (TextView) convertView.findViewById(R.id.releaseYear);

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

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

        // title
        title.setText(m.getTitle());

        // rating
        rating.setText("Rating: " + String.valueOf(m.getRating()));

        // genre
        String genreStr = "";
        for (String str : m.getGenre()) {
            genreStr += str + ", ";
        }
        genreStr = genreStr.length() > 0 ? genreStr.substring(0,
                genreStr.length() - 2) : genreStr;
        genre.setText(genreStr);

        // release year
        year.setText(String.valueOf(m.getYear()));

        return convertView;
    }
}

AppController的

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);
        }
    }
}

logcat的

05-29 23:19:30.155 5253-5253/team.mrmalhotra.com.newmalayalamsmscollections I/InstantRun: starting instant run server: is main process
05-29 23:19:30.248 5253-5253/team.mrmalhotra.com.newmalayalamsmscollections D/AndroidRuntime: Shutting down VM
05-29 23:19:30.249 5253-5253/team.mrmalhotra.com.newmalayalamsmscollections E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                              Process: team.mrmalhotra.com.newmalayalamsmscollections, PID: 5253
                                                                                              java.lang.RuntimeException: Unable to start activity ComponentInfo{team.mrmalhotra.com.newmalayalamsmscollections/team.mrmalhotra.com.newmalayalamsmscollections.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'com.android.volley.toolbox.ImageLoader team.mrmalhotra.com.newmalayalamsmscollections.app.AppController.getImageLoader()' on a null object reference
                                                                                                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
                                                                                                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
                                                                                                  at android.app.ActivityThread.access$800(ActivityThread.java:151)
                                                                                                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
                                                                                                  at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                                  at android.os.Looper.loop(Looper.java:135)
                                                                                                  at android.app.ActivityThread.main(ActivityThread.java:5254)
                                                                                                  at java.lang.reflect.Method.invoke(Native Method)
                                                                                                  at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                                                                                                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
                                                                                               Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'com.android.volley.toolbox.ImageLoader team.mrmalhotra.com.newmalayalamsmscollections.app.AppController.getImageLoader()' on a null object reference
                                                                                                  at team.mrmalhotra.com.newmalayalamsmscollections.adater.CustomListAdapter.<init>(CustomListAdapter.java:24)
                                                                                                  at team.mrmalhotra.com.newmalayalamsmscollections.MainActivity.onCreate(MainActivity.java:44)
                                                                                                  at android.app.Activity.performCreate(Activity.java:5990)
                                                                                                  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
                                                                                                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
                                                                                                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
                                                                                                  at android.app.ActivityThread.access$800(ActivityThread.java:151) 
                                                                                                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
                                                                                                  at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                                                  at android.os.Looper.loop(Looper.java:135) 
                                                                                                  at android.app.ActivityThread.main(ActivityThread.java:5254) 
                                                                                                  at java.lang.reflect.Method.invoke(Native Method) 
                                                                                                  at java.lang.reflect.Method.invoke(Method.java:372) 
                                                                                                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
                                                                                                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 
05-29 23:19:31.884 5253-5253/? I/Process: Sending signal. PID: 5253 SIG: 9

的Manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="team.mrmalhotra.com.newmalayalamsmscollections">
<uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

0 个答案:

没有答案