简体   繁体   中英

unable to instantiate activity componentinfo (Volley)

I would like to implement Android volley so followed these examples 1 2 :

project compiles with no error But HTTP request is not fired and android throws this error:

07-05 06:33:09.596: E/AndroidRuntime(1943): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.testsite.testvolley/com.testsite.testvolley.MainActivity}: java.lang.NullPointerException

MainActivity:

package com.testsite.testvolley;

import com.android.volley.Request.Method;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.testsite.testvolley.MyVolley;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {

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

        RequestQueue queue = MyVolley.getRequestQueue();
        StringRequest myReq = new StringRequest(Method.GET, 
                                                "http://www.google.com/",
                                                createMyReqSuccessListener(),
                                                createMyReqErrorListener());

        queue.add(myReq);

    }

    TextView tv = (TextView) findViewById(R.id.textView1);

    private Response.Listener<String> createMyReqSuccessListener() {
        return new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                tv.setText(response);
            }
        };
    }


    private Response.ErrorListener createMyReqErrorListener() {
        return new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                tv.setText(error.getMessage());
            }
        };
    }

}

MyVolley.java:

package com.testsite.testvolley;

import android.content.Context;
import android.app.ActivityManager;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
import com.testsite.testvolley.BitmapLruCache;

public class MyVolley {
    private static RequestQueue mRequestQueue;
    private static ImageLoader mImageLoader;


    private MyVolley() {
        // no instances
    }


    static void init(Context context) {
        mRequestQueue = Volley.newRequestQueue(context);

        int memClass = ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE))
                .getMemoryClass();
        // Use 1/8th of the available memory for this memory cache.
        int cacheSize = 1024 * 1024 * memClass / 8;
        mImageLoader = new ImageLoader(mRequestQueue, new BitmapLruCache(cacheSize));
    }


    public static RequestQueue getRequestQueue() {
        if (mRequestQueue != null) {
            return mRequestQueue;
        } else {
            throw new IllegalStateException("RequestQueue not initialized");
        }
    }

    public static ImageLoader getImageLoader() {
        if (mImageLoader != null) {
            return mImageLoader;
        } else {
            throw new IllegalStateException("ImageLoader not initialized");
        }
    }
}

BitmapLruCache.java:

package com.testsite.testvolley;

import android.graphics.Bitmap;
import android.support.v4.util.LruCache;

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

public class BitmapLruCache extends LruCache<String, Bitmap> implements ImageCache {
    public BitmapLruCache(int maxSize) {
        super(maxSize);
    }


    @Override
    protected int sizeOf(String key, Bitmap value) {
        return value.getRowBytes() * value.getHeight();
    }


    @Override
    public Bitmap getBitmap(String url) {
        return get(url);
    }


    @Override
    public void putBitmap(String url, Bitmap bitmap) {
        put(url, bitmap);
    }
}

Android Manifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.testsite.testvolley"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.testsite.testvolley.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.testsite.testvolley.MyVolley"
            android:label="@string/app_name" >
        </activity>
        <activity
            android:name="com.testsite.testvolley.BitmapLruCache"
            android:label="@string/app_name" >
        </activity>
    </application>

</manifest>

I checked the volley.jar file is also included in Buildpath. Anybody can point out what i am still missing ?

EDIT: LogCat:

    07-05 07:25:06.755: E/AndroidRuntime(1933): FATAL EXCEPTION: main
07-05 07:25:06.755: E/AndroidRuntime(1933): Process: com.testsite.testvolley, PID: 1933
07-05 07:25:06.755: E/AndroidRuntime(1933): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.testsite.testvolley/com.testsite.testvolley.MainActivity}: java.lang.IllegalStateException: RequestQueue not initialized
07-05 07:25:06.755: E/AndroidRuntime(1933):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
07-05 07:25:06.755: E/AndroidRuntime(1933):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
07-05 07:25:06.755: E/AndroidRuntime(1933):     at android.app.ActivityThread.access$800(ActivityThread.java:135)
07-05 07:25:06.755: E/AndroidRuntime(1933):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
07-05 07:25:06.755: E/AndroidRuntime(1933):     at android.os.Handler.dispatchMessage(Handler.java:102)
07-05 07:25:06.755: E/AndroidRuntime(1933):     at android.os.Looper.loop(Looper.java:136)
07-05 07:25:06.755: E/AndroidRuntime(1933):     at android.app.ActivityThread.main(ActivityThread.java:5017)
07-05 07:25:06.755: E/AndroidRuntime(1933):     at java.lang.reflect.Method.invokeNative(Native Method)
07-05 07:25:06.755: E/AndroidRuntime(1933):     at java.lang.reflect.Method.invoke(Method.java:515)
07-05 07:25:06.755: E/AndroidRuntime(1933):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
07-05 07:25:06.755: E/AndroidRuntime(1933):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
07-05 07:25:06.755: E/AndroidRuntime(1933):     at dalvik.system.NativeStart.main(Native Method)
07-05 07:25:06.755: E/AndroidRuntime(1933): Caused by: java.lang.IllegalStateException: RequestQueue not initialized
07-05 07:25:06.755: E/AndroidRuntime(1933):     at com.testsite.testvolley.MyVolley.getRequestQueue(MyVolley.java:36)
07-05 07:25:06.755: E/AndroidRuntime(1933):     at com.testsite.testvolley.MainActivity.onCreate(MainActivity.java:24)
07-05 07:25:06.755: E/AndroidRuntime(1933):     at android.app.Activity.performCreate(Activity.java:5231)
07-05 07:25:06.755: E/AndroidRuntime(1933):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
07-05 07:25:06.755: E/AndroidRuntime(1933):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
07-05 07:25:06.755: E/AndroidRuntime(1933):     ... 11 more

i'm also facing the same problem... but i fixed it by using another class that extends Application (App_VolleyExample.java) ...

public class App_VolleyExamples extends Application {

    private static Context applicationContext;
    @Override
    public void onCreate() {
        super.onCreate();

        applicationContext = this.getApplicationContext();
        MyVolley.init(applicationContext);

    }

and the most important thing... you have to declare in manifest (under application ) as well

<application
        android:name="com.xxx.App_VolleyExamples"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
    .....
</application>

In my case i solved like this. Hope this help.

The problem is you set textview findViewById outside of onCreate method.So,Initialize textview in method of activity not in activity class. ie Change

public class MainActivity extends Activity {

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

        RequestQueue queue = MyVolley.getRequestQueue();
        StringRequest myReq = new StringRequest(Method.GET, 
                                                "http://www.google.com/",
                                                createMyReqSuccessListener(),
                                                createMyReqErrorListener());

        queue.add(myReq);

    }

    TextView tv = (TextView) findViewById(R.id.textView1);

to

public class MainActivity extends Activity {
      TextView tv; 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv = (TextView) findViewById(R.id.textView1);

RequestQueue queue = MyVolley.getRequestQueue(this);
        StringRequest myReq = new StringRequest(Method.GET, 
                                                "http://www.google.com/",
                                                createMyReqSuccessListener(),
                                                createMyReqErrorListener());

        queue.add(myReq);


    }

Edit

You did not initialize volley's request queue,so first initialize it. so change this

  public static RequestQueue getRequestQueue() {
        if (mRequestQueue != null) {
            return mRequestQueue;
        } else {
            throw new IllegalStateException("RequestQueue not initialized");
        }
    }

to

public static RequestQueue getRequestQueue(Context mContext) {
    if (mRequestQueue == null) {
        mRequestQueue = Volley.newRequestQueue(mContext);  
    } 
    return mRequestQueue;
}

and change

    RequestQueue queue = MyVolley.getRequestQueue();

to

RequestQueue queue = MyVolley.getRequestQueue(this);

in OnCreate method of activity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM