Android: Fragments and menus. Remove when not needed

So after a long long time there is a post on android. Starting today I will post atleast one trick per week that may ease your day to day android development task.

Before I start my first trick, I am assuming you are already familiar with fragments development in android and already know about action items. If not I suggest you head first to this android guide .

When developing with fragments where your fragments needs to have some specific menus we already use


and than we override needed methods to work with menus right? This is the way to add menus to activity from fragments.

But what if we want to open a new fragment B from our already opened fragment A and our newly opened fragment does not need a menu. And letting menu from fragment A be visible can lead to some serious issues. In such cases we can not let such menus be visible right?

Unfortunately fragments have sort of one-way communications with activity when it comes for menus. Fragments can add any menus they like. But can not remove if they don’t need. Without calling setHasOptionsMenu we can not get callback to fragments method. And we are not doing in fragment B because it’s not needed there. Thus we are helpless here right?..

No fortunately fragments api is not a one-way communication as long as parent activity or any other fragment is involved. In our case we can do the following.

1. When adding fragment B from fragment A. add this line in frag A.


Here targetCode can be anything you like. It can work like startActivityForResult();

2. Now from fragment B our previous fragment A can be accessed by calling


3. In onResume of fragment B call

getTargetFragment().setMenuVisibility(false); .

This will hide any menu from fragments, note that the menu added from activity is still visible (which was in-fact my need of time)

4. In onStop of fragment A call


this will let menu from fragment A be visible when B is leaving. If it’s going back from B to A old menus from A can be visible.

Thats all folks.

Next time we will meet with some more tricks and tips.

PHP – How to read a file from another server using FTP credentials?

I had a task to read file from another server. Obvious you would suggest file_get_contents or cURL for same. But those files was not accessible through URL. I have to read it using FTP server credentials, Initially I was trying with ftp_get and some other FTP functions. But it was download all files to my local server.

But finally I got the solution, here its….

    $filename = 'ftp://username:password@hostname/files/path/and/name.txt';
    $handle = fopen($filename, "r");
    $contents = fread($handle, filesize($filename));
    echo $contents;

I hope this would help you….

Magento – What is the difference between getAllVisibleItems() and getAllItems()?

Before we start with answer of the question, I would like to explain what are these functions. These bothe functionas are used to get all order items,

// load form order ID
$order_id = 1234;
$order = Mage::getModel("sales/order")->load($order_id);
// Get current order ID
$order_id = Mage::getSingleton('checkout/session')->getLastRealOrderId();
$order = Mage::getModel('sales/order')->loadByIncrementId($order_id);
//$order->getSubtotal() ; $order->getGrandTotal() ;
$items = $order->getAllItems(); OR $order->getAllVisibleItems();
foreach ($items as $itemId => $item)
    $item->getQtyOrdered(); //$item->getQtyToInvoice();

Above code will give all the information of order and ordered items.

Now lets get back to the main question. Let’s look at the code of both methods first,

public function getAllItems()
    $items = array();
    foreach ($this->getItemsCollection() as $item) {
       if (!$item->isDeleted()) {
          $items[] = $item;
    return $items;
public function getAllVisibleItems()
    $items = array();
    foreach ($this->getItemsCollection() as $item) {
       if (!$item->isDeleted() && !$item->getParentItemId()) {
          $items[] = $item;
    return $items;

From the code we can see, The only difference is getAllVisibleItems() has an additional check for each item that is,


Which will allow parent item only, It means if you have Configurable Product in your order, getAllVisibleItems will show you only the parent item while getAllItem will show both products.

$order->getAllItems() refers to the all items parent and it’s child (ref: configurable product and it’s child items)

$order->getAllVisibleItems() refers to the Parent items only (Ref: configurable product only)

Conclusion, If you need to show order product or do some kind calculation on total ordered items getAllVisibleItems is more preferable.

Magento – Category tree view listing in drop-down

It took bit time to complete this task. After a big fight with the code, finally I am done with the category drop-down with subcategories parent and child tree view.

dropdown post

Here is the code, You can just create bellow function under the block or helper with your module.

function getCategoriesTreeView() {
    // Get category collection
    $categories = Mage::getModel('catalog/category')
        ->addAttributeToSort('path', 'asc')
        ->addFieldToFilter('is_active', array('eq'=>'1'))

    // Arrange categories in required array
    $categoryList = array();
    foreach ($categories as $catId => $category) {
        if (isset($category['name'])) {
            $categoryList[] = array(
                'label' => $category['name'],
                'level'  =>$category['level'],
                'value' => $catId
    return $categoryList;

Now its time for design, bellow is the code which will give you the category drop down.

<select id="categorylist" name="categorylist">
<option value="">Select Category</option>
    $categoriesTreeView = getCategoriesTreeView();

    foreach($categoriesTreeView as $value)
        $catName    = $value['label'];
        $catId      = $value['value'];
        $catLevel    = $value['level'];

        $space = '&nbsp;';
        for($i=1; $i<$catLevel; $i++){
            $space = $space."&nbsp;";
        $catName = $space.$catName;

     <option value="<?php echo $catIdIs; ?>"><?php echo $catName ?></option>

With the same code you can create category switcher / category changer. Just you need to get the category’s URL with the category collection and redirect to that category with on change event of drop-down.

Magento – Onepage checkout not working after upgrade/update Magento 1.8

We have resolve the issue with top menu navigation after upgrade magento to least version. Just recently I get new issue with checkout page that, step 3 Shipping Method is not working after upgrade magento 1.8 with my custom theme. Checkout process is stuck on step 3 Shipping Method.

After exploring web and debugging the code I have found solution. In order to resolve this issue you just need to add new class to html tag fieldset as shown below,

Go to /app/design/frontend/base/default/template/checkout/onepage/payment.phtml

look for the code

<?php echo $this->getChildHtml('methods') ?>

change it to this

<fieldset id="checkout-payment-method-load">
<?php echo $this->getChildHtml('methods') ?>

I hope this would resolve your issue….

Topmenu not functioning after upgrade magento 1.8 fatal error addCacheTag()

As we seen with my previous blog upgrade community edition magento 1.7 to magento 1.8,  we know how to upgrade magento with latest version.

When I was doing the same with one my project, I come across the error something like,

Fatal error: Call to a member function addCacheTag() on a non-object in (Base Path)/app/code/core/Mage/Catalog/Model/Observer.php on line 215

For quick fix, initially I have comment out two lines from file app/code/core/Mage/Catalog/Model/Observer.php

Line # 241 ($menuBlock->addModelTags($categoryModel);) 
Line # 215 ($block->addCacheTag(Mage_Catalog_Model_Category::CACHE_TAG);)

But after spending some time, I come to know that I have used one of the menu extension which is exptending the “Mage_Page_Block_Html_Topmenu” and there is some problem with Mage::dispatchEvent.

With my extended code it was just something like

Mage::dispatchEvent('page_block_html_topmenu_gethtml_before', array(
          'menu' => $this->_menu

Updated code is,

Mage::dispatchEvent('page_block_html_topmenu_gethtml_before', array(
        'menu' => $this->_menu,
        'block' => $this         //add this line

Most probebly this would resolve your issue.

How to upgrade magento to 1.8

Magento 1.8 has been released with,

  • Major overhaul of tax calculation formulas, correction of rounding errors, and additional assistance with configuration.
  • Optimized cache adapters for single-server systems.
  • Upgraded Redis cache adapters for multi-server systems.
  • Eliminated many types of database deadlocks.
  • And many more updates and changes………..

Now, Magento developers get a new JOB to upgrade magento from older version to magento 1.8.

Magento recommends you upgrade your installation using the following guidelines in a development or test environment, separate from your existing production environment:

  1. Create a parallel development or testing system, identical to your current production system.
    • You’ll use this parallel system to implement and test the Magento upgrade.
  2. In your current production environment:
    • Back up your Magento database.
    • Archive the file system. This includes the media directory and subdirectories; all extensions and customizations; and all custom themes.
  3. In the development or test environment:
    • Create a new, empty database instance.
    • Import the production database tables into the development database instance.
    • Copy your production media directory, extensions, themes, and other customizations to the development system.
    • Copy local.xml to magento-install-dir/app/etc and edit it if necessary to reference the production database instance.
    • In a web browser, go to your development system base URL.
    • Wait for upgrade scripts to run.
    • Verify the development system is now identical to the production system.
    • If not, fix issues, retest, and upgrade again.
  4. Test the development system thoroughly, including:
    • Verify all extensions, themes, and customizations work.
    • Place orders using all webstores and all payment methods.

Magento – Blank white screen frontend issue

Magento shows blank/empty page, I was scared when this happened on one of the live site but after some exercises with source code and using internet I come to find out the solution. Most probably it could have memory issue or the compilation tool.

In order to troubleshoot the issue,  your first step is to edit index.php, find out bellow line and uncomment

ini_set('display_errors', 1);

If its not available, insert this line somewhere at the top of the file and try out bellow solutions.

Try – 1 : Disable Complier

Go to System -> Tools -> Compilation and Disable you Complier and clear/flush magento cache data. In most of the cases this would solve the issue.

Try – 2 : Improve PHP Memory Limit

If you can access php.ini OR using .htaccess in the root OR edit index.php add bellow line right after ini_set(‘display_errors’, 1);

ini_set('memory_limit', '256M');

Try – 3 : Design changes

If you have recently installed new theme try to switch interface to a previously used one. Flush Magento cache after each operation. Magento will switch to default theme if it can not find a custom one.

I hope these would resolve  your problem.

Magento query master

This post is collection of mysql query to perform particular task, this will make you life easy.

NOTE : Basically this is not good practis to work with database directlly for live project. Make sure that you have database back up before run query.

Update customer group of all subscriber customer using query – Magento

    customer_entity.`group_id` = 5
    customer_entity.`entity_id` = newsletter_subscriber.`customer_id`
    newsletter_subscriber.`subscriber_status` = 1;

Turn template hints on/off using query – Magento

   value = 0
   path = "dev/debug/template_hints"
   path = "dev/debug/template_hints_blocks";

Change admin user password using query – magento

UPDATE admin_user SET password=CONCAT(MD5('qXpassword'), ':qX') WHERE username='admin';

Delete particular order using query – Magento

SET @increment_id='43290';
SELECT @order_id:=entity_id FROM sales_order_entity WHERE increment_id=@increment_id;
DELETE FROM sales_order_entity WHERE entity_id=@order_id OR parent_id=@order_id;
DELETE FROM sales_order WHERE increment_id=@increment_id;

Mass Exclude/Unexclude Images using query – Magento

//Mass Unexclude
UPDATE`catalog_product_entity_media_gallery_value` SET `disabled` = '0' WHERE `disabled` = '1';
//Mass Exclude
UPDATE`catalog_product_entity_media_gallery_value` SET `disabled` = '1' WHERE `disabled` = '0';

Delete all products using query – Magento

TRUNCATE TABLE `catalog_product_bundle_option`;
TRUNCATE TABLE `catalog_product_bundle_option_value`;
TRUNCATE TABLE `catalog_product_bundle_selection`;
TRUNCATE TABLE `catalog_product_entity_datetime`;
TRUNCATE TABLE `catalog_product_entity_decimal`;
TRUNCATE TABLE `catalog_product_entity_gallery`;
TRUNCATE TABLE `catalog_product_entity_int`;
TRUNCATE TABLE `catalog_product_entity_media_gallery`;
TRUNCATE TABLE `catalog_product_entity_media_gallery_value`;
TRUNCATE TABLE `catalog_product_entity_text`;
TRUNCATE TABLE `catalog_product_entity_tier_price`;
TRUNCATE TABLE `catalog_product_entity_varchar`;
TRUNCATE TABLE `catalog_product_link`;
TRUNCATE TABLE `catalog_product_link_attribute_decimal`;
TRUNCATE TABLE `catalog_product_link_attribute_int`;
TRUNCATE TABLE `catalog_product_link_attribute_varchar`;
TRUNCATE TABLE `catalog_product_option`;
TRUNCATE TABLE `catalog_product_option_price`;
TRUNCATE TABLE `catalog_product_option_title`;
TRUNCATE TABLE `catalog_product_option_type_price`;
TRUNCATE TABLE `catalog_product_option_type_title`;
TRUNCATE TABLE `catalog_product_option_type_value`;
TRUNCATE TABLE `catalog_product_super_attribute`;
TRUNCATE TABLE `catalog_product_super_attribute_label`;
TRUNCATE TABLE `catalog_product_super_attribute_pricing`;
TRUNCATE TABLE `catalog_product_super_link`;
TRUNCATE TABLE `catalog_product_enabled_index`;
TRUNCATE TABLE `catalog_product_website`;
TRUNCATE TABLE `catalog_product_entity`;
TRUNCATE TABLE `cataloginventory_stock_item`;
TRUNCATE TABLE `cataloginventory_stock_status`;

Get class and methods of an object – PHP

Use get_class to get the name of an object’s class.

<?php $class_name = get_class($object); ?>

Now, Use get_class_methods to get a list of all the accessible methods on an object

$class_name = get_class($object);
$methods = get_class_methods($class_name);
foreach($methods as $method)
    echo "<br>";