Click here to Skip to main content
15,895,011 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Java
public class ProductListActivity extends NavigationDrawerActivity
{

    private final String TAG = ProductListActivity.class.getSimpleName();
    private SectionsPagerAdapter mSectionsPagerAdapter;
    private ViewPager mViewPager;
    private ImageLoader imageLoader;
    private int lastTop = 0;
    private ProgressDialog mProgressDialog;
    private ArrayList<String> tabContent;
    private Context context;
    private CharSequence[] mMerchantCategoryName;
    private ArrayList<MasterCategory> categoriesList;
    private MasterCategory category;

    private ArrayList<Product> mMerchantProducts;

    private ArrayList<MasterCategory> mMerchantCategories;
    private HashMap<Integer, ArrayList<MasterCategory>> mMerchantSubCategories;
    private HashMap<Integer, ArrayList<MasterCategory>> mMerchantSubSubCategories;
    private HashMap<Integer, ArrayList<MasterCategory>> mMerchantSuperSubCategories;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isViewPagerPresent = true;

        isViewPagerWithParalexPresent = true;
       super.onCreate(savedInstanceState);
        getWindow().setWindowAnimations(0);
       // setToolbarTitle("My Products");
        if (!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().register(this);
        context = this;
        initialiseUI();
        getMasterCategory();
    }

    public void initialiseUI()
    {
        imageLoader = Global.getInstance().getImageLoader();
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
        mViewPager = (ViewPager) findViewById(R.id.pager);
        //showSubCategoryTabs();
    }

    private void getMasterCategoryFromServer()
    {
        if(null == AmodaMerchantUser.getInstance().getMerchantCategories())
        {
            MerchantCategoryRequest merchantCategoryRequest = new MerchantCategoryRequest();
            ArrayList<Category> categories = AmodaMerchantUser.getInstance().getMerchantProfile().getVendorCategoryList();
            if (null != categories)
            {
                ArrayList<String> categoryIds = new ArrayList<>();
                for (int i = 0; i < categories.size(); i++)
                {
                    categoryIds.add("" + categories.get(i).getId());
                }

                merchantCategoryRequest.setCategoryIds(TextUtils.join(", ", categoryIds));
                merchantCategoryRequest.setMerchantId(AmodaMerchantUser.getInstance().getMerchantProfile().getMerchantId());
                if(null == mProgressDialog)
                    mProgressDialog = UIHelper.showProgressDialog(this, "One moment Please...", false, true);
                new WebServicesManager().getMerchantCategoryList(merchantCategoryRequest);
            }
        }
    }

    private void getMasterCategory()
    {
        /*mProgressDialog = UIHelper.showProgressDialog(this, "Please Wait...", false, true);
        MerchantCategoryRequest merchantCategoryRequest = new MerchantCategoryRequest();
        ArrayList<Category> categories = AmodaMerchantUser.getInstance().getMerchantProfile().getVendorCategoryList();
        ArrayList<String> categoryIds = new ArrayList<>();
        for (int i = 0; i < categories.size(); i++) {
            categoryIds.add("" + categories.get(i).getId());
        }

        merchantCategoryRequest.setCategoryIds(TextUtils.join(", ", categoryIds));
        merchantCategoryRequest.setMerchantId(AmodaMerchantUser.getInstance().getMerchantProfile().getMerchantId());
        new WebServicesManager().getMerchantCategoryList(merchantCategoryRequest);*/
        //mMerchantCategories         = AmodaMerchantUser.getInstance().getMerchantCategories();
        mMerchantSubCategories      = AmodaMerchantUser.getInstance().getMerchantSubCategories();
        mMerchantSubSubCategories   = AmodaMerchantUser.getInstance().getMerchantSubSubCategories();
        mMerchantSuperSubCategories = AmodaMerchantUser.getInstance().getMerchantSuperSubCategories();
        categoriesList = AmodaMerchantUser.getInstance().getMerchantCategories();

        if(null == categoriesList)
        {
            /*UIHelper.showOneButtonAlert(this, "Alert", "Your Profile expired. Please try again.", "OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    onBackPressed();
                }
            }, false);*/
            getMerchantProfile(PreferencesManager.getMerchantId());
        }
        else
        {
            mMerchantCategories = categoriesList;
            category = categoriesList.get(0);
            createCategoryHashTable();
            showSubCategoryTabs();
        }

    }

    private void getMerchantProfile(int merchantID)
    {
        mProgressDialog = UIHelper.showProgressDialog(this, "Profile expired, synchronising with server", false, true);
        new WebServicesManager().getMerchantProfile(new RequestManager().getMerchantProfileRequest(merchantID));
    }

    public void onEvent(MerchantProfileResponse merchantProfileResponse)
    {
        if (merchantProfileResponse != null && merchantProfileResponse.getStatusCode() == Constants.Merchant.HttpResponse.SUCCESS)
        {
            removePreviousProfile();
            DatabaseManager.MerchantProfileManager merchantProfileManager = new DatabaseManager().new MerchantProfileManager(this);
            merchantProfileManager.insertMerchantInDB(merchantProfileResponse);
            AmodaMerchantUser.getInstance().setMerchantProfile(merchantProfileResponse);
            PreferencesManager.setMerchantId(merchantProfileResponse.getMerchantId());
            getMasterCategoryFromServer();
        }
        else
        {
            UIHelper.stopProgressDialog(mProgressDialog);
            logoutUser();
        }
    }

    public void onEvent(MerchantCategoryResponse merchantCategoryResponse)
    {
        UIHelper.stopProgressDialog(mProgressDialog);
        if (Constants.Merchant.HttpResponse.SUCCESS == merchantCategoryResponse.getStatusCode())
        {
            AmodaMerchantUser.getInstance().createCategoryHashTable(merchantCategoryResponse.getCategoriesList());
            mMerchantSubCategories      = AmodaMerchantUser.getInstance().getMerchantSubCategories();
            mMerchantSubSubCategories   = AmodaMerchantUser.getInstance().getMerchantSubSubCategories();
            mMerchantSuperSubCategories = AmodaMerchantUser.getInstance().getMerchantSuperSubCategories();
            categoriesList = AmodaMerchantUser.getInstance().getMerchantCategories();
            mMerchantCategories = categoriesList;
            category = categoriesList.get(0);
            createCategoryHashTable();
            showSubCategoryTabs();
        }
        else
        {
            logoutUser();
        }
    }

    private void logoutUser()
    {
        Toast.makeText(this, "Can not synchronise with server, please login again.", Toast.LENGTH_SHORT).show();
        new WebServicesManager().merchantLogout(new RequestManager().getMerchantLogoutRequest(PreferencesManager.getMerchantId()));
        clearUserDataOnLogout();
        Intent intent = new Intent(this, BaseFragmentActivity.class);
        intent.putExtra("toolbarTitle", Constants.Merchant.ToolbarTitle.LOGIN);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        intent.putExtra("FragmentClassName", LoginFragment.class.getName());
        intent.putExtra("isLogin", true);
        startActivity(intent);
        finish();
    }

    private void removePreviousProfile()
    {
        DatabaseManager.MerchantProfileManager merchantProfileManager = new DatabaseManager().new MerchantProfileManager(this);
        Merchant merchantProfiles;
        long retVal = -1;
        do
        {
            merchantProfiles = merchantProfileManager.getMerchantProfile();
            if(null!= merchantProfiles)
                retVal = merchantProfileManager.deleteMerchantById(merchantProfiles);
        }while(null != merchantProfiles && retVal > 0);
    }

    /*public void onEvent(MerchantCategoryResponse merchantCategoryResponse) {
        UIHelper.stopProgressDialog(mProgressDialog);
        if (Constants.Merchant.HttpResponse.SUCCESS == merchantCategoryResponse.getStatusCode()) {
            categoriesList = merchantCategoryResponse.getCategoriesList();
            mMerchantCategories =  categoriesList;
            category = categoriesList.get(0);
            createCategoryHashTable();
            showSubCategoryTabs();
        } else {
           UIHelper.showOneButtonAlert(this, "Alert", "Merchant category details not found", "OK", null);
        }
    }*/

    private void showSubCategoryTabs()
    {
        setToolbarTitle(category != null ? category.getName() : "");
        try
        {
            mPromotionalImage.setDefaultImageResId(R.drawable.nodeals_img);
            mPromotionalImage.setImageUrl(category.getImageUrl(), imageLoader);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        tabContent = new ArrayList<String>();

        for (MasterCategory subCategories : category.getCategories()) {
            /*Check if the sub-sub category has super-sub category or not.*/
            if (null != subCategories.getCategories())
                tabContent.add(subCategories.getName());
        }

        mViewPager.setAdapter(mSectionsPagerAdapter);
        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
        tabLayout.setupWithViewPager(mViewPager);

        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener()
        {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
            {

            }

            @Override
            public void onPageSelected(int position) 
           {
                // callCategory.get(position).sendCategoryResponse();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    public class SectionsPagerAdapter extends FragmentStatePagerAdapter
    {
        public SectionsPagerAdapter(FragmentManager fm)
        {
            super(fm);
        }

        @Override
        public Fragment getItem(int position)
        {
            MasterCategory subCategories = category.getCategories().get(position);
            if (subCategories.isHasChildCategory())
            {
                SubCategoryFragment subCategoryFragment = new SubCategoryFragment();
                Bundle bundle = new Bundle();
                bundle.putSerializable("iconImageURL", category.getIconImageUrl());
                bundle.putSerializable("data", category.getCategories().get(position));
                subCategoryFragment.setArguments(bundle);
                return subCategoryFragment;
            }
            else
            {
                SubCategoryProductsFragment subCategoryProductsFragment = new SubCategoryProductsFragment();
                Bundle bundle = new Bundle();
                bundle.putInt("categoryId", subCategories.getCategoryId());
                bundle.putString("categoryName", subCategories.getName());
                bundle.putBoolean("isSubCatProducts", true);
                subCategoryProductsFragment.setArguments(bundle);
                return subCategoryProductsFragment;
            }
        }

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

        @Override
        public CharSequence getPageTitle(int position) {
            Locale l = Locale.getDefault();
            return tabContent.get(position);
        }
    }

    @Override
    public void onResume()
    {
        if (!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().register(this);
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    public void onStop()
    {
        super.onStop();
        //*Unregister event bus when the app goes in background*//*
        if (EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().unregister(this);
    }


    @Override
    public void onDestroy()
    {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().unregister(this);
    }

    public void onError(VolleyError volleyError) {
        UIHelper.stopProgressDialog(mProgressDialog);
        Functions.Application.VolleyErrorCheck(this, volleyError);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        getMenuInflater().inflate(R.menu.menu_category_change, menu);
        MenuItem categoryMenuItem = menu.findItem(R.id.category);
        boolean visible;
        if (null != categoriesList && categoriesList.size() > 1)
        {
            visible = true;
        }
        else
        {
            visible = false;
        }
        categoryMenuItem.setVisible(visible);
        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId())
        {
            case R.id.category:
                displayCategories();
                break;

            case R.id.add_product:
                Intent addProductIntent = new Intent(this, BaseFragmentActivity.class);
                addProductIntent.putExtra("Categories", mMerchantCategories);
                addProductIntent.putExtra("SubCategories", mMerchantSubCategories);
                addProductIntent.putExtra("SubSubCategories", mMerchantSubSubCategories);
                addProductIntent.putExtra("SuperSubCategories", mMerchantSuperSubCategories);
                addProductIntent.putExtra("FragmentClassName", AddProductFragment.class.getName());
                startActivity(addProductIntent);
                break;

              /*  CustomDialogAddProductOption addproduct=new CustomDialogAddProductOption(context,mMerchantCategories,mMerchantSubCategories,mMerchantSubSubCategories,mMerchantSuperSubCategories);
                addproduct.show();
*/
            case R.id.changeproductprice:
                changeproductprice();
                break;

            default:
                return super.onOptionsItemSelected(item);
        }
        return true;
    }

    public void displayCategories()
    {

        getMasterCategoryFromServer();

        if (!categoriesList.isEmpty())
        {

            mMerchantCategoryName = new String[categoriesList.size()];
            for (int i = 0; i < categoriesList.size(); i++)
            {
                mMerchantCategoryName[i] = categoriesList.get(i).getName();
            }
            AlertDialog.Builder builder = new AlertDialog.Builder(context);

            builder.setTitle("Select Category");

            builder.setItems(mMerchantCategoryName, new DialogInterface.OnClickListener()
            {
                public void onClick(DialogInterface dialog, int item)
                {

                   category = categoriesList.get(item);
                    showSubCategoryTabs();
                }
            });

            builder.setNegativeButton("Cancel", null);
            AlertDialog alert = builder.create();
            alert.show();
        }
    }

    private void createCategoryHashTable()
    {
        mMerchantSubCategories = new HashMap<>();
        mMerchantSubSubCategories = new HashMap<>();
        mMerchantSuperSubCategories = new HashMap<>();
        if (null != mMerchantCategories)
        {
            /*Get merchant's sub-category from database*/
            for (int i = 0; i < mMerchantCategories.size(); i++)
            {
                try
                {
                    mMerchantSubCategories.put(mMerchantCategories.get(i).getCategoryId(), mMerchantCategories.get(i).getCategories());
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
            /*Get merchant's sub-sub-category from database*/
            for (int i = 0; i < mMerchantSubCategories.size(); i++) {
                for (int j = 0; j < mMerchantSubCategories.get(mMerchantCategories.get(i).getCategoryId()).size(); j++) {
                    try {
                        mMerchantSubSubCategories.put(mMerchantSubCategories.get(mMerchantCategories.get(i).getCategoryId()).get(j).getCategoryId(),
                                mMerchantSubCategories.get(mMerchantCategories.get(i).getCategoryId()).get(j).getCategories());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }


            }
            /*Get merchant's super-sub-category from database*/
            for (int subCategoryId = 0; subCategoryId < mMerchantSubCategories.size(); subCategoryId++) {
                for (int i = 0; i < mMerchantCategories.get(subCategoryId).getCategories().size(); i++) {
                    for (int j = 0; j < mMerchantSubSubCategories.get(mMerchantCategories.get(subCategoryId).getCategories().get(i).getCategoryId()).size(); j++) {
                        try {
                            mMerchantSuperSubCategories.put(mMerchantSubSubCategories.get(mMerchantCategories.get(subCategoryId).getCategories().get(i).getCategoryId()).get(j).getCategoryId(),
                                    mMerchantSubSubCategories.get(mMerchantCategories.get(subCategoryId).getCategories().get(i).getCategoryId()).get(j).getCategories());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }

    public void changeproductprice()
    {
        new WebServicesManager().UpdateProductPrice(new RequestManager().getUpdateProductPriceRequest(AmodaMerchantUser.getInstance().getMerchantProfile().getMerchantId()));
        Toast.makeText(context,"Email sent successfully",Toast.LENGTH_LONG).show();
    }
}


What I have tried:

I tried solving the null pointer exception . I created a dialog and then gave it two options of which if user clicks on one of the options then the fragment will load . Inside the fragment instead of assigning direct values to the fragment as shown above,I fetched the data directly from another java class.
Posted
Updated 26-Jun-16 23:51pm

1 solution

This is one of the most common problems we get asked, and it's also the one we are least equipped to answer, but you are most equipped to answer yourself.

Let me just explain what the error means: You have tried to use a variable, property, or a method return value but it contains null - which means that there is no instance of a class in the variable.
It's a bit like a pocket: you have a pocket in your shirt, which you use to hold a pen. If you reach into the pocket and find there isn't a pen there, you can't sign your name on a piece of paper - and you will get very funny looks if you try! The empty pocket is giving you a null value (no pen here!) so you can't do anything that you would normally do once you retrieved your pen. Why is it empty? That's the question - it may be that you forgot to pick up your pen when you left the house this morning, or possibly you left the pen in the pocket of yesterdays shirt when you took it off last night.

We can't tell, because we weren't there, and even more importantly, we can't even see your shirt, much less what is in the pocket!

Back to computers, and you have done the same thing, somehow - and we can't see your code, much less run it and find out what contains null when it shouldn't.
But you can - and your IDE of choice will help you here. Run your program in the debugger and when it fails, it will show you the line it found the problem on. You can then start looking at the various parts of it to see what value is null and start looking back through your code to find out why. So put a breakpoint at the beginning of the method containing the error line, and run your program from the start again. This time, VS will stop before the error, and let you examine what is going on by stepping through the code looking at your values.

But we can't do that - we don't have your code, we don't know how to use it if we did have it, we don't have your data. So try it - and see how much information you can find out!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900