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

How to store an Image from Android to a SQlite and retrieve it?

Hello all…

In today’s post I will show you how to store an image in an SQLite database and retrieve it.

Check out the output after running the program.

Image in SQLite DB

Image in SQLite DB

Image in SQLite DB

Image in SQLite DB

Image in SQLite DB

Image in SQLite DB

Image in SQLite DB

This is the layout for the MainActivity.

<ScrollView 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" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <Button
            android:id="@+id/get_image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_above="@+id/textView1"
            android:layout_alignRight="@+id/textView1"
            android:text="Get Image" />

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_above="@+id/button1"
            android:layout_alignLeft="@+id/button1"
            android:src="@drawable/ic_action_search"
            android:visibility="gone" />

        <Button
            android:id="@+id/save_image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_above="@+id/textView1"
            android:layout_alignRight="@+id/textView1"
            android:text="Save Image in DB" />

        <Button
            android:id="@+id/read_image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_above="@+id/textView1"
            android:layout_alignRight="@+id/textView1"
            android:text="Read Image from DB" />

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            tools:context=".MainActivity" />

        <ImageView
            android:id="@+id/imageView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_above="@+id/button1"
            android:layout_alignLeft="@+id/button1"
            android:layout_marginBottom="40dp"
            android:src="@drawable/ic_action_search" />
    </LinearLayout>

</ScrollView>

Now the code for the Activity.

MainActivity.java

package com.coderzheaven.saveimageindb;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {
	protected static TextView textView;
	protected static ImageView image1, image2;
	protected Button get_image, save_image, read_image;
	private String selectedImagePath;
	private static final int SELECT_PICTURE = 1;
	String DB_NAME = Environment.getExternalStorageDirectory() + "/test.db";
	String TABLE_NAME = "mytable";

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

		image1 = (ImageView) findViewById(R.id.imageView1);
		image2 = (ImageView) findViewById(R.id.imageView2);
		textView = (TextView) findViewById(R.id.textView1);

		get_image = (Button) findViewById(R.id.get_image);
		get_image.setOnClickListener(this);

		save_image = (Button) findViewById(R.id.save_image);
		save_image.setOnClickListener(this);

		read_image = (Button) findViewById(R.id.read_image);
		read_image.setOnClickListener(this);

	}

	public void onClick(View v) {

		int id = v.getId();
		switch (id) {

		case R.id.get_image:
			Intent intent = new Intent();
			intent.setType("image/*");
			intent.setAction(Intent.ACTION_GET_CONTENT);
			startActivityForResult(
					Intent.createChooser(intent, "Select Picture"),
					SELECT_PICTURE);
			break;

		case R.id.save_image:
			createTable();
			saveInDB();
			break;

		case R.id.read_image:
			readFromDB();
			break;
		default:
			break;

		}
	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			if (requestCode == SELECT_PICTURE) {
				Uri selectedImageUri = data.getData();
				selectedImagePath = getPath(selectedImageUri);
				System.out.println("Image Path : " + selectedImagePath);
				image1.setVisibility(View.VISIBLE);
				image1.setImageURI(selectedImageUri);
			}
		}
	}

	@SuppressWarnings("deprecation")
	public String getPath(Uri uri) {
		String[] projection = { MediaStore.Images.Media.DATA };
		Cursor cursor = managedQuery(uri, projection, null, null, null);
		int column_index = cursor
				.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		cursor.moveToFirst();
		return cursor.getString(column_index);
	}

	void createTable() {
		SQLiteDatabase myDb = openOrCreateDatabase(DB_NAME,
				Context.MODE_PRIVATE, null);
		String MySQL = "create table if not exists "
				+ TABLE_NAME
				+ " (_id INTEGER primary key autoincrement, name TEXT not null, image BLOB);";
		myDb.execSQL(MySQL);
		myDb.close();
	}

	void saveInDB() {
		SQLiteDatabase myDb = openOrCreateDatabase(DB_NAME,
				Context.MODE_PRIVATE, null);
		byte[] byteImage1 = null;
		String s = myDb.getPath();

		myDb.execSQL("delete from " + TABLE_NAME); 			// clearing the table
		ContentValues newValues = new ContentValues();
		String name = "CoderzHeaven";
		newValues.put("name", name);
		try {
			FileInputStream instream = new FileInputStream(selectedImagePath);
			BufferedInputStream bif = new BufferedInputStream(instream);
			byteImage1 = new byte[bif.available()];
			bif.read(byteImage1);
			newValues.put("image", byteImage1);
			long ret = myDb.insert(TABLE_NAME, null, newValues);
			if (ret < 0)
				textView.append("Error");
		} catch (IOException e) {
			textView.append("Error Exception : " + e.getMessage());
		}
		myDb.close();
		textView.append("\n Saving Details \n Name : " + name);
		textView.append("\n Image Size : " + byteImage1.length + " KB");
		textView.append("\n Saved in DB : " + s + "\n");
		Toast.makeText(this.getBaseContext(),
				"Image Saved in DB successfully.", Toast.LENGTH_SHORT).show();
	}

	void readFromDB() {
		byte[] byteImage2 = null;
		SQLiteDatabase myDb;
		myDb = openOrCreateDatabase(DB_NAME, Context.MODE_PRIVATE, null);
		Cursor cur = myDb.query(TABLE_NAME, null, null, null, null, null, null);
		cur.moveToFirst();
		while (cur.isAfterLast() == false) {
			textView.append("\n Reading Details \n Name : " + cur.getString(1));
			cur.moveToNext();
		}

		// /////Read data from blob field////////////////////
		cur.moveToFirst();
		byteImage2 = cur.getBlob(cur.getColumnIndex("image"));
		setImage(byteImage2);
		cur.close();
		myDb.close();
		Toast.makeText(this.getBaseContext(),
				"Image read from DB successfully.", Toast.LENGTH_SHORT).show();
		Toast.makeText(this.getBaseContext(),
				"If your image is big, please scrolldown to see the result.",
				Toast.LENGTH_SHORT).show();
	}

	void setImage(byte[] byteImage2) {
		image2.setImageBitmap(BitmapFactory.decodeByteArray(byteImage2, 0,
				byteImage2.length));
		textView.append("\n Image Size : " + byteImage2.length + " KB");
	}

}

Please leave your valuable comments.

Cheaper, slimmer Google Nexus 7 rumored for Q1 2013

Google

Google may be readying a revamped model of the middle sibling in its Nexus line of Android devices for as early as the first quarter of 2013, if the supply-chain snoops at Taiwanese tech news site DigiTimes are correct.

Sources in the tech manufacturing sector are whispering that the Chocolate Factory and its manufacturing partner Asustek are “making headway” on a new, slimmer version of the popular Nexus 7 fondleslab.

Google – working on a secret phone called the “X-Phone”

Google

Google is working on what the company is internally calling the “X Phone” that it hopes will provide a credible challenge to Apple and Samsung, reveals the Wall Street Journal. Google is using Motorola, which it acquired seven months ago for $12.5 billion, to design a phone that will supposedly have new features unlike any seen in the crop of products currently in the market. But becoming a cutting-edge phone manufacturer is proving a tad more difficult for Google than it had foreseen and the Internet giant has run into several supply-chain management problems, according to the paper.

source : http://www.slate.com/blogs/the_slatest/2012/12/22/google_works_on_secret_phone_to_rival_iphone_apple.html

Samsung’s New Galaxy Grand with Dual-SIM, 5-Inch Display

Samsung Galxy Grand

Samsung has added the Grand, a new midrange smartphone, to its Android-running Galaxy lineup. At a glance, it strongly resembles the Galaxy S III, though Grand features a larger, though lower-resolution display—a 5-inch WVGA TFT LCD compared with the 4.8-inch HD Super AMOLED on the Galaxy S III—and will be available in a dual Subscriber Identity Module (SIM) version.

Read More from here

http://www.eweek.com/mobile/samsungs-new-galaxy-grand-offers-dual-sim-5-inch-display

A better Google News experience on tablets

Google News on Tablets

There’s something special about reading news on your tablet. Indeed, swiping through articles brings to mind the familiar feeling of flipping through a favorite magazine or newspaper. Starting today, Google News feels even more natural and fluid on tablet devices. For example:

You can find new articles, news sources, and even topics of interest with intuitive gestures. Swipe horizontally between sections – from Business to Entertainment, for example – or tap “Explore in depth” to see multiple articles and other info related to a particular story.

Read more from here

Samsung Galaxy S3 will get Android 4.1 Jelly Bean this Friday

Samsung Galxy S3 gets Android JellyBean Update
US Cellular has announced that it would be rolling Jelly Bean out to its Samsung Galaxy S3 starting this Friday, December 21st. This would make it the fifth and final upgrade needing to go out to the Samsung Galaxy S3 here in the United States as all major carriers, including Verizon, will have been offering it.

Read more from here….

http://phandroid.com/2012/12/17/us-cellular-galaxy-s3-jelly-bean/

Join the Forum discussion on this post

CoverFlow in Android – Complete implementation with source code.

Have you seen the coverflow in iPhone.
This is the Android implementation of CoverFlow.

Please leave your comments if this article is helpful for you.

Let’s see how.

This is the CoverFlow class that extends the Gallery.

package com.coderzheaven.coverflow;

import android.content.Context;
import android.graphics.Camera;
import android.graphics.Color;
import android.graphics.Matrix;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.Transformation;
import android.widget.Gallery;
import android.widget.ImageView;

@SuppressWarnings("deprecation")
public class CoverFlow extends Gallery {

	/**
	 * Graphics Camera used for transforming the matrix of ImageViews
	 */
	private Camera mCamera = new Camera();

	/**
	 * The maximum angle the Child ImageView will be rotated by
	 */
	private int mMaxRotationAngle = 60;

	/**
	 * The maximum zoom on the centre Child
	 */
	private int mMaxZoom = -120;

	/**
	 * The Centre of the Coverflow
	 */
	private int mCoveflowCenter;

	public CoverFlow(Context context) {
		super(context);
		this.setStaticTransformationsEnabled(true);
		this.setBackgroundColor(Color.BLACK);
	}

	public CoverFlow(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.setStaticTransformationsEnabled(true);
		this.setBackgroundColor(Color.BLACK);
	}

	public CoverFlow(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		this.setStaticTransformationsEnabled(true);
		this.setBackgroundColor(Color.BLACK);
	}

	/**
	 * Get the max rotational angle of the image
	 * 
	 * @return the mMaxRotationAngle
	 */
	public int getMaxRotationAngle() {
		return mMaxRotationAngle;
	}

	/**
	 * Set the max rotational angle of each image
	 * 
	 * @param maxRotationAngle
	 *            the mMaxRotationAngle to set
	 */
	public void setMaxRotationAngle(int maxRotationAngle) {
		mMaxRotationAngle = maxRotationAngle;
	}

	/**
	 * Get the Max zoom of the centre image
	 * 
	 * @return the mMaxZoom
	 */
	public int getMaxZoom() {
		return mMaxZoom;
	}

	/**
	 * Set the max zoom of the centre image
	 * 
	 * @param maxZoom
	 *            the mMaxZoom to set
	 */
	public void setMaxZoom(int maxZoom) {
		mMaxZoom = maxZoom;
	}

	/**
	 * Get the Centre of the Coverflow
	 * 
	 * @return The centre of this Coverflow.
	 */
	private int getCenterOfCoverflow() {
		return (getWidth() - getPaddingLeft() - getPaddingRight()) / 2
				+ getPaddingLeft();
	}

	/**
	 * Get the Centre of the View
	 * 
	 * @return The centre of the given view.
	 */
	private static int getCenterOfView(View view) {
		return view.getLeft() + view.getWidth() / 2;
	}

	/**
	 * {@inheritDoc}
	 * 
	 * @see #setStaticTransformationsEnabled(boolean)
	 */
	protected boolean getChildStaticTransformation(View child, Transformation t) {

		final int childCenter = getCenterOfView(child);
		final int childWidth = child.getWidth();
		int rotationAngle = 0;

		t.clear();
		t.setTransformationType(Transformation.TYPE_MATRIX);

		if (childCenter == mCoveflowCenter) {
			transformImageBitmap((ImageView) child, t, 0);
		} else {
			rotationAngle = (int) (((float) (mCoveflowCenter - childCenter) / childWidth) * mMaxRotationAngle);
			if (Math.abs(rotationAngle) > mMaxRotationAngle) {
				rotationAngle = (rotationAngle < 0) ? -mMaxRotationAngle
						: mMaxRotationAngle;
			}
			transformImageBitmap((ImageView) child, t, rotationAngle);
		}

		return true;
	}

	/**
	 * This is called during layout when the size of this view has changed. If
	 * you were just added to the view hierarchy, you're called with the old
	 * values of 0.
	 * 
	 * @param w
	 *            Current width of this view.
	 * @param h
	 *            Current height of this view.
	 * @param oldw
	 *            Old width of this view.
	 * @param oldh
	 *            Old height of this view.
	 */
	protected void onSizeChanged(int w, int h, int oldw, int oldh) {
		mCoveflowCenter = getCenterOfCoverflow();
		super.onSizeChanged(w, h, oldw, oldh);
	}

	/**
	 * Transform the Image Bitmap by the Angle passed
	 * 
	 * @param imageView
	 *            ImageView the ImageView whose bitmap we want to rotate
	 * @param t
	 *            transformation
	 * @param rotationAngle
	 *            the Angle by which to rotate the Bitmap
	 */
	private void transformImageBitmap(ImageView child, Transformation t,
			int rotationAngle) {
		mCamera.save();
		final Matrix imageMatrix = t.getMatrix();
		;
		final int imageHeight = child.getLayoutParams().height;
		;
		final int imageWidth = child.getLayoutParams().width;
		final int rotation = Math.abs(rotationAngle);

		mCamera.translate(0.0f, 0.0f, 100.0f);

		// As the angle of the view gets less, zoom in
		if (rotation < mMaxRotationAngle) {
			float zoomAmount = (float) (mMaxZoom + (rotation * 1.5));
			mCamera.translate(0.0f, 0.0f, zoomAmount);
		}

		mCamera.rotateY(rotationAngle);
		mCamera.getMatrix(imageMatrix);
		imageMatrix.preTranslate(-(imageWidth / 2), -(imageHeight / 2));
		imageMatrix.postTranslate((imageWidth / 2), (imageHeight / 2));
		mCamera.restore();
	}
}

Now the main activity that implements the coverflow.

package com.coderzheaven.coverflow;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

public class CoverFlowDemo extends Activity {

	@SuppressWarnings("deprecation")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		CoverFlow coverFlow;
		coverFlow = new CoverFlow(this);

		coverFlow.setAdapter(new ImageAdapter(this));

		ImageAdapter coverImageAdapter = new ImageAdapter(this);

		coverFlow.setAdapter(coverImageAdapter);

		coverFlow.setSpacing(-25);
		coverFlow.setSelection(4, true);
		coverFlow.setAnimationDuration(1000);

		setContentView(coverFlow);
	}

	public class ImageAdapter extends BaseAdapter {
		int mGalleryItemBackground;
		private Context mContext;

		private Integer[] mImageIds = { R.drawable.android,
				R.drawable.img1, R.drawable.img2,
				R.drawable.img3, R.drawable.img4,
				R.drawable.img1, R.drawable.img2,
				R.drawable.img3, R.drawable.img4
		};

		private ImageView[] mImages;

		public ImageAdapter(Context c) {
			mContext = c;
			mImages = new ImageView[mImageIds.length];
		}

		@SuppressWarnings("deprecation")
		public boolean createReflectedImages() {
			// The gap we want between the reflection and the original image
			final int reflectionGap = 4;

			int index = 0;
			for (int imageId : mImageIds) {
				Bitmap originalImage = BitmapFactory.decodeResource(
						getResources(), imageId);
				int width = originalImage.getWidth();
				int height = originalImage.getHeight();

				// This will not scale but will flip on the Y axis
				Matrix matrix = new Matrix();
				matrix.preScale(1, -1);

				// Create a Bitmap with the flip matrix applied to it.
				// We only want the bottom half of the image
				Bitmap reflectionImage = Bitmap.createBitmap(originalImage, 0,
						height / 2, width, height / 2, matrix, false);

				// Create a new bitmap with same width but taller to fit
				// reflection
				Bitmap bitmapWithReflection = Bitmap.createBitmap(width,
						(height + height / 2), Config.ARGB_8888);

				// Create a new Canvas with the bitmap that's big enough for
				// the image plus gap plus reflection
				Canvas canvas = new Canvas(bitmapWithReflection);
				// Draw in the original image
				canvas.drawBitmap(originalImage, 0, 0, null);
				// Draw in the gap
				Paint deafaultPaint = new Paint();
				canvas.drawRect(0, height, width, height + reflectionGap,
						deafaultPaint);
				// Draw in the reflection
				canvas.drawBitmap(reflectionImage, 0, height + reflectionGap,
						null);

				// Create a shader that is a linear gradient that covers the
				// reflection
				Paint paint = new Paint();
				LinearGradient shader = new LinearGradient(0,
						originalImage.getHeight(), 0,
						bitmapWithReflection.getHeight() + reflectionGap,
						0x70ffffff, 0x00ffffff, TileMode.CLAMP);
				// Set the paint to use this shader (linear gradient)
				paint.setShader(shader);
				// Set the Transfer mode to be porter duff and destination in
				paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
				// Draw a rectangle using the paint with our linear gradient
				canvas.drawRect(0, height, width,
						bitmapWithReflection.getHeight() + reflectionGap, paint);

				ImageView imageView = new ImageView(mContext);
				imageView.setImageBitmap(bitmapWithReflection);
				android.widget.Gallery.LayoutParams imgLayout = new CoverFlow.LayoutParams(
						320, 480);
				imageView.setLayoutParams(imgLayout);
				imageView.setPadding(30, 100, 20, 20);
				mImages[index++] = imageView;

			}
			return true;
		}

		public int getCount() {
			return mImageIds.length;
		}

		public Object getItem(int position) {
			return position;
		}

		public long getItemId(int position) {
			return position;
		}

		@SuppressWarnings("deprecation")
		public View getView(int position, View convertView, ViewGroup parent) {

			// Use this code if you want to load from resources
			ImageView i = new ImageView(mContext);
			i.setImageResource(mImageIds[position]);
			i.setLayoutParams(new CoverFlow.LayoutParams(380, 450));
			i.setScaleType(ImageView.ScaleType.CENTER_INSIDE);

			// Make sure we set anti-aliasing otherwise we get jaggies
			BitmapDrawable drawable = (BitmapDrawable) i.getDrawable();
			drawable.setAntiAlias(true);
			return i;

			// return mImages[position];
		}

		/**
		 * Returns the size (0.0f to 1.0f) of the views depending on the
		 * 'offset' to the center.
		 */
		public float getScale(boolean focused, int offset) {
			/* Formula: 1 / (2 ^ offset) */
			return Math.max(0, 1.0f / (float) Math.pow(2, Math.abs(offset)));
		}

	}
}

OK Done. Now go on and Run your project.

CoverFlow

Download the Complete android source code from here.