Volley库引发应用程序异常

时间:2014-12-17 08:33:32

标签: android-volley

我在一个应用程序中添加了我的两个独立的android活动,我的一个活动有一个volley库但它给了我一个例外appcontroller(volley库)它的应用程序不是活动请帮帮我

5 个答案:

答案 0 :(得分:0)

Ya,您在清单文件appcontroller类中提到了Application。这解决了例外。

答案 1 :(得分:0)

主要活动:

公共类MainActivity扩展FragmentActivity实现OnTabChangeListener,OnPageChangeListener {

MyPageAdapter pageAdapter;
private ViewPager mViewPager;
private TabHost mTabHost;
private Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mViewPager = (ViewPager) findViewById(R.id.viewpager);

    // Tab Initialization
    initialiseTabHost();

    // Fragments and ViewPager Initialization
    List<Fragment> fragments = getFragments();
    pageAdapter = new MyPageAdapter(getSupportFragmentManager(), fragments);
    mViewPager.setAdapter(pageAdapter);
    mViewPager.setOnPageChangeListener(MainActivity.this);
}

// Method to add a TabHost
private static void AddTab(MainActivity activity, TabHost tabHost, TabHost.TabSpec tabSpec,String message,int picture,Context x) 
{
    tabSpec.setContent(new MyTabFactory(activity));
    View tabIndicator = LayoutInflater.from(x).inflate(R.layout.tab_indicator, tabHost.getTabWidget(), false);
    TextView title = (TextView) tabIndicator.findViewById(R.id.title);
    title.setText(message);

    ImageView icon = (ImageView) tabIndicator.findViewById(R.id.icon);
    icon.setBackgroundDrawable(x.getResources().getDrawable(picture));
    icon.setScaleType(ImageView.ScaleType.FIT_CENTER);
    tabSpec.setIndicator(tabIndicator);
    tabHost.addTab(tabSpec);
}

// Manages the Tab changes, synchronizing it with Pages
public void onTabChanged(String tag) {
    int pos = this.mTabHost.getCurrentTab();
    this.mViewPager.setCurrentItem(pos);

    for(int i=0;i<mTabHost.getTabWidget().getChildCount();i++)
    {
        mTabHost.getTabWidget().getChildAt(i).setBackgroundColor(Color.BLUE);
        //mTabHost.getTabWidget().setDividerDrawable(R.Color.transperant);
    }
    mTabHost.getTabWidget().getChildAt(mTabHost.getCurrentTab()).setBackgroundColor(Color.CYAN);// selected
}

@Override
public void onPageScrollStateChanged(int arg0) {
}
public void destroyItem(View collection, int position, Object view){
    ((ViewPager) collection).removeView((ImageView) view);
}
// Manages the Page changes, synchronizing it with Tabs
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
    int pos = this.mViewPager.getCurrentItem();
    this.mTabHost.setCurrentTab(pos);
}

@Override
    public void onPageSelected(int arg0) {
}

private List<Fragment> getFragments(){
    List<Fragment> fList = new ArrayList<Fragment>();

    // TODO Put here your Fragments
    NewSampleFragment f1 = NewSampleFragment.newInstance(getApplicationContext(),R.layout.newfragment_a);
    MySampleFragment f2 = MySampleFragment.newInstance("Sample Fragment 2");
    MySampleFragment f3 = MySampleFragment.newInstance("Sample Fragment 3");
    MySampleFragment f4 = MySampleFragment.newInstance("Sample Fragment 4");
    MySampleFragment f5 = MySampleFragment.newInstance("Sample Fragment 5");
    fList.add(f1);
    fList.add(f2);
    fList.add(f3);
    fList.add(f4);
    fList.add(f5);
    return fList;
}

// Tabs Creation
private void initialiseTabHost() {
    mTabHost = (TabHost) findViewById(android.R.id.tabhost);
    mTabHost.setup();

    // TODO Put here your Tabs
    MainActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab1").setIndicator("Tab1"),"Grocery",R.drawable.movies,getApplicationContext());
    MainActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab2").setIndicator("Tab2"),"Crockery",R.drawable.artist,getApplicationContext());
    MainActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab3").setIndicator("Tab3"),"Foods",R.drawable.song,getApplicationContext());
    MainActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab3").setIndicator("Tab4"),"Drinks",R.drawable.shopping,getApplicationContext());
    MainActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab3").setIndicator("Tab5"),"Toys",R.drawable.play,getApplicationContext());

    mTabHost.setOnTabChangedListener(this);
}

}

答案 2 :(得分:0)

OfferActivity(按下按钮时应该打开)

公共类OfferActivity扩展了Activity {

private static final String TAG = MainActivity.class.getSimpleName();
private ListView listView;
private FeedListAdapter listAdapter;
private List<FeedItem> feedItems;
private ProgressDialog pDialog;
private String URL_FEED = "http://nusdtech.com/public_html/checking2.php";
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main1);

    listView = (ListView) findViewById(R.id.list);

    feedItems = new ArrayList<FeedItem>();

    listAdapter = new FeedListAdapter(this, feedItems);
    listView.setAdapter(listAdapter);

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

    // These two lines not needed,
    // just to get the look of facebook (changing background color & hiding the icon)
    getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#3b5998")));
    //getActionBar().setIcon(
        //     new ColorDrawable(getResources().getColor(android.R.color.transparent)));

    JsonArrayRequest movieReq = new JsonArrayRequest(URL_FEED,
            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);
                            FeedItem movie = new FeedItem();


                            movie.setId(obj.getInt("id"));
                            movie.setName(obj.getString("name"));

                            // Image might be null sometimes
                            String image = obj.isNull("image") ? null : obj
                                    .getString("image");
                            movie.setImge(image);
                            movie.setStatus(obj.getString("status"));
                            movie.setProfilePic(obj.getString("profilePic"));
                            //movie.setTimeStamp(obj.getString("price"));
                            movie.setPrice(obj.getString("price"));
                            movie.setDate(obj.getString("dates"));

                                feedItems.add(movie);

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

                    }

                    // notifying list adapter about data changes
                    // so that it renders the list view with updated data
                    listAdapter.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) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

}

答案 3 :(得分:0)

AppController的:

public class AppController扩展了Application {

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

private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
LruBitmapCache mLruBitmapCache;

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) {
        getLruBitmapCache();
        mImageLoader = new ImageLoader(this.mRequestQueue, mLruBitmapCache);
    }

    return this.mImageLoader;
}

public LruBitmapCache getLruBitmapCache() {
    if (mLruBitmapCache == null)
        mLruBitmapCache = new LruBitmapCache();
    return this.mLruBitmapCache;
}

public <T> void addToRequestQueue(Request<T> req, String tag) {
    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);
    }
}

}

答案 4 :(得分:0)

包含片段按钮的活动

公共类NewSampleFragment扩展了Fragment {

private static View mView;
private Context con;
public static final NewSampleFragment newInstance(Context con,int layout) {
    NewSampleFragment f = new NewSampleFragment();
    con=con;
    Bundle b = new Bundle();
    b.putInt("mylayout",layout);
    f.setArguments(b);

    return f;
}

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

    int layout = getArguments().getInt("mylayout");
    mView = inflater.inflate(R.layout.newfragment_a, container, false);
    Button button = (Button) mView.findViewById(R.id.bactivity);
    Button offer=(Button) mView.findViewById(R.id.aactivity);
    button.setOnClickListener(new OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            Intent myIntent = new Intent(getActivity(), ListViewDemo.class);
            //Optional parameters
            getActivity().startActivity(myIntent);
            Log.e("Error","Kashif");
        } 
    });  
    offer.setOnClickListener(new OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            startApplication("uzair.sabir.app.OfferActivity");

        } 
    });  
    return mView;
}
public void startApplication(String application_name){
    try{
        Intent intent = new Intent("android.intent.action.MAIN");
        intent.addCategory("android.intent.category.LAUNCHER");

        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
        List<ResolveInfo> resolveinfo_list = getActivity().getPackageManager().queryIntentActivities(intent, 0);

        for(ResolveInfo info:resolveinfo_list){
            if(info.activityInfo.packageName.equalsIgnoreCase(application_name)){
                launchComponent("uzair.sabir.app", "OfferActivity");
                break;
            }
        }
    }
    catch (ActivityNotFoundException e) {
        Toast.makeText(getActivity(), "There was a problem loading the application: "+application_name,Toast.LENGTH_SHORT).show();
        Log.e("Error",e.getMessage());    
    }
}
private void  launchComponent(String packageName, String name){
    Intent launch_intent = new Intent("android.intent.action.MAIN");
    launch_intent.addCategory("android.intent.category.LAUNCHER");
    launch_intent.setComponent(new ComponentName(packageName, name));
    launch_intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    getActivity().startActivity(launch_intent);
}

}