How to Use Fragment Layouts in Android

android-293x300-123

Fragment is a concept of UI components-with a new idea for the ability to retain state across configuration changes. As a result, web-pages load comparatively faster because it retains their previous state. Without Fragments components, the normal activity class causes running activities to be stopped, reloaded and re-rendered using the new parameters. A fragment allows building a UI as a series of smaller, reusable graphical elements that can be arranged as needed, based on the device’s capabilities.

Fragment layout in Android is pretty distinct from other platforms. This design was first introduced for the platform in version 3.0 and onwards.

Here are the main concepts about Android fragment layout:

  • Android tabs are most often presented as text compared to icons, because it is difficult to come up with descriptive icons for all the possible navigation option. Text is much better.
  • Android tabs aren’t square buttons.  They mostly contain text
  • Visual style of Android tabs is flat. There should not be any glossy or reflection effects like in html web design.

A Fragment framework works much like an activity.
To implement it in the app we need an independent Java activity class along with a fragment xml layout:

  1. Create a layout XML and an Activity subclass for your activity
  2. Create a layout XML and a Fragment subclass for your fragment
  3. Map the two together in your Activity layout XML (or using FragmentTransaction mostly in Java code)

Example of layout xml for activity

[sourcecode]<?xml version=”1.0″ encoding=”utf-8″?>
<TabHost
xmlns:android=”http://schemas.android.com/apk/res/android”
android:id=”@android:id/tabhost”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”>

<LinearLayout
android:orientation=”vertical”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”>

<FrameLayout
android:id=”@android:id/tabcontent”
android:layout_width=”0dp”
android:layout_height=”0dp”
android:layout_weight=”0″/>

<FrameLayout
android:id=”@+android:id/realtabcontent”
android:layout_width=”fill_parent”
android:layout_height=”0dp”
android:layout_weight=”1″/>

<TabWidget
android:id=”@android:id/tabs”
android:orientation=”horizontal”
android:layout_width=”fill_parent”
android:layout_height=”55dip”
android:layout_weight=”0″/>

</LinearLayout>
</TabHost>
[/sourcecode]

Example of Activity subclass

[sourcecode]package com.myproj;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Stack;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TextView;

public class AppMainTabActivity extends FragmentActivity {
/* Your Tab host */
private TabHost mTabHost;

/* A HashMap of stacks, where we use tab identifier as keys..*/
private HashMap<String, Stack<Fragment>> mStacks;

/*Save current tabs identifier in this..*/
private String mCurrentTab;

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_layout);
/*
*  Navigation stacks for each tab gets created..
*  tab identifier is used as key to get respective stack for each tab
*/
mStacks = new HashMap<String, Stack<Fragment>>();
mStacks.put(AppConstants.TAB_A, new Stack<Fragment>());
mStacks.put(AppConstants.TAB_B, new Stack<Fragment>());
mStacks.put(AppConstants.TAB_C, new Stack<Fragment>());
mStacks.put(AppConstants.TAB_D, new Stack<Fragment>());
mTabHost = (TabHost)findViewById(android.R.id.tabhost);
mTabHost.setOnTabChangedListener(listener);
mTabHost.setup();
initializeTabs();
}

private View createTabView(final int id,String s) {
View view = LayoutInflater.from(this).inflate(R.layout.tabs_icon, null);
ImageView imageView =   (ImageView) view.findViewById(R.id.icon);
imageView.setImageDrawable(getResources().getDrawable(id));
TextView textview= (TextView) view.findViewById(R.id.title);
textview.setText(s);
return view;
}

public void initializeTabs(){
/* Setup your tab icons and content views.. Nothing special in this..*/
TabHost.TabSpec spec    =   mTabHost.newTabSpec(AppConstants.TAB_A);
mTabHost.setCurrentTab(-3);
spec.setContent(new TabHost.TabContentFactory() {
public View createTabContent(String tag) {
return findViewById(R.id.realtabcontent);
}
});
spec.setIndicator(createTabView(R.drawable.cameratab, “Camera”));
mTabHost.addTab(spec);

spec = mTabHost.newTabSpec(AppConstants.TAB_B);
spec.setContent(new TabHost.TabContentFactory() {
public View createTabContent(String tag) {
return findViewById(R.id.realtabcontent);
}
});
spec.setIndicator(createTabView(R.drawable.presettab, “Presets”));
mTabHost.addTab(spec);

//Create a class AppConstants to declare your variables

spec = mTabHost.newTabSpec(AppConstants.TAB_C);
spec.setContent(new TabHost.TabContentFactory() {
public View createTabContent(String tag) {
return findViewById(R.id.realtabcontent);
}
});
spec.setIndicator(createTabView(R.drawable.manualtab, “Manual Entry”));

mTabHost.addTab(spec);

spec = mTabHost.newTabSpec(AppConstants.TAB_D);
spec.setContent(new TabHost.TabContentFactory() {
public View createTabContent(String tag) {
return findViewById(R.id.realtabcontent);
}
});
spec.setIndicator(createTabView(R.drawable.infotab, “Info”));
mTabHost.addTab(spec);
}

/*Comes here when user switch tab, or we do programmatically*/
TabHost.OnTabChangeListener listener    =   new
TabHost.OnTabChangeListener() {
public void onTabChanged(String tabId) {
/*Set current tab..*/
mCurrentTab                     =   tabId;

if(mStacks.get(tabId).size() == 0){
/*
*    First time this tab is selected. So add first fragment of that tab.
*    Dont need animation, so that argument is false.
*    We are adding a new fragment which is not present in stack. So add to stack is true.
*/
if(tabId.equals(AppConstants.TAB_A)){
pushFragments(tabId, new Camera(), false,true);
}else if(tabId.equals(AppConstants.TAB_B)){
pushFragments(tabId, new PresetsActivity(), false,true);
}else if(tabId.equals(AppConstants.TAB_C)){
pushFragments(tabId, new ManualActivity(), false,true);
}else if(tabId.equals(AppConstants.TAB_D)){
pushFragments(tabId, new InfoActivity(), false,true);
}
}else {
/*
*    We are switching tabs, and target tab is already has atleast one fragment.
*    No need of animation, no need of stack pushing. Just show the target fragment
*/
pushFragments(tabId, mStacks.get(tabId).lastElement(), false,false);
}
}
};

/* Might be useful if we want to switch tab programmatically, from
inside any of the fragment.*/
public void setCurrentTab(int val){
mTabHost.setCurrentTab(val);
}

/*
*      To add fragment to a tab.
*  tag             ->  Tab identifier
*  fragment        ->  Fragment to show, in tab identified by tag
*  shouldAnimate   ->  should animate transaction. false when we switch tabs, or adding first fragment to a tab
*                      true when when we are pushing more fragment into navigation stack.
*  shouldAdd       ->  Should add to fragment navigation stack (mStacks.get(tag)). false when we are switching tabs (except for the first time)
*                      true in all other cases.
*/
public void pushFragments(String tag, Fragment fragment,boolean shouldAnimate, boolean shouldAdd){
if(shouldAdd)
mStacks.get(tag).push(fragment);
FragmentManager   manager         =   getSupportFragmentManager();
FragmentTransaction ft            =   manager.beginTransaction();
if(shouldAnimate)
ft.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left);
ft.replace(R.id.realtabcontent, fragment);
ft.commit();
}

public void popFragments(){
/*
*    Select the second last fragment in current tab’s stack..
*    which will be shown after the fragment transaction given below
*/
Fragment fragment             =   mStacks.get(mCurrentTab).elementAt(mStacks.get(mCurrentTab).size() – 2);

/*pop current fragment from stack.. */
mStacks.get(mCurrentTab).pop();

/* We have the target fragment in hand.. Just show it.. Show a standard navigation animation*/
FragmentManager   manager         =   getSupportFragmentManager();
FragmentTransaction ft            =   manager.beginTransaction();
ft.setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_right);
ft.replace(R.id.realtabcontent, fragment);
ft.commit();
}

@SuppressLint(“NewApi”)
@Override
public void onBackPressed() {
if(((BaseFragment)mStacks.get(mCurrentTab).lastElement()).onBackPressed() == false){
/*
* top fragment in current tab doesn’t handles back press, we can do our thing, which is
*
* if current tab has only one fragment in stack, ie first fragment is showing for this tab.
*        finish the activity
* else
*        pop to previous fragment in stack for the same tab
*
*/
if(mStacks.get(mCurrentTab).size() == 1){
super.onBackPressed();  // or call finish..
}else{
popFragments();
}
}else{
//do nothing.. fragment already handled back button press.
}
}

/*
*   Imagine if you wanted to get an image selected using ImagePicker intent to the fragment. Ofcourse I could have created a public function
*  in that fragment, and called it from the activity. But couldn’t resist myself.
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

mStacks.get(mCurrentTab).lastElement().onActivityResult(requestCode, resultCode, data);
}
}
[/sourcecode]

Example of Fragment subclass

[sourcecode]package com.myproj;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;

public class BaseFragment extends Fragment {
public AppMainTabActivity mActivity;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

mActivity    = (AppMainTabActivity) this.getActivity();
}

public boolean onBackPressed(){
return false;
}
public void onActivityResult(int requestCode, int resultCode, Intent data){

}
}
[/sourcecode]

Fragment layout in Android is pretty distinct from other platforms. This design was first introduced for the platform in version 3.0 and onwards.

Here are the main concepts about Android fragment layout:

  1. Android tabs are most often presented as text compared to icons. Because, it is difficult to come up with descriptive icons for all the possible navigation option. Text is much better.
  2. Android tabs aren’t square buttons.  They mostly contain text
  3. Visual style of Android tabs is flat. There should not be any glossy or reflection effects like in html web design.

A fragment must always be embedded in an activity and the fragment’s lifecycle is directly affected by the parent activity’s lifecycle. When we add a fragment as a part of an activity layout, it lives in ViewGroup inside the activity’s view hierarchy and the fragment defines its own view layout. We can insert a fragment into the activity layout by declaring the fragment in the activity’s layout file, as a <fragment> element, or from the application code by adding it to an existing ViewGroup.
To animate the transition between fragments or to animate the process of showing or hiding a fragment the Fragment Manager API can be used and create a Fragment Transaction.
Within each Fragment Transaction we can specify in and out animations that will be used for show and hide respectively (or both when replace is used).

Benefits:

Fragments are useful in following cases:

  • If we split up views on some devices/orientations and show them in two activities and show all the content in one on other devices. That would be a use case if you go on a tablet or maybe even in landscape mode on a phone: e.g. you show the list of items and the details on one screen. On a phone or in portrait mode you just show one part.
  • Another use case is reusable views. So if we have some views that are visible on different activities and also perform some actions we could put this behavior into a fragment and then reuse it.
  • Animated effects can availed when dynamically adding and removing fragments from the screen
  • Integration with the action bar for tabs, as a replacement for TabHost
  • Integration with the action bar for “list”-based navigation (really a Spinner in the action bar, toggling between different fragments)

See Also: Webview Layouts usages in Android

If you have thoughts about or experiences with Android fragments, share them with us. We’d love to hear from you.

AWS-Elastic Beanstalk VS Custom Environment Solution

Amazon_S3_Online_Service-123 (1)

AWS has a beautiful feature named Elastic Beanstalk to deploy application in AWS cloud with minimal knowledge on environment setup. Currently it supports Ruby, Java, Node.js, python and PHP applications. But the question is, “should we use Elastic Beanstalk for a low/ medium traffic application?

Advantage:

  • The Elastic Beanstalk is a fully automatic feature for application deployment and versioning
  • AWS has pre-setup templates that can be used like LAMP stack, Ruby Stack
  • Helps to provide single management interface to monitor the activity of your environments like EC2, ELB and S3

Disadvantage:

  • Since this does not support micro instance the cost of for Small instance or higher configuration instance to AWS is redundant
  • There are some limitations to customize the ELB after deployment.
  • AWS scales up and down the resources based on metrics. It supports Elastic Beanstalk on a single metric.
  • AutoScaling cannot be configured with CPU parameters and Network traffic.

Finally, it can be said that Elastic beanstalk is the best fit for application environments that require very little customization with heavy traffic. As it doesn’t support Micro instances, so it is advisable to use customizable environments for low traffic applications.

Why is CakePHP Popular For Web App Development

Web application development is a competitive field with new frameworks and tools emerging almost every day. If you are looking to create a dynamic website or web app, you may be wondering which framework will best suit your needs. When it comes to choosing the right technology for your project, there are many factors to consider. Below, we’ll review some of the benefits of using CakePHP  and why is CakePHP popular for web app development.

What is CakePHP?

CakePHP is a free and open-source platform, which facilitates the developers to build highly affordable web-applications using the MVC framework. This is a robust and efficient platform for the developers to create exciting PHP web applications.

What Makes CakePHP Popular?

Here I would like to discuss the aspects responsible for popularizing CakePHP among developers.

  • Easy-To-Use Functionality

    Developers are constantly looking for ways to make development process easier and hassle-free. Hence we can use code generation and scaffolding features built-in in CakePHP to rapidly build prototypes.

Never miss an update from us. Join 10,000+ marketers and leaders.

CakePHP facilitates this opportunity which adds to its popularity. With CakePHP, the application development is not burdened with writing complex codes for the application hence saves a lot of development time. The code lines are also simplified and reduced to facilitate the developers with productive development process.

  • Flexible And Versatile

    CakePHP is used for web app development is because the configuration is flexible and versatile. It can automatically cater itself based on the requirements of the developers and the changes made by them. Hence, it doesn’t require any elaborate configuration settings for project development. Most features and settings are auto detected in the system and require only the settings for database connections. It’s a feature rich light weight PHP framework comes with lot of features like code generation, translations, database access, caching, validation, authentication etc.

  • MVC (Model View Control) Architecture

    CakePHP development uses the model-view-control architecture which helps in distinguishing the business logic from data and design. It does a clear discrimination among the presentation layer, the business logic and database. It enables the developers to work independently on separate aspects of development at the same time. It enables the developers to develop faster and make optimum use of the resources.

  • Security

    The security of the application must be top notch such that they make the website full proof from any security breaches and is safe from the hands of hackers. CakePHP comes with built-in tools for input validation, CSRF protection, Form tampering protection, SQL injection prevention, and XSS prevention, helping you keep your application safe & secure. 

  • Friendly License

    CakePHP is licensed under the MIT license which makes it perfect for use in commercial applications.

CakePHP Development has become the foremost option for web developers as well as the Businesses to build exciting and unique applications. No wonder it is one of the most preferred MVC framework.

Planning something on CakePHP? Get in touch with Andolasoft’s Experts to discuss your idea.

Ruby On Rails Releases Fixes For DoS, XSS Vulnerabilities

In 18th March, Ruby on Rails released four new versions along with fixes for a number of vulnerabilities, which could have lead to denial of service attacks and XSS injections. According to a post in company’s blog a total of 4 vulnerabilities were addressed in version 3.2.13, 3.1.12 and 2.3.18 of Rails. The company wrote “All versions are impacted by one or more of these security issues,”

The patches were released for symbol denial service (DoS) vulnerability (CVE-2013-1854) in ActiveRecord function and for two cross-sites scripting vulnerabilities i.e. sanitize helper (CVE-2013-1857) and sanitize_css method in Action Pack (CVE-2013-1855).

According to one of the warnings, an additional XML parsing vulnerability in JDOM backend of ActiveSupport could have also allowed attackers to perform denial of service attack when using JRuby (CVE-2013-1856) or could have enabled to gain access to files stored in the app server.

The XSS vulnerability could have allowed attackers to embed tag URL, which executes arbitrary JavaScript code.

The XSS vulnerabilities in particular could have allowed an attacker to embed a tag containing a URL that executes arbitrary JavaScript code.

Ruby on rails developer have fixed a number of similar issues in Ruby on Rails last month, which also included a YAML issue in ActiveRecord that lead to remote code execution

How Cloud Computing Will Affect Staffing And Recruitment

Integrating Cloud computing with staffing and recruitment industry would bring numerous new opportunities to the human resources applications as well as to the IT industry.

Cloud technology enables companies to use the latest version of the software that gets automatically updated to meet user’s needs.

Also, all the users of the cloud-based software are always on the same version of the release.

It negates the issue of incompatibility and having to update it manually to match other user’s version.

Every company wants their staffing or recruitment application to be scalable and cost-effective.

Ideal human resources software should be easy to use which could be accessible from anywhere.

This is where cloud-based HR software comes in, which makes recruitment easier.

Cloud-based application or SaaS (Software as a Service) is a software that can be accessed remotely from anywhere using a web browser and doesn’t necessarily require any installation or managing software on a local system.

Cloud-based systems facilitate the companies to avail applications on a subscription basis, according to the companies’ requirements. IT enables businesses to empower the application based on the degree of their usage.

This enables the companies to save investment as well as the use of the traditional software model.

It doesn’t have to be purchased or avail license of the software and might contain more than what is required. It saves time and money in the form of training and implementation, which doesn’t have to take place.

The various pricing model can help business’ requirements by allowing them to manage their user’s accounts on demand and cloud-based staffing software means, a company uses what they need when they need it.

New features are instantly available, when the application is upgraded, instead of having to wait to download and install the updates to avail necessary features

The SaaS-based application doesn’t require any implementation cost. It is because; there are no upfront capital expenditures or any sorts of IT resources. Setup and training are much faster and simple.

Companies benefit from ‘rent vs. buy’ model of SaaS software and don’t have to deal with application licenses. Companies save money by not having to pay servers, additional features, and software or in house IT staff.

Every company wants their staffing or recruitment application to be scalable and cost-effective. Ideal human resources software should be easy to use which could be accessible from anywhere. This is where cloud-based HR software comes in, which makes recruitment easier.

Cloud-based application or SaaS (Software as a Service) is a software that can be accessed remotely from anywhere using a web browser and doesn’t necessarily require any installation or managing software on a local system.

Here I have mentioned some advantages of using cloud-based recruitment software.

Cloud technology enables companies to use the latest version of the software that gets automatically updated to meet user’s needs. That means new features are instantly available, when the application is upgraded, instead of having to wait to download and install the updates to avail necessary features.

Also, all the users of the cloud-based software are always on the same version of the release. It negates the issue of incompatibility and having to update it manually to match other user’s version.

Cloud-based systems facilitate the companies to avail applications on a subscription basis, according to the companies’ requirements. IT enables businesses to empower the application based on the degree of their usage.

This enables the companies to save investment as well as the use of the traditional software model. It doesn’t have to be purchased or avail license of the software and might contain more than what is required. It saves time and money in the form of training and implementation, which doesn’t have to take place.

The various pricing model can help business’ requirements by allowing them to manage their user’s accounts on demand and cloud-based staffing software means, a company uses what they need when they need it.

The SaaS-based application doesn’t require any implementation cost. It is because; there are no upfront capital expenditures or any sorts of IT resources. Setup and training are much faster and simple.

Companies benefit from ‘rent vs. buy’ model of SaaS software and don’t have to deal with application licenses. Companies save money by not having to pay servers, additional features, and software or in house IT staff.

Cloud management services for staffing and recruiting software is profitable for businesses of all sizes. Here they work with more cost-effective and flexible software.

Software setup is faster and cost-effective than the traditional models. Cloud-based staffing and recruiting applications could be the solution to business’ staffing and recruiting needs.

IPhone 5S And IPad 5 Is Expected To Launch On 29th Of June

Apple’s next big thing is expected to lunch iphone 5s and ipad 5 on 29th of June of this year. Apparently iPhone 5S Smartphone will be entering the consumer market much earlier than what was expected. It is designed as a high-end sibling of the present generation iPhone 5. DigiTimes has revealed that the IPhone 5S will feature a faster processor, based on Apple’s ARM processing cores. They have also claimed that, it will have a higher-resolution camera than its previous models. These features can be disappointing for most users who find the phone’s design to be little boring and outdated compared to other major smart device manufacturers. But the next-generation iPhone 6 is expected to bring a fresh, updated and completely re-designed phone. Rumors have it that its design is inspired form iPad mini tablet.

Never miss an update from us. Join 10,000+ marketers and leaders.

DigiTimes’ sources has also pointed out that deliveries of essential iPhone 5S components are already scheduled to May, which makes sense that the launch date might be true. Resources have also stated that Apple is planning to launch iPad5 along with the iPhone 5S in an event on 29thof June. While unconfirmed from Apple, this date fits well with the earlier humors of the launch, but the inclusion of iPad 5 comes as something of a surprise. And these devices might be running iOS 7.

DigiTimes has released in their website stating-“Components for the next-generation iPhone will start shipping at the end of May with the new smartphone to have a chance of showing up in the third quarter, according to sources from the upstream supply chain.”

The new iPhone will not receive a major upgrade and may just be a slightly enhanced version of iPhone 5 (iPhone 5S), the sources said citing their latest specification data.”

If the event does really take place in June, It will be something of a test to iPhone 5S and iPad-5. This could also be the deciding factor of the company’s future. It will be the first major release from the company since the death of its co-founder Steve Jobs.

Major iphone application development company are also looking forward to the release of the new iPhone as well as the iOS 7. It will facilitate them to develop apps for the new OS with numerous new features and functionalities.