How to create Gradient Buttons Dynamically without XML in Android?

Hello all..

I have shown you how to create gradient buttons in Android using XML in this post.

Now I will show you how to create these gradient buttons dynamically.

We will start with a class that extends StateListDrawable similar to state-list we use in XML

UIGradientSelector.java

package com.example.dynamicgradient;

import android.graphics.drawable.StateListDrawable;

/**
 * {@link StateListDrawable} that controls selection of
 * {@link UIGradientDrawable} based on the three basic button states.
 */
public class UIGradientSelector extends StateListDrawable {

	/**
	 * {@link UIGradientSelector} that selects the {@link UIGradientDrawable}
	 * defined by the colors for the three basic button states.
	 * 
	 * @param normalColors
	 *            Array of primitive ints that define the gradient colors for a
	 *            button in its normal state.
	 * @param focusedColors
	 *            Array of primitive ints that define the gradient colors for a
	 *            button in its focused state.
	 * @param pressedColors
	 *            Array of primitive ints that define the gradient colors for a
	 *            button in its pressed state. If the array is null, then
	 *            focusedColors will be used for the pressed state.
	 */
	public UIGradientSelector(int[] normalColors, int[] focusedColors,
			int[] pressedColors) {
		int stateFocused = android.R.attr.state_focused;
		int statePressed = android.R.attr.state_pressed;
		UIGradientDrawable normalGradient = new UIGradientDrawable(normalColors);
		UIGradientDrawable focusedGradient = new UIGradientDrawable(
				focusedColors);
		UIGradientDrawable pressedGradient;

		if (pressedColors == null) {
			pressedGradient = focusedGradient;
		} else {
			pressedGradient = new UIGradientDrawable(pressedColors);
		}

		addState(new int[] { stateFocused }, focusedGradient);
		addState(new int[] { statePressed }, pressedGradient);
		addState(new int[] { -statePressed, -stateFocused }, normalGradient);
	}
}

Now the class that extends PaintDrawable Class.

UIGradientDrawable.java

package com.example.dynamicgradient;

import android.graphics.drawable.PaintDrawable;
import android.graphics.drawable.shapes.RectShape;

/**
 * {@link PaintDrawable} that paints the surface via a {@link UIGradientShader}.
 */
public class UIGradientDrawable extends PaintDrawable {

    /**
     * {@link UIGradientDrawable} with an initial shape of a rounded rectangle
     * that transitions evenly between the specified colors.
     * 
     * @param colors
     *            Array of primitive ints that contain the argb values of the
     *            color to use for transitioning.
     */
    public UIGradientDrawable(int[] colors) {
        UIGradientShader gradientShader = new UIGradientShader(colors);
        setShape(new RectShape());
        setCornerRadius(8);
        setShaderFactory(gradientShader);
        setDither(true);
    }
}

Now the last java class that extends ShaderFactory.
UIGradientShader.java

package com.example.dynamicgradient;

import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Shader;
import android.graphics.drawable.ShapeDrawable.ShaderFactory;

/**
 * {@link ShaderFactory} that uses a {@link LinearGradient} to transition
 * between specified colors. Any number of colors may be specified.
 */
public class UIGradientShader extends ShaderFactory {
	private int[] colors;
	private float[] positions;

	/**
	 * {@link UIGradientShader} that spaces color transitions evenly across the
	 * painting surface.
	 * 
	 * @param colors
	 *            Array of primitive ints that contain the argb values of the
	 *            color to use for transitioning. If the array contains only one
	 *            color, then an argb of (0, 0, 0, 0) will be used for the end
	 *            color of the transition. If the array is set to null or
	 *            contains zero colors, then the transition will be from an argb
	 *            of (255, 255, 255, 255) to and argb of (0, 0, 0, 0).
	 * 
	 * @see Color
	 */
	public UIGradientShader(int[] colors) {
		init(colors, null);
	}

	/**
	 * {@link UIGradientShader} that spaces color transitions across the
	 * painting surface as specified.
	 * 
	 * @param colors
	 *            Array of primitive ints that contain the argb values of the
	 *            color to use for transitioning. If the array contains only one
	 *            color, then an argb of (0, 0, 0, 0) will be used for the end
	 *            color of the transition. If the array is set to null or
	 *            contains zero colors, then the transition will be from an argb
	 *            of (255, 255, 255, 255) to and argb of (0, 0, 0, 0).
	 * @param positions
	 *            Array of primitive floats that contain the position of the
	 *            transition points. If the array is null, then the color
	 *            transitions will be spaced evenly.
	 */
	public UIGradientShader(int[] colors, float[] positions) {
		init(colors, positions);
	}

	private void init(int[] colors, float[] positions) {
		if (colors == null || colors.length == 0) {
			this.colors = new int[2];
			this.colors[0] = Color.argb(255, 255, 255, 255);
			this.colors[1] = Color.argb(0, 0, 0, 0);
		} else if (colors.length == 1) {
			this.colors = new int[2];
			this.colors[0] = colors[0];
			this.colors[1] = Color.argb(0, 0, 0, 0);
		} else {
			this.colors = colors;
		}

		this.positions = positions;
	}

	public Shader resize(int width, int height) {
		LinearGradient lg = new LinearGradient(0, 0, 0, height, colors,
				positions, Shader.TileMode.REPEAT);
		return lg;
	}

}

Atlast the MainActivity Class that applies these java classes.

package com.example.dynamicgradient;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.Button;
import android.widget.LinearLayout;

public class MainActivity extends Activity {

	protected LinearLayout mainLayout;
	public static Button btn1 = null;
	public static Button btn2 = null;

	// Members
	private int[] normalColors = new int[4];
	private int[] focusedColors = new int[2];
	private int[] disabledColors = new int[1];
	private int defaultSkinR = 255;
	private int defaultSkinG = 100;
	private int defaultSkinB = 150;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		  mainLayout = (LinearLayout) getLayoutInflater().inflate(R.layout.activity_main,
	                null);

	        normalColors[0] = Color.argb(255, defaultSkinR, defaultSkinG,
	                defaultSkinB);
	        normalColors[1] = Color.argb(255, 217, 217, 217);
	        normalColors[2] = Color.argb(191, defaultSkinR, defaultSkinG,
	                defaultSkinB);
	        normalColors[3] = Color.argb(140, defaultSkinR, defaultSkinG,
	                defaultSkinB);

	        focusedColors[0] = Color.argb(100, 242, 242, 242);
	        focusedColors[1] = Color.BLUE;

	        UIGradientSelector gradientSelector1 = new UIGradientSelector(
	                normalColors, focusedColors, null);
	        UIGradientSelector gradientSelector2 = new UIGradientSelector(
	                normalColors, focusedColors, null);

	        disabledColors[0] = Color.argb(153, 216, 216, 216);
	        UIGradientDrawable disabledGradient = new UIGradientDrawable(
	                disabledColors);

	        btn1 = (Button) mainLayout.findViewById(R.id.btn1);
	        btn1.setBackgroundDrawable(gradientSelector1);

	        btn2 = (Button) mainLayout.findViewById(R.id.btn3);
	        btn2.setBackgroundDrawable(disabledGradient);

	        setContentView(mainLayout);
	}

}

Now the Layout XML that contains two buttons.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" 
    android:background="@android:color/black">

    <Button
        android:id="@+id/btn1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:textColor="@android:color/white"
        android:text="Dynamic Gradient Button" />

    <Button
        android:id="@+id/btn3"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:textColor="@android:color/white"
        android:text="Dynamic Gradient Disbled Button" />

</LinearLayout>

How to Download a PDF File and open it in Android using an installed PDF Reader?

Actually this is fairly simple.

Open PDF

Open PDF

Open PDF

This simple code does this.

Uri path = Uri.fromFile(downloadFile(download_file_url));
				try {
					Intent intent = new Intent(Intent.ACTION_VIEW);
					intent.setDataAndType(path, "application/pdf");
					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(intent);
					finish();
				} catch (ActivityNotFoundException e) {
					setError("PDF Reader application is not installed in your device");
				}

Here is the complete program that shows how to download a PDF File and open it in Android using an installed PDF Reader.

package com.example.openpdf;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.Gravity;
import android.widget.TextView;

public class MainActivity extends Activity {

	TextView tv_loading;
	String dest_file_path = "test.pdf";
	int downloadedSize = 0, totalsize;
	String download_file_url = "http://ilabs.uw.edu/sites/default/files/sample_0.pdf";
	float per = 0;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		tv_loading = new TextView(this);
		setContentView(tv_loading);
		tv_loading.setGravity(Gravity.CENTER);
		tv_loading.setTypeface(null, Typeface.BOLD);
		downloadAndOpenPDF();
	}

	void downloadAndOpenPDF() {
		new Thread(new Runnable() {
			public void run() {
				Uri path = Uri.fromFile(downloadFile(download_file_url));
				try {
					Intent intent = new Intent(Intent.ACTION_VIEW);
					intent.setDataAndType(path, "application/pdf");
					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(intent);
					finish();
				} catch (ActivityNotFoundException e) {
					tv_loading
							.setError("PDF Reader application is not installed in your device");
				}
			}
		}).start();
  
	}

	File downloadFile(String dwnload_file_path) {
		File file = null;
		try {

			URL url = new URL(dwnload_file_path);
			HttpURLConnection urlConnection = (HttpURLConnection) url
					.openConnection();

			urlConnection.setRequestMethod("GET");
			urlConnection.setDoOutput(true);

			// connect
			urlConnection.connect();

			// set the path where we want to save the file
			File SDCardRoot = Environment.getExternalStorageDirectory();
			// create a new file, to save the downloaded file
			file = new File(SDCardRoot, dest_file_path);

			FileOutputStream fileOutput = new FileOutputStream(file);

			// Stream used for reading the data from the internet
			InputStream inputStream = urlConnection.getInputStream();

			// this is the total size of the file which we are
			// downloading
			totalsize = urlConnection.getContentLength();
			setText("Starting PDF download...");

			// create a buffer...
			byte[] buffer = new byte[1024 * 1024];  
			int bufferLength = 0;

			while ((bufferLength = inputStream.read(buffer)) > 0) {
				fileOutput.write(buffer, 0, bufferLength);
				downloadedSize += bufferLength;
				per = ((float) downloadedSize / totalsize) * 100;
				setText("Total PDF File size  : "
						+ (totalsize / 1024)
						+ " KB\n\nDownloading PDF " + (int) per
						+ "% complete");
			}
			// close the output stream when complete //
			fileOutput.close();
			setText("Download Complete. Open PDF Application installed in the device.");

		} catch (final MalformedURLException e) {
			setTextError("Some error occured. Press back and try again.",
					Color.RED);
		} catch (final IOException e) {
			setTextError("Some error occured. Press back and try again.",
					Color.RED);
		} catch (final Exception e) {
			setTextError(
					"Failed to download image. Please check your internet connection.",
					Color.RED);
		}
		return file;
	}

	void setTextError(final String message, final int color) {
		runOnUiThread(new Runnable() {
			public void run() {
				tv_loading.setTextColor(color);
				tv_loading.setText(message);
			}
		});

	}

	void setText(final String txt) {
		runOnUiThread(new Runnable() {
			public void run() {
				tv_loading.setText(txt);
			}
		});

	}

}

Samsung Galaxy s4 Rumours – Bigger, Better, Eye-Based Scrolling

Samsung Galaxy S4

We know Samsung is set to reveal its Galaxy S4 smartphone on March 14th, and that the company has been desperately trying to spin up the same sort of pre-release hype about the device that Apple usually benefits from–including a rather strange promotion campaign involving a young “secret messenger” called Jeremy. Now a source that has been accurate with Samsung rumors in the past has leaked some specs of the device.

Read the complete story here…

http://www.fastcompany.com/3006602/tech-forecast/galaxy-s-iv-rumors-bigger-better-eye-based-scrolling

Different ways to KEEP SCREEN ON in Android.

These are the different ways in which you can keep your screen on in your app

1. Declare the screen stays on in your XML layout
2. Inform the window manager in onCreate you want the screen to stay on
3. WakeLock – used for critical downloads or things that you definitely don’t want the Android system shutting down for

First Method

import android.app.Activity;
import android.os.Bundle;
import android.view.WindowManager;

public class ScreenOnFlagActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_flag);
 
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }
}

Next Method

import android.app.Activity;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;

public class ScreenOnWakeLockActivity extends Activity {
    private static final String TAG = "com.blundell.tut.ui.phone.ScreenOnWakeLockActivity.WAKE_LOCK_TAG";
    private WakeLock wakeLock;
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wake_lock);
 
        PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
        wakeLock = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, TAG);
    }
 
    @Override
    protected void onResume() {
        super.onResume();
        wakeLock.acquire();
    }
 
    @Override
    protected void onPause() {
        super.onPause();
        wakeLock.release();
    }
}

The third method

Add this to your root layout

‘android:keepScreenOn=”true”‘

But for all these to work.
You have to add this permission in the AndroidManifest.xml

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

Note : Don’t use this screen on feature unless you really need it, because it kills your battery.

Budget iPhone 5 Coming Soon

iPhone 5

The budget version of Apple’s latest iPhone will cost roughly $330 (£220), priced in order to appeal to young, middle class consumers in countries like China and India.
The claims about the price and the imminent release were made on the Japanese website Macotakara, following on from earlier reports about Apple plans for a cheaper phone.
In January it was reported that the planned new phone will resemble the iPhone 5 from the front but Apple will replace that handset’s aluminium body with a cheaper plastic casing.

Read More from here
http://www.telegraph.co.uk/technology/apple/9902864/Budget-iPhone-5-to-launch-soon.html

Galaxy S3 rival LG Optimus G @ Rs 30,990

LG launching Galaxy S3 rival Optimus G @ Rs 30,990

LG is all set to launch its erstwhile flagship smartphone Optimus G in India at an event in Mumbai on February 27. This device is pitted against the current market leader Samsung Galaxy S III and is the basis for the highly popular Google Nexus 4. India will be among the first countries outside the US, Canada, Japan and South Korea, as the device is yet to hit Europe as well as other major markets. The phone is available on online retail sites in the country at Rs 30,990 even before its launch.

Read More from
here

What are webservices? How we can use in Android?

A webservice can be

A web service is any piece of software that makes itself available over the internet and uses a standardized XML messaging system. XML is used to encode all communications to a web service. For example, a client invokes a web service by sending an XML message, then waits for a corresponding XML response. Because all communication is in XML, web services are not tied to any one operating system or programming language–Java can talk with Perl; Windows applications can talk with Unix applications.

Web Services are self-contained, modular, distributed, dynamic applications that can be described, published, located, or invoked over the network to create products, processes, and supply chains. These applications can be local, distributed, or Web-based. Web services are built on top of open standards such as TCP/IP, HTTP, Java, HTML, and XML.

Web services are XML-based information exchange systems that use the Internet for direct application-to-application interaction. These systems can include programs, objects, messages, or documents.

A web service is a collection of open protocols and standards used for exchanging data between applications or systems. Software applications written in various programming languages and running on various platforms can use web services to exchange data over computer networks like the Internet in a manner similar to inter-process communication on a single computer. This interoperability (e.g., between Java and Python, or Windows and Linux applications) is due to the use of open standards.

To summarize, a complete web service is, therefore, any service that:

1. Is available over the Internet or private (intranet) networks

2. Uses a standardized XML messaging system

3. Is not tied to any one operating system or programming language

4. Is self-describing via a common XML grammar

Is discoverable via a simple find mechanism

An Example

Consider a simple account-management and order -processing system. The accounting personnel use a client application built with Visual Basic or JSP to create new accounts and enter new customer orders.

The processing logic for this system is written in Java and resides on a Solaris machine, which also interacts with a database to store the information.
The steps illustrated above are as follows:

The client program bundles the account registration information into a SOAP message.
This SOAP message is sent to the Web Service as the body of an HTTP POST request.
The Web Service unpacks the SOAP request and converts it into a command that the application can understand. The application processes the information as required and responds with a new unique account number for that customer.
Next, the Web Service packages up the response into another SOAP message, which it sends back to the client program in response to its HTTP request.
The client program unpacks the SOAP message to obtain the results of the account registration process. For further details regarding the implementation of Web Services technology, read about the Cape Clear product set and review the product components.

In Android we can use it like an HTTP call. Several examples can be found on coderzheaven.com
Some of them are “connecting with php and android” where the php script can be called as a webservice which can be used by any system independent of the operating systems.

Some example links

http://www.coderzheaven.com/2012/09/25/table-values-mysql-database-show-android-tables/

How to create Simple Login form using php in android? – Connect php with android.

Samsung Galaxy Note 8.0

Samsung Galaxy Note 8.0

It would appear that Samsung will indeed be showing off their fabled Galaxy Note 8.0 tablet this coming week at Mobile World Congress 2013. We’ve been sent a sort of spy-shot of the Samsung Galaxy Note 8.0 being blasted on a large screen inside the new MWC convention location – the show still being set up in a very large way. True to what we’ve seen in several leaked bits and pieces over the past couple of weeks, this device is everything you might expect it to be – with an 8-inch screen!

Read complete story here

http://www.slashgear.com/samsung-galaxy-note-8-0-leaked-at-mwc-23270810/

iPhone Mini launch this summer

iPhone Mini

A low-priced iPhone makes a lot of sense, Morgan Stanley says, and it even could hit the market this summer.
Katy Huberty, an analyst with the banking firm, noted that after her meetings with Apple Chief Financial Officer Peter Oppenheimer, she’s convinced that innovation remains a top priority for the Cupertino, Calif., electronics giant. She also believes that Apple will increase cash return to shareholders and expand carriers, distribution, and possibly price points to drive iPhone growth.
She noted that a lower priced iPhone makes sense for several reasons:
“iPad Mini is expanding Apple’s customer base with 50 [percent] of purchases in China/Brazil representing new customers to the ecosystem.”
“Chinese consumers show a desire to purchase the latest version of iPhone (instead of discounted older generations).”
“iPhone 4 demand surprised to the upside in the December quarter.”

Read more from here

http://news.cnet.com/8301-13579_3-57570715-37/iphone-mini-launch-this-summer-makes-sense-analyst-says/

HTC One takes on iPhone5 and Samsung Galaxy S3

HTC One

since its arrival on the scene, HTC has been performing absolutely well and its latest launched, the HTC One or simply called the One, is pitted against Samsung’s Galaxy S3 and Apple’s iPhone 5 by the company and the market pundits.

But will the HTC One be a competition for the top two, namely, Samsung and Apple in the smartphone world?

That is for the company and the consumer to answer. Nevertheless, here’s looking at some of the important features of HTC One that could set it up against Samsung Galaxy S3 and Apple iPhone 5.

Read More from here

How to create layouts that change according to the phone and Tablet in Android Using Fragments in SDK Less than HoneyComb?

Hello all…..

This is a simple tutorial to show how to create a FLEXIBLE UI for both Phone and Tablets in Android.
In the figure below you can see the result after running this tutorial.

Tablet in LANDSCAPE MODE

Fragments

TABLET IN PORTRAIT MODE

Fragments

TABLET IN PORTRAIT MODE – AFTER CLICKING THE LIST.

Fragments

PHONE IN PORTRAIT MODE

Fragments

PHONE IN LANDSCAPE MODE.

Fragments

This can be achieved through Fragments.
This tutorial will have two parts.
1. In the first part I will show you how to use Fragments from API 11 (Honeycomb) and greater.
2. In the second I will show how to change it to adapt to lower versions from 1.6(Donut) using Google’s supporting Library.

I have already covered the first tutorial here..

http://www.coderzheaven.com/2013/02/17/create-layouts-change-phone-tablet-android-fragments/

Please check it before continue reading this post, because there are only small changes in the first post to make it compatible with the older version of Android.

These are the main changes you have to make.
1. Change all Activity to FragmentActivity and change the import statements like below

import android.app.Activity;
to
import android.support.v4.app.FragmentActivity;

2. Change the imports of Fragment from

import android.app.Fragment;
to
import android.support.v4.app.Fragment;

3. Now in the DetailsActivity.java change this line

getFragmentManager().beginTransaction()
.add(android.R.id.content, details).commit();

To

getSupportFragmentManager().beginTransaction()
.add(android.R.id.content, details).commit();

4. match_parent is not supported in old versions so change all “match_parent” in all layouts to “fill_parent”

5. Optionally You can change the min-sdkversion in Manifest to 5.

Done.

Now you have successfully adapted Fragments to the Older version of Android.

How to create layouts that change according to the phone and Tablet in Android Using Fragments?

Hello all…..

This is a simple tutorial to show how to create a FLEXIBLE UI for both Phone and Tablets in Android.
In the figure below you can see the result after running this tutorial.

Tablet in LANDSCAPE MODE

Fragments

TABLET IN PORTRAIT MODE

Fragments

TABLET IN PORTRAIT MODE – AFTER CLICKING THE LIST.

Fragments

PHONE IN PORTRAIT MODE

Fragments

PHONE IN LANDSCAPE MODE.

Fragments

This can be achieved through Fragments.
This tutorial will have two parts.
1. In the first part I will show you how to use Fragments from API 11 (Honeycomb) and greater.
2. In the second I will show how to change it to adapt to lower versions from 1.6(Donut) using Google’s supporting Library.

First Part ( ONLY for HONEYCOMB and GREATER).
(How to use Fragments from API 11 (Honeycomb) and greater)

First we will start with the layout XML Files.
This layout is for the first left part.

left_panel.xml. (Create this XML inside the res/layout folder)

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >


    <fragment
        android:id="@+id/titles"
        android:layout_width="0px"
        android:layout_height="match_parent"
        android:layout_weight="1"
        class="com.coderzheaven.googlefragment.TitlesFragment" />

</LinearLayout>

Now create the same copy of this XML inside the res/layout-land folder and change it’s contents slightly to this.
Here we have two fragments because this is used for the landscape mode in the tablets.
So Two fragments will be there at the same time in a single activity.
In the above XML this is not the case since there is only one fragment.

left_panel.xml (inside layout-land folder)

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal" >

    <fragment
        android:id="@+id/titles"
        android:layout_width="0px"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        class="com.coderzheaven.googlefragment.TitlesFragment" />

    <LinearLayout
        android:id="@+id/details"
        android:layout_width="0px"
        android:layout_height="fill_parent"
        android:layout_weight="2"
        android:background="?android:attr/detailsElementBackground" >
        
        
    </LinearLayout>

</LinearLayout>

The above XML will contain the two layout(fragments) for showing the details while clicking or selecting from the Left Panel for the TABLETS not the PHONES.

So we have to create another XML for showing details in the PHONES.

For that Create a new XML named “details_lay.xml” inside res/layout folder.

details_lay.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >


    <LinearLayout
        android:id="@+id/details"
        android:layout_width="0px"
        android:layout_height="match_parent"
        android:layout_weight="1"
        class="com.coderzheaven.googlefragment.DetailsFragment" />

</LinearLayout>

NOTE the class attribute inside the Fragments. It will be pointing to the Class for corresponding Fragments This is the important part in Fragments.
Make sure you change this to your package name before running your project.

Now we will create another layout for content inside the Details (right Panel).
I am naming it “layout_details_content.xml”.

layout_details_content.xml ( this is simply for showing a textview inside the Right Panel, However you can create this dynamically also)
layout_details_content.xml.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:layout_gravity="center" >

    <TextView
        android:id="@+id/tv1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:text="test"
        android:gravity="center" />

</LinearLayout>

OK Now all layouts are complete. Now we will go to the JAVA coding Part.

Remember all Fragments are associated with a java class that extends the Fragment Class.
That’s why we can use Fragments anywhere.

Now the MainActivity that launches First.

MainActivity.java

package com.coderzheaven.googlefragment;

import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.left_panel);
	}

}

The MainActivity has left_panel.xml as layout which will be layout/left_panel.xml in the phones and layout-land/ left_panel.xml in the tablets.
One thing to remember is Tablets will take layout/left_panel.xml while in it’s PORTRAIT mode.

Now we will write the classes for the Fragments.

First we will write class for the List Fragment on the Left.
TitlesFragment.java

package com.coderzheaven.googlefragment;

import android.app.FragmentTransaction;
import android.app.ListFragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class TitlesFragment extends ListFragment {
	boolean mDualPane;
	int mCurCheckPosition = 0;

	static String titles[] = { "CoderzHeaven", "Google", "Apple","Android","Microsoft","Samsung" };
 
	@Override 
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		// Populate list with our static array of titles.
		setListAdapter(new ArrayAdapter<String>(getActivity(),
				android.R.layout.simple_dropdown_item_1line, titles));

		// Check to see if we have a frame in which to embed the details
		// fragment directly in the containing UI.
		View detailsFrame = getActivity().findViewById(R.id.details);
		mDualPane = detailsFrame != null
				&& detailsFrame.getVisibility() == View.VISIBLE;

		if (savedInstanceState != null) {
			// Restore last state for checked position.
			mCurCheckPosition = savedInstanceState.getInt("curChoice", 0);
		} 

		if (mDualPane) {  
			// In dual-pane mode, the list view highlights the selected item.
			getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
			// Make sure our UI is in the correct state.
			showDetails(mCurCheckPosition);
		}else{
			System.out.println("NOT DUAL");
		}
	}  

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putInt("curChoice", mCurCheckPosition);
	}

	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		showDetails(position);
	}

	/**
	 * Helper function to show the details of a selected item, either by
	 * displaying a fragment in-place in the current UI, or starting a whole new
	 * activity in which it is displayed.
	 */
	void showDetails(int index) { 
		mCurCheckPosition = index;
		if (mDualPane) {
			// We can display everything in-place with fragments, so update
			// the list to highlight the selected item and show the data.
			getListView().setItemChecked(index, true);

			// Check what fragment is currently shown, replace if needed.
			DetailsFragment details = (DetailsFragment) getFragmentManager()
					.findFragmentById(R.id.details);
			if (details == null || details.getShownIndex() != index) {
				// Make new fragment to show this selection.
				details = DetailsFragment.newInstance(index);

				// Execute a transaction, replacing any existing fragment
				// with this one inside the frame.
				FragmentTransaction ft = getFragmentManager()
						.beginTransaction();
				ft.replace(R.id.details, details);
				ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
				ft.commit();
			}

		} else {
			// Otherwise we need to launch a new activity to display
			// the dialog fragment with selected text.
			Intent intent = new Intent();
			intent.setClass(getActivity(), DetailsActivity.class);
			intent.putExtra("index", index);
			startActivity(intent);
		}
	}
}

Note this Line

View detailsFrame = getActivity().findViewById(R.id.details);
		mDualPane = detailsFrame != null
				&& detailsFrame.getVisibility() == View.VISIBLE;

Since for phones there will not be Details Fragment in the first layout as you see in the phones the layout/left_panel.xml is loaded and it has no DETAIL Fragment.

Now we will write class for the DETAIL Fragment.
DetailsFragment.java

package com.coderzheaven.googlefragment;

import android.app.Fragment;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class DetailsFragment extends Fragment {
	/**
	 * Create a new instance of DetailsFragment, initialized to show the text at
	 * 'index'.
	 */
	static int i = 0;

	public static DetailsFragment newInstance(int index) {
		DetailsFragment f = new DetailsFragment();

		// Supply index input as an argument.
		Bundle args = new Bundle();
		args.putInt("index", index);

		i = index;
		f.setArguments(args);

		return f;
	}

	public int getShownIndex() {
		return getArguments().getInt("index", 0);
	}


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

		View v = getActivity().getLayoutInflater().inflate(
				R.layout.layout_details_content, null);
		TextView tv = (TextView)v.findViewById(R.id.tv1);
		tv.setText(TitlesFragment.titles[i].toUpperCase());
		tv.setTextColor(Color.RED);
		tv.setTextSize(25);
		
		return v;
	}
}

Note this fragement is used By phones and TABLETS while in portrait or LANDSCAPE Mode.
Only difference is when in Phone it is not shown at first since it is not present in the first layout.
Then we will check whether it is in the first layout. If it is there then we are in the LANDSCAPE MODE and if it is not present then we are in the portrait mode in PHONES AND TABLETS. So at that time we will start another DetailActivity which will load the DetaisFragment.

This is the line checking whether second fragment is in the layout or not

View detailsFrame = getActivity().findViewById(R.id.details);
		mDualPane = detailsFrame != null
				&& detailsFrame.getVisibility() == View.VISIBLE;

Here is the Second Activity for PHONES AND TABLETS IN THE PORTRAIT MODE.
DetailsActivity.java

package com.coderzheaven.googlefragment;

import android.app.Activity;
import android.app.Fragment;
import android.content.res.Configuration;
import android.os.Bundle;

public class DetailsActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
			setContentView(R.layout.details_lay); 
			return;
		}

		if (savedInstanceState == null) {
			// During initial setup, plug in the details fragment.
			Fragment details = new DetailsFragment();
			details.setArguments(getIntent().getExtras());
			getFragmentManager().beginTransaction()
					.add(android.R.id.content, details).commit();
		}
	}
}

For you understanding I am also pasting the AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.coderzheaven.googlefragment"
    android:versionCode="1"
    android:versionName="1.0" >
  
    <uses-sdk
        android:minSdkVersion="11"
        android:targetSdkVersion="17" />

    <uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.coderzheaven.googlefragment.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="com.coderzheaven.googlefragment.DetailsActivity"></activity>
    </application>

</manifest>

Using DialogFragments in Android – A Simple example.

Dialog Fragment

You can click on the links to download the code.

A little on Dialog Fragments

A fragment that displays a dialog window, floating on top of its activity’s window. This fragment contains a Dialog object, which it displays as appropriate based on the fragment’s state. Control of the dialog (deciding when to show, hide, dismiss it) should be done through the API here, not with direct calls on the dialog.

Implementations should override this class and implement onCreateView(LayoutInflater, ViewGroup, Bundle) to supply the content of the dialog. Alternatively, they can override onCreateDialog(Bundle) to create an entirely custom dialog, such as an AlertDialog, with its own content.

First we will create the layout for the Dialog.

dialog_fragment.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/edit_name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/lbl_your_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello from CoderzHeaven, DialogFragment Demo" />

</LinearLayout>

Now the layout for the activity

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/hello_world" />

</RelativeLayout>

Now the DialogFragment Class.

package com.example.dialogfragments;

import android.app.DialogFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class TestDialog extends DialogFragment {


	public TestDialog() {
		// Empty constructor required for DialogFragment
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.dialog_fragment, container);
		return view;
	}
}

Now the Activity that uses this fragment.

package com.example.dialogfragments;

import android.app.Activity;
import android.app.FragmentManager;
import android.os.Bundle;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		FragmentManager fm = getFragmentManager();
		TestDialog testDialog = new TestDialog();
		testDialog.setRetainInstance(true);
		testDialog.show(fm, "fragment_name");

	}

}

How to extend a Dialog class and write it’s button click on your activity using Interfaces in Android?

Hello all…….

This tutorial is all about writing your own Dialogs and implementing the click or touch on any of it’s views in another class (say another activity).
This is primarily useful if we have a common dialog and have to handle it’s button click in different ways in different activities.

Here what we will do is
1. Create a class that extends the Dialog.
2. The dialog contains a button , but the click of this button to be handled inside our activity.
3. Write an interface that will be implemented by the activity that handles the click.
So how do we do that..

Interfaces in Android Demo

This is the class that extends the Dialog along with the interface definition.

package com.coderzheaven.interfacedemo;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;

public class MyDialog extends Dialog {

	public MyDialog(Context context, myOnClickListener myclick) {
		super(context);
		this.myListener = myclick;
	}

	
	public myOnClickListener myListener;
        
        // This is my interface //
	public interface myOnClickListener {
		void onButtonClick();
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.alert);

		Button btn = (Button) findViewById(R.id.btn);
		btn.setOnClickListener(new android.view.View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				myListener.onButtonClick(); // I am giving the click to the
											// interface function which we need
											// to implements where we call this
											// class

			}
		});
	}

}

Now the activity that creates the object of the above class, thereby creating a dialog and calls it’s button click.

package com.coderzheaven.interfacedemo;

import com.coderzheaven.interfacedemo.MyDialog.myOnClickListener;

import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends Activity {

	public myOnClickListener myListener;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		// create new onclicklistener interface //
		myListener = new myOnClickListener() {
			@Override
			public void onButtonClick() {
				System.out.println("I am clicking the button in the dialog");
				Toast.makeText(getApplicationContext(),
						"I am clicking the button in the dialog",
						Toast.LENGTH_LONG).show();
			}
		};

		MyDialog mydialog = new MyDialog(this, myListener);
		mydialog.show();

	}

}

This is the layout for the Dialog.
Alert.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/parent"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="#ffffff"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_gravity="left|center"
        android:gravity="left|center"
        android:padding="8dip"
        android:text="Implementing common dialog button click in your own class using interfaces"
        android:textColor="#000000"
        android:textSize="20sp"
        android:textStyle="bold" />
    
    
    <Button
        android:id="@+id/btn"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_gravity="left|center"
        android:text="Click Me"
        android:textSize="20sp"
        android:textStyle="bold" />

</LinearLayout>

Done. Now you have successfully implemented a dialog’s button click on another activity.

How to write interfaces in java or Android?

Hello friends…

This tutorial is about how to use interfaces in java or Android.

So what is an Interface?

An interface is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface.

An interface is not a class. Writing an interface is similar to writing a class, but they are two different concepts. A class describes the attributes and behaviors of an object. An interface contains behaviors that a class implements.

Unless the class that implements the interface is abstract, all the methods of the interface need to be defined in the class.

An interface is similar to a class in the following ways:

  • An interface can contain any number of methods.

  • An interface is written in a file with a .java extension, with the name of the interface matching the name of the file.

  • The bytecode of an interface appears in a .class file.

  • Interfaces appear in packages, and their corresponding bytecode file must be in a directory structure that matches the package name.

However, an interface is different from a class in several ways, including:

  • You cannot instantiate an interface.

  • An interface does not contain any constructors.

  • All of the methods in an interface are abstract.

  • An interface cannot contain instance fields. The only fields that can appear in an interface must be declared both static and final.

  • An interface is not extended by a class; it is implemented by a class.

  • An interface can extend multiple interfaces.

———————————————–

Here I will show you how to do it in Android or Java.
This example is for Android.

So can we start.

This is the interface that I am going to implement.

MyTestInterface.java

package com.coderzheaven.interfacetest1;

public interface MyTestInterface {

	void testFunctionOne();

	void testFunctionTwo();

}

Now we will write the activity that implements the above interface.

package com.coderzheaven.interfacetest1;

import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity implements MyTestInterface {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}

	@Override
	public void testFunctionOne() {
		System.out.println("Print from testFunctionOne in the Interface");
	}

	@Override
	public void testFunctionTwo() {
		System.out.println("Print from testFunctionTwo in the Interface");
	}
}

Ok Done. Go on and Run it.

How to create transparency without using image in Android?

Transparency in a background of a View in android can be achieved in two ways.
1. By providing a transparent image.
2. By providing an XML that has as shape with end, starting and middle color.

This is a sample XML that creates a transparency.
bg_gradiant.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape>
             <gradient
                android:endColor ="#FFFFFF"
                android:startColor="#AA2F1701"
                android:angle="270" />
            <stroke
                android:width="0dp"
                android:color="#C2C2C2" />
            <corners
                android:radius="3dp" />
            <padding android:left="5dp"
                android:top="5dp"
                android:right="5dp"
                android:bottom="5dp"/>
        </shape>
    </item>   
</selector>

Note : By Simply providing a color doesn’t creates transparency.
The trick lies in the 8-digit code for the color.
The thing is that the last 6 letters represent the original color. The first 2 letter determines it’s alpha or Transparency.

The advantages of this type of xml is that.
1. We can have gradient of colors.
2. we can have gradient in any direction.
3. We have have strokes around the image.
4. we can reduce the size of our application without using an image for this transparency.
5. we can provide padding to them.
6. Most importantly we can have rounded corners to which ever view we apply this as background.

This is how it is applied in XML.

android:background="@drawable/bg_gradiant" 

BlackBerry Z10 vs. Nokia Lumia 920

BB 10 vs Nokia Lumia

The BlackBerry Z10 is finally here flying the BlackBerry 10 OS flag and, with it, carrying the hopes of the struggling company. We’ve pitted the Z10 against its two most dominant competitors, the Apple iPhone 5 and the ever-popular Android Samsung Galaxy S III, but the truth is, the Z10 will likely be clawing for market share against another young hopeful—Windows Phone 8. So how does the Z10 stack up against Microsoft’s flagship phone, the Nokia Lumia 920? We break down the two underdogs for a side-by-side spec comparison.

Read more from here

http://www.pcmag.com/article2/0,2817,2415004,00.asp

Custom Spinner in Android Redone using BaseAdapter..

I have already shown another example of creating custom spinner in android in this post.
That was by extending the ArrayAdapter class, Now it’s using the baseAdapter class.

You all knew that a spinner or combobox is an inbuilt widget in android. And Like any other widgets spinners are also customizable.
Here is a simple example to customize a spinner. First we will look at the java code.
The getView method is called for each row in the spinner. So with the help of an Layout Inflater you can inflate any layout for each row.
At extreme you can have each layout for each row.

Check these older posts about spinner.

1. How to get a selected Item from a spinner in ANDROID?

2. How to set an item selected in Spinner in ANDROID?

3. How to create a custom ListView in android?
4. Customizing a spinner in android.

Check out these of ListViews

1. Simplest Lazy Loading ListView Example in Android with data populated from a MySQL database using php.

2. How to add checkboxes and radio buttons to ListView in android? OR How to set single choice items in a ListView in android?

Ok We will start.
These are the layouts.

Activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Spinner
        android:id="@+id/spinner"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:drawSelectorOnTop="true"
        android:prompt="@string/prompt" />

</LinearLayout>

Now this is the layout for each row in the spinner.
row.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="3dip" >

    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" />

    <TextView
        android:id="@+id/company"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dip"
        android:layout_marginTop="2dip"
        android:layout_toRightOf="@+id/image"
        android:padding="3dip"
        android:text="CoderzHeaven"
        android:textColor="@drawable/red"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/sub"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/company"
        android:layout_marginLeft="5dip"
        android:layout_toRightOf="@+id/image"
        android:padding="2dip"
        android:text="Sub "
        android:textColor="@drawable/darkgrey" />

</RelativeLayout>

Now the object which we are placing in each row in the Spinner.
ListObject.java

package com.coderzheaven.customspinner;

public class ListObject {

	String company, sub;
	int image_id;

	public String getCompany() {
		return company;
	}

	public void setCompany(String company) {
		this.company = company;
	}

	public String getSub() {
		return sub;
	}

	public void setSub(String sub) {
		this.sub = sub;
	}

	public int getImage_id() {
		return image_id;
	}

	public void setImage_id(int image_id) {
		this.image_id = image_id;
	}

	public void setAll(int img_id, String title, String sub) {
		setImage_id(img_id);
		setCompany(title);
		setSub(sub);
	}
}

Now the Adapter class that creates each row for the spinner.
MyAdapter.java

package com.coderzheaven.customspinner;

import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class MyAdapter extends BaseAdapter {

	Context c;
	ArrayList<ListObject> objects;

	public MyAdapter(Context context, ArrayList<ListObject> objects) {
		super();
		this.c = context;
		this.objects = objects;
	}

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

	@Override
	public Object getItem(int position) {
		return objects.get(position);
	}

	@Override
	public long getItemId(int position) {
		return 0;
	}

	public View getView(int position, View convertView, ViewGroup parent) {

		ListObject cur_obj = objects.get(position);
		LayoutInflater inflater = ((Activity) c).getLayoutInflater();
		View row = inflater.inflate(R.layout.row, parent, false);
		TextView label = (TextView) row.findViewById(R.id.company);
		label.setText(cur_obj.getCompany());
		TextView sub = (TextView) row.findViewById(R.id.sub);
		sub.setText(cur_obj.getSub());
		ImageView icon = (ImageView) row.findViewById(R.id.image);
		icon.setImageResource(cur_obj.getImage_id());

		return row;
	}
}

Now the activity that ads the spinner and set the values.
MainActivity.java

package com.coderzheaven.customspinner;

import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Spinner;

public class MainActivity extends Activity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		String[] strings = { "CoderzHeaven", "Google", "Microsoft", "Apple",
				"Yahoo", "Samsung" };
		ArrayList<ListObject> objects = new ArrayList<ListObject>();
		for (int k = 0; k < strings.length; k++) {
			ListObject obj = new ListObject();
			obj.setAll(R.drawable.ic_launcher, strings[k], "Sub title");
			objects.add(obj);
		}

		Spinner mySpinner = (Spinner) findViewById(R.id.spinner);
		mySpinner.setAdapter(new MyAdapter(this, objects));
	}

}

And at last the manifest file. You may not need it .
AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.coderzheaven.customspinner"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.coderzheaven.customspinner.MainActivity"
            android:label="Custom Spinner" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

How to draw Arcs in Android using canvas?

This is a simple example showing how to draw Arcs in android, You can use this to create piecharts or someother similar thing you want.

Arc Drawing

Arc Drawing

Arc Drawing

Arc Drawing

Here we have 3 classes.
1. GraphicsActivity.java
2. MainActivity.java
3. PictureLayout.java

GraphicsActivity.java

package com.coderzheaven.arcdrawing;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;

class GraphicsActivity extends Activity {
    // set to true to test Picture
    private static final boolean TEST_PICTURE = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void setContentView(View view) {
        if (TEST_PICTURE) {
            ViewGroup vg = new PictureLayout(this);
            vg.addView(view);
            view = vg;
        }

        super.setContentView(view);
    }
}

PictureLayout.java

package com.coderzheaven.arcdrawing;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Picture;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;

public class PictureLayout extends ViewGroup {
    private final Picture mPicture = new Picture();

    public PictureLayout(Context context) {
        super(context);
    }

    public PictureLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public void addView(View child) {
        if (getChildCount() &gt; 1) {
            throw new IllegalStateException(&quot;PictureLayout can host only one direct child&quot;);
        }

        super.addView(child);
    }

    @Override
    public void addView(View child, int index) {
        if (getChildCount() &gt; 1) {
            throw new IllegalStateException(&quot;PictureLayout can host only one direct child&quot;);
        }

        super.addView(child, index);
    }

    @Override
    public void addView(View child, LayoutParams params) {
        if (getChildCount() &gt; 1) {
            throw new IllegalStateException(&quot;PictureLayout can host only one direct child&quot;);
        }

        super.addView(child, params);
    }

    @Override
    public void addView(View child, int index, LayoutParams params) {
        if (getChildCount() &gt; 1) {
            throw new IllegalStateException(&quot;PictureLayout can host only one direct child&quot;);
        }

        super.addView(child, index, params);
    }

    @Override
    protected LayoutParams generateDefaultLayoutParams() {
        return new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        final int count = getChildCount();

        int maxHeight = 0;
        int maxWidth = 0;

        for (int i = 0; i &lt; count; i++) {
            final View child = getChildAt(i);
            if (child.getVisibility() != GONE) {
                measureChild(child, widthMeasureSpec, heightMeasureSpec);
            }
        }

        maxWidth += getPaddingLeft() + getPaddingRight();
        maxHeight += getPaddingTop() + getPaddingBottom();

        Drawable drawable = getBackground();
        if (drawable != null) {
            maxHeight = Math.max(maxHeight, drawable.getMinimumHeight());
            maxWidth = Math.max(maxWidth, drawable.getMinimumWidth());
        }

        setMeasuredDimension(resolveSize(maxWidth, widthMeasureSpec),
                resolveSize(maxHeight, heightMeasureSpec));
    }

    private void drawPict(Canvas canvas, int x, int y, int w, int h,
                          float sx, float sy) {
        canvas.save();
        canvas.translate(x, y);
        canvas.clipRect(0, 0, w, h);
        canvas.scale(0.5f, 0.5f);
        canvas.scale(sx, sy, w, h);
        canvas.drawPicture(mPicture);
        canvas.restore();
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        super.dispatchDraw(mPicture.beginRecording(getWidth(), getHeight()));
        mPicture.endRecording();

        int x = getWidth()/2;
        int y = getHeight()/2;

        if (false) {
            canvas.drawPicture(mPicture);
        } else {
            drawPict(canvas, 0, 0, x, y,  1,  1);
            drawPict(canvas, x, 0, x, y, -1,  1);
            drawPict(canvas, 0, y, x, y,  1, -1);
            drawPict(canvas, x, y, x, y, -1, -1);
        }
    }

    @Override
    public ViewParent invalidateChildInParent(int[] location, Rect dirty) {
        location[0] = getLeft();
        location[1] = getTop();
        dirty.set(0, 0, getWidth(), getHeight());
        return getParent();
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        final int count = super.getChildCount();

        for (int i = 0; i &lt; count; i++) {
            final View child = getChildAt(i);
            if (child.getVisibility() != GONE) {
                final int childLeft = getPaddingLeft();
                final int childTop = getPaddingTop();
                child.layout(childLeft, childTop,
                        childLeft + child.getMeasuredWidth(),
                        childTop + child.getMeasuredHeight());

            }
        }
    }
}

MainActivity.java

package com.coderzheaven.arcdrawing;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.RectF;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;

public class MainActivity extends GraphicsActivity implements OnClickListener {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		Button b1 = (Button) findViewById(R.id.button1);
		Button b2 = (Button) findViewById(R.id.button2);
		Button b3 = (Button) findViewById(R.id.button3);
		b1.setOnClickListener(this);
		b2.setOnClickListener(this);
		b3.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		Style sytle = null;
		boolean use_centre = false;
		final LinearLayout r1 = (LinearLayout) findViewById(R.id.l1);
		if (MainActivity.this.findViewById(1) != null)
			r1.removeView(MainActivity.this.findViewById(1));
		switch (id) {
		case R.id.button1:
			use_centre = true;
			sytle = Paint.Style.FILL;
			break;
		case R.id.button2:
			use_centre = false;
			sytle = Paint.Style.STROKE;
			break;
		case R.id.button3:
			use_centre = true;
			sytle = Paint.Style.STROKE;
			break;
		default:
			break;

		}
		SampleView s = new SampleView(MainActivity.this);
		s.setId(1);
		s.startDraw(sytle, use_centre);
		r1.addView(s);
	}

	private static class SampleView extends View {
		private Paint mPaint;
		private Paint mFramePaint;
		private RectF mBigOval;
		private float mStart;
		private float mSweep;
		private boolean use_centre = false;
		private static final float SWEEP_INC = 0.5f;
		private static final float START_INC = 15;

		public SampleView(Context context) {
			super(context);
			mPaint = new Paint();
			mPaint.setAntiAlias(true);
			mPaint.setColor(0x880000FF);
			mPaint.setStrokeWidth(4);

			mBigOval = new RectF(40, 10, 280, 250);

			mFramePaint = new Paint();
			mFramePaint.setAntiAlias(true);
			mFramePaint.setStrokeWidth(4);
		}

		public void startDraw(Style style, boolean use_centre) {
			this.use_centre = use_centre;
			mPaint.setStyle(style);
			mFramePaint.setStyle(style);
		}

		private void drawArcs(Canvas canvas, RectF oval, boolean useCenter,
				Paint paint) {
			// canvas.drawRect(oval, mFramePaint);
			canvas.drawArc(oval, mStart, mSweep, useCenter, paint);
		}

		@Override
		protected void onDraw(Canvas canvas) {
			canvas.drawColor(Color.WHITE);

			drawArcs(canvas, mBigOval, use_centre, mPaint);

			mSweep += SWEEP_INC;
			if (mSweep &gt; 360) {
				mSweep -= 360;
				mStart += START_INC;
				if (mStart &gt;= 360) {
					mStart -= 360;
				}
			}
			invalidate();
		}
	}
}

Download the complete source code from here.

How to call a function in background in Xcode(iPhone)?

“performSelectorInBackground” will call anyfunction to execute in background and you can also pass string parameters with this method or if you want to pass more params then pass the parameters as an object.

[self performSelectorInBackground:@selector(myBackgroundMethod:) withObject:@"String Params"];

How to Change UIWebview’s background color in iPhone Xcode?

Unlike other UIViews, the UIWebview’s opaque property is set to true by default. That should be set to false for changing the background color.

[myWebView setOpaque:NO];

myWebView.backgroundColor=[UIColor redColor];

Samsung Year in Review: Galaxy Triumphs, Apple Losses

Samsung produces a number of products – from kitchen appliances to PCs – but it was the company’s mobile division that made the most headlines in 2012.
The Korea-based company dominated the mobile phone space, introducing several new Galaxy devices throughout the year. But it couldn’t shake one its biggest rivals, Apple, which proved to be a worthy opponent in the courtroom and in stores.
Still, despite all the hysteria surrounding the launch of the iPhone 5 and iPad mini, it was Samsung and its Android-heavy lineup of devices like the Galaxy S III and Galaxy Note II that were the really mobile winners in 2012. Those two smartphones were only introduced in the second half of the year and they have already sold at least 30 million and 5 million worldwide, respectively.

Read more from here..

http://www.pcmag.com/article2/0,2817,2413529,00.asp

How to copy a file to another saved in SDCARD in Android?

Hello all…

This tutorial explains how to copy a file contents to another in Android. The file to copy is saved in SDCARD, however you can change the path to save it in your application sandbox.
if you want to save it in your sandbox, change the path to

/data/data/your_packagename/your_file.extension

Now we will see the layout for the program.


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".CopyFileActivity" >

    <TextView
        android:id="@+id/tv1"
        android:textStyle="bold"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <TextView
        android:id="@+id/tv2"
        android:textStyle="bold"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/btn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Copy First file to second" />
    
      <TextView
        android:id="@+id/tv3"
        android:textStyle="bold"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="" />

</LinearLayout>

Now this is the java program that does the copying.

package com.coderzheaven.copyfiletoanother;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class CopyFileActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_copy_file);

		Button btn = (Button) findViewById(R.id.btn1);
		TextView tv1 = (TextView) findViewById(R.id.tv1);
		final TextView tv2 = (TextView) findViewById(R.id.tv2);
		final TextView tv3 = (TextView) findViewById(R.id.tv3);

		final String path1 = Environment.getExternalStorageDirectory()
				+ "/first_file.txt";
		final String path2 = Environment.getExternalStorageDirectory()
				+ "/second_file.txt";

		File file1 = new File(path1);
		tv1.setText("First File  : " + file1.getPath() + "(" + file1.length()
				+ " Bytes)\nFirst file contents : \n" + readFromSD(path1));

		File file2 = new File(path2);
		tv2.setText("Second File  : " + file2.getPath() + "(" + file2.length()
				+ " Bytes)");

		btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (copyFile(path1, path2))
					Toast.makeText(getApplicationContext(), "File Copied.",
							Toast.LENGTH_LONG).show();
				else
					Toast.makeText(getApplicationContext(), "File Not Copied.",
							Toast.LENGTH_LONG).show();

				tv3.setText("Second File Contents :" + readFromSD(path2));

			}
		});

	}

	public static boolean copyFile(String from, String to) {
		try {
			int bytesum = 0;
			int byteread = 0;
			File oldfile = new File(from);
			if (oldfile.exists()) {
				InputStream inStream = new FileInputStream(from);
				FileOutputStream fs = new FileOutputStream(to);
				byte[] buffer = new byte[1444];
				while ((byteread = inStream.read(buffer)) != -1) {
					bytesum += byteread;
					fs.write(buffer, 0, byteread);
				}
				inStream.close();
				fs.close();
			}
			return true;
		} catch (Exception e) {
			System.out.println(e.getMessage());
			return false;
		}
	}

	public String readFromSD(String path) {
		File file = new File(path);
		StringBuilder text = new StringBuilder();
		try {
			BufferedReader br = new BufferedReader(new FileReader(file));
			String line;
			while ((line = br.readLine()) != null) {
				text.append(line);
				text.append('\n');
			}
		} catch (IOException e) {
		}
		return text.toString();
	}

}

Note : if you are writing to Sdcard, then always give this permission in the AndroidManifest file.

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

Another important thing is here I am not creating the file to copy, simply assuming that the first file is present in the sdcard in the correct path.

Copy File

Copy File

Download complete Android source code from here.

Download the tutorial PDF from here.

Apple fined by China court for copyright violation

A court in China has ordered Apple to pay compensation to eight Chinese writers and two companies for violating their copyrights.

They had claimed that unlicensed electronic versions of their books had been sold on Apple’s online store.

The court ordered Apple to pay them 1.03m yuan ($165,000; £100,000) in compensation, according to the official news agency Xinhua.
… Read more from here.

http://www.bbc.co.uk/news/business-20856199