Android RequestQueue未初始化

时间:2016-01-18 06:19:17

标签: android networking queue android-volley

我是android新手,目前我想开发一个需要使用凌空请求网络的应用程序。但是,它会返回以下错误:

Caused by: java.lang.IllegalStateException: RequestQueue not initialized
                                                                                             at com.myapp.zeptomobile.myapp.app.StaggeredDemoApplication.getRequestQueue(StaggeredDemoApplication.java:35)
    at com.myapp.zeptomobile.myapp.FlickrActivity.onCreate(FlickrActivity.java:75)
    at android.app.Activity.performCreate(Activity.java:5248)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2164)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2249) 
    at android.app.ActivityThread.access$800(ActivityThread.java:141) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1212) 
    at android.os.Handler.dispatchMessage(Handler.java:102) 
    at android.os.Looper.loop(Looper.java:136) 
    at android.app.ActivityThread.main(ActivityThread.java:5052) 
    at java.lang.reflect.Method.invokeNative(Native Method) 
    at java.lang.reflect.Method.invoke(Method.java:515) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609) 
    at dalvik.system.NativeStart.main(Native Method) 
    01-18 14:07:15.655 24065-24065/com.myapp.zeptomobile.myapp I/Process: Sending signal. PID: 24065 SIG: 9

以下是主程序

enter public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener, FragmentRecent.OnFragmentInteractionListener,
    FragmentAseanGirl.OnFragmentInteractionListener,FragmentFlickrStart.OnFragmentInteractionListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    if (savedInstanceState == null) {
        Fragment fragment = null;
        Class fragmentClass = null;
        fragmentClass = FragmentRecent.class;
        try {
            fragment = (Fragment) fragmentClass.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }

        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
    }

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
}

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();
    Fragment fragment = null;
    Class fragmentClass = null;
    if (id == R.id.nav_camera) {
        fragmentClass = FragmentRecent.class;
    } else if (id == R.id.nav_gallery) {
        fragmentClass = FragmentAseanGirl.class;
    } else if (id == R.id.nav_slideshow) {
        fragmentClass = FragmentRecent.class;
    } else if (id == R.id.nav_manage) {
        fragmentClass = FragmentFlickrStart.class;
    } else if (id == R.id.nav_share) {
        fragmentClass = FragmentRecent.class;
    } else if (id == R.id.nav_send) {
        fragmentClass = FragmentAseanGirl.class;
    }
    try {
        fragment = (Fragment) fragmentClass.newInstance();
    } catch (Exception e) {
        e.printStackTrace();
    }
    FragmentManager fragmentManager = getSupportFragmentManager();
    fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

@Override
public void onFragmentInteraction(Uri uri) {

}
} 

以下是片段计划

public class FragmentFlickrStart extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";

// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;

private OnFragmentInteractionListener mListener;

public FragmentFlickrStart() {
    // Required empty public constructor
}

/**
 * Use this factory method to create a new instance of
 * this fragment using the provided parameters.
 *
 * @param param1 Parameter 1.
 * @param param2 Parameter 2.
 * @return A new instance of fragment FragmentTwo.
 */
// TODO: Rename and change types and number of parameters
public static FragmentFlickrStart newInstance(String param1, String param2) {
    FragmentFlickrStart fragment = new FragmentFlickrStart();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
    }
    Intent intent = new Intent(getActivity(),FlickrActivity.class);
    startActivity(intent);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_flickrstart, container, false);
}

// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
    if (mListener != null) {
        mListener.onFragmentInteraction(uri);
    }
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if (context instanceof OnFragmentInteractionListener) {
        mListener = (OnFragmentInteractionListener) context;
    } else {
        throw new RuntimeException(context.toString()
                + " must implement OnFragmentInteractionListener");
    }
}

@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}

/**
 * This interface must be implemented by activities that contain this
 * fragment to allow an interaction in this fragment to be communicated
 * to the activity and potentially other fragments contained in that
 * activity.
 * <p/>
 * See the Android Training lesson <a href=
 * "http://developer.android.com/training/basics/fragments/communicating.html"
 * >Communicating with Other Fragments</a> for more information.
 */
public interface OnFragmentInteractionListener {
    // TODO: Update argument type and name
    void onFragmentInteraction(Uri uri);
}
} 

以下是活动计划

public class FlickrActivity extends Activity{
private StaggeredGridView mStaggeredView;
private RequestQueue mVolleyQueue;
private ProgressDialog mProgress;
private int currPage=1;
GsonRequest<FlickrResponsePhotos> gsonObjRequest;

private RelativeLayout mListFooter;
private boolean isLoading = false;

private final String TAG_REQUEST = "MY_TAG";


private StaggeredGridView.OnScrollListener scrollListener = new StaggeredGridView.OnScrollListener() {
    public void onTop() {
    }

    public void onScroll() {

    }

    public void onBottom() {
        loadMoreData();
    }
};

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_flickr);

    //actionBarSetup();

    // Initialise Volley Request Queue. added to fix TBS
    if(mVolleyQueue==null){
        mVolleyQueue= Volley.newRequestQueue(getApplicationContext());
    }
    mVolleyQueue = StaggeredDemoApplication.getRequestQueue();
    mListFooter = (RelativeLayout) findViewById(R.id.footer);

    mStaggeredView = (StaggeredGridView) findViewById(R.id.staggeredview);
    // Be sure before calling initialize that you haven't initialised from XML
    //mStaggeredView.initialize(2, StaggeredGridView.Mode.FIXED);
    mStaggeredView.setOnScrollListener(scrollListener);

    showProgress();
    flickerGetImagesRequest();
}

public void onStop() {
    super.onStop();
    if(mProgress != null)
        mProgress.dismiss();
}

private void loadMoreData() {

    if ( isLoading )
        return;

    mListFooter.setVisibility(View.VISIBLE);
    isLoading = true;
    flickerGetImagesRequest();
}


private void flickerGetImagesRequest() {

    String url = "https://api.flickr.com/services/rest";
    Uri.Builder builder = Uri.parse(url).buildUpon();
    builder.appendQueryParameter("api_key", "5e045abd4baba4bbcd866e1864ca9d7b");
    //builder.appendQueryParameter("method", "flickr.interestingness.getList"); //TBS
    builder.appendQueryParameter("method", "flickr.photos.search");
    builder.appendQueryParameter("tags","bikinigirl,lingerine");
    //builder.appendQueryParameter("sort","relevance");
    builder.appendQueryParameter("format", "json");
    builder.appendQueryParameter("nojsoncallback", "1");
    builder.appendQueryParameter("per_page", "10");
    builder.appendQueryParameter("page", Integer.toString(currPage));

    gsonObjRequest = new GsonRequest<FlickrResponsePhotos>(Request.Method.GET, builder.toString(),
            FlickrResponsePhotos.class, null, new Response.Listener<FlickrResponsePhotos>() {
        @Override
        public void onResponse(FlickrResponsePhotos response) {
            try {
                if(response != null) {
                    parseFlickrImageResponse(response);
                    currPage++;
                }
            } catch (Exception e) {
                e.printStackTrace();
                showToast("JSON parse error");
            }
            stopProgress();
        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            // Handle your error types accordingly.For Timeout & No connection error, you can show 'retry' button.
            // For AuthFailure, you can re login with user credentials.
            // For ClientError, 400 & 401, Errors happening on client side when sending api request.
            // In this case you can check how client is forming the api and debug accordingly.
            // For ServerError 5xx, you can do retry or handle accordingly.
            if( error instanceof NetworkError) {
            } else if( error instanceof ClientError) {
            } else if( error instanceof ServerError) {
            } else if( error instanceof AuthFailureError) {
            } else if( error instanceof ParseError) {
            } else if( error instanceof NoConnectionError) {
            } else if( error instanceof TimeoutError) {
            }
            //mStaggeredView.onRefreshComplete();
            stopProgress();
            showToast(error.getMessage());
        }
    });
    gsonObjRequest.setTag(TAG_REQUEST);
    mVolleyQueue.add(gsonObjRequest);
}


private void showProgress() {
    mProgress = ProgressDialog.show(this, "", "Loading...");
}

private void stopProgress() {
    isLoading = false;
    mListFooter.setVisibility(View.GONE);
    mProgress.cancel();
}

private void showToast(String msg) {
    Toast.makeText(FlickrActivity.this, msg, Toast.LENGTH_LONG).show();
}

@TargetApi(Build.VERSION_CODES.GINGERBREAD)
private void parseFlickrImageResponse(FlickrResponsePhotos response) {

    FlickrGetImagesResponse photos = response.getPhotos(); //pass array of images to Picture Activity
    String[] photoUrl;
    photoUrl = new String[photos.getPhotos().size()];
    for (int index = 0; index < photos.getPhotos().size(); index++) {

        FlickrImage flkrImage = photos.getPhotos().get(index);
        photoUrl[index]=flkrImage.getImageUrl();
        StaggeredGridViewItem item = null;
        item = new GridItem(this, flkrImage,photoUrl); //pass one image of index
        mStaggeredView.addItem(item);



       }




    }


} 

以下是队列请求程序

 public class StaggeredDemoApplication extends Application {

private static Context applicationContext;
private static RequestQueue mRequestQueue;
private static ImageLoader mImageLoader;
private static BitmapLruCache mBitmapCache;

public static boolean INIT_FLAG = true;

public void onCreate() {
    super.onCreate();

    applicationContext = this.getApplicationContext();

    mRequestQueue = Volley.newRequestQueue(applicationContext);
    long size = Runtime.getRuntime().maxMemory()/4;
    mBitmapCache = new BitmapLruCache(50);//(int)size);
    mImageLoader = new ImageLoader(mRequestQueue, mBitmapCache);
}

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

}

显示错误的行位于FlickrActivity.java

 mVolleyQueue = StaggeredDemoApplication.getRequestQueue();

以下是我的清单文件

<?xml version="1.0" encoding="utf-8"?>

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".FlickrActivity"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.NoActionBar">
        <intent-filter>
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>
    <activity
        android:name=".FullScreenImageActivity"
        android:screenOrientation="portrait" />
</application>

请建议并帮助......谢谢你!

1 个答案:

答案 0 :(得分:0)

在清单中注册应用程序类名,以避免请求未初始化问题

<application
android:name=".StaggeredDemoApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">