Sunday 17 November 2013

Difference between Android AsyncTask,Thread,IntentService and Service


Service
Thread
IntentService
AsyncTask
When to use ?
Task with no UI, but shouldn't be too long. Use threads within service for long tasks.
- Long task in general.

- For tasks in parallel use Multiple threads (traditional mechanisms)
- Long task usually with no communication to main thread.
(Update)- If communication is required, can use main thread handler or broadcast intents

- When callbacks are needed (Intent triggered tasks). 
- Small task having to communicate with main thread.

- For tasks in parallel use multiple instances OR Executor
 
Trigger
Call to method
onStartService()
Thread start() method
Intent
Call to method execute()
Triggered From (thread)
Any thread
Any Thread
Main Thread (Intent is received on main thread and then worker thread is spawed)
Main Thread
Runs On (thread)
Main Thread
Its own thread
Separate worker thread
Worker thread. However, Main thread methods may be invoked in between to publish progress.
Limitations /
Drawbacks
May block main thread
- Manual thread management

- Code may become difficult to read
- Cannot run tasks in parallel.

- Multiple intents are queued on the same worker thread.
- one instance can only be executed once (hence cannot run in a loop) 

- Must be created and executed from the Main thread

Content from : techtej

Thursday 17 October 2013

List of open source Game Engines for Android(Android Game Development)

Here below is list of Game Engine used in Android Game Development

  • Open Source Android Apps for Developers: jMonkeyEngine (Java Based 3D Game Engine)
  • Open Source Android Apps for Developers: Android-2D-Engine (Android Game)
  • Open Source Android Apps for Developers: YoghurtGum (Android Game Engine)
  • Open Source Android Apps for Developers: Catcake (Android Game Engine)
  • Open Source Android Apps for Developers: jPCT-AE (Android Game 3D Engine)
  • Open Source Android Apps for Developers: Dwarf-fw (Android 3D Framework)
  • Open Source Android Apps for Developers: Mages (Android Game Engine)
  • Open Source Android Apps for Developers: AndEngine (Android Game Engine)
  • Open Source Android Apps for Developers: Angle (Android Game Engine)

Thursday 10 October 2013

Tuesday 1 October 2013

Android GridLayout Example (New Feature in 4.0)

Here The Below Example shows How to create GridLayout in Android ?

GridLayout induced in Android 4.0 as New Feature.

LinearLayout and RelativeLayout are the most common layouts used in user
interface design in Android. For simple user interfaces they are a good choice but
when the user interface gets complicated, the use of nested LinearLayout tends
to increase. Nested layouts (of any type) can hurt performance, and furthermore
nested LinearLayout deeper than 10 may cause a crash in your application.
Thus, you should either avoid using too many nested LinearLayout blocks or
you should use RelativeLayout in order to decrease nested LinearLayout blocks.
Another drawback of these layouts for complicated user interfaces is the difficulty
in readability. It is difficult to maintain nested LinearLayout or RelativeLayout
layouts that have many views. It is a good choice to use GridLayout in these
cases. Too many nested LinearLayouts could be avoided by using GridLayout.
Furthermore, it is much easier to maintain GridLayout. Many of the user interfaces
that use LinearLayout, RelativeLayout, or TableLayout can be converted to
GridLayout where GridLayout will provide performance enhancements. One of
the major advantages of GridLayout over other layouts is that you can control the
alignment of a view in both horizontal and vertical axes.

Example GridLayout:

<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:columnCount="3"
    android:rowCount="3" >
    <Button android:text="1,1" />
    <Button android:text="1,2" />
    <Button android:text="1,3" />
    <Button android:text="2,1" />
    <Button android:text="2,2" />
    <Button android:text="2,3" />
    <Button android:text="3,1" />
    <Button android:text="3,2" />
    <Button android:text="3,3" />
</GridLayout>

Output Screen:








Monday 30 September 2013

How to connect the micromax Phone to the eclipse?

Hi friends to detect micromax mobile to the eclipse for Development purpose .Just download this below Driver and install .Then you can see Your Device in Eclipse Devices List.

Note: Don't forget to enable USB Debug mode in Developer Options in Settings.

Click on Globe to Download Driver.

If your Unable to find Developer option in your micromax mobile just follow below post for enable for find Developer option in your mobile.


Thursday 12 September 2013

IPhone Dialog in Android

Hi friends here below i created same iphone dialog view in android, with different types of views.if you want u can download .and plz add your valuable comments in below.

Output Screenshots:









































































Tuesday 10 September 2013

New Features For Android Application Development Explanation with Source

This below  book is a practical and hands-on guide for developing Android applications
using new features of Android Ice Cream Sandwich (Android 4.0), with a step-by-step
approach and clearly explained sample codes. You will learn the new APIs in Android
4.0 with these sample codes.

This Book covers these Below points.

Action Bar
New Layout(GridLayout)
Social APIs
Calendar APIs
Fragments
Supporting Different Screen Sizes
Android Compatibility Package
New Connectivity APIs





Wednesday 4 September 2013

Permission granted only to system apps error in IDE

So many people are getting "Permission granted only to system apps error" in Eclipse.While using System services in your application like

    <uses-permission android:name="android.permission.MODIFY_PHONE_STATE" />
we can resolve this Error in Eclipse & Android Studio By below steps

In Eclipse:

Window -> Preferences -> Android -> Lint Error Checking.
In the list find an entry with ID = ProtectedPermission. Set the Severity to something lower than Error. This way you can still compile the project using Eclipse.

In Android Studio:

File -> Settings -> Inspections
Under Android Lint, locate Using system app permission. Either uncheck the checkbox or choose a Severity lower than Error.:





How to enable USB debug mode in Android 4.2.2 (secret developer options)

Hi Friends i am wondered when i buy new mobile with Android 4.2.2 for Testing my Development Apps in Android mobile.Because Their is no option found defiantly in my Android Device(USB Debug mode.).In Default They give this option as secret developer  option.We can enable this option by seen this below video.
Options: Settings -> About Phone->Build number(Click on this option one or two times) then Developer options will be enable in Settings(Under system category)



Friday 9 August 2013

Thursday 25 July 2013

ViewPager with PageNumbers Example in Android

ViewPager is a Layout manager that allows the user to flip left and right through pages of data.
You supply an implementation of a PagerAdapter to generate the pages that the view shows.

Here we can see how to add page numbers in to a ViewPager.
This Example create 6 pages and show pagenumbers in Textview.

UI layout(pages.xml)

This layout is used to show pagenumber in ViewPager.


<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"
    android:id="@+id/rel" >

    <TextView
        android:id="@+id/pagenumber"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true" />

</RelativeLayout>

UI layout(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" >

    <RelativeLayout
        android:id="@+id/relativeTextview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_below="@+id/header"
        android:padding="5dp" >

        <android.support.v4.view.ViewPager
            android:id="@+id/reviewpager"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" />
    </RelativeLayout>

</RelativeLayout>


Android Activity (ViewPagerAdapter.java)

This calss supply an implementation of a PagerAdapter to generate the pages that the view shows


package com.androidsurya.androidviewpager;

import android.app.Activity;
import android.content.Context;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class ViewPagerAdapter extends PagerAdapter {
    int size;
    Activity act;
    View layout;
    TextView pagenumber;
    Button click;

    public ViewPagerAdapter(MainActivity mainActivity, int noofsize) {
        // TODO Auto-generated constructor stub
        size = noofsize;
        act = mainActivity;
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return size;
    }

    @Override
    public Object instantiateItem(View container, int position) {
        // TODO Auto-generated method stub
        LayoutInflater inflater = (LayoutInflater) act
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        layout = inflater.inflate(R.layout.pages, null);
        pagenumber = (TextView) layout.findViewById(R.id.pagenumber);
        int pagenumberTxt=position + 1;
        pagenumber.setText("Now your in Page No  " +pagenumberTxt );
        ((ViewPager) container).addView(layout, 0);
        return layout;
    }

    @Override
    public void destroyItem(View arg0, int arg1, Object arg2) {
        ((ViewPager) arg0).removeView((View) arg2);
    }

    @Override
    public boolean isViewFromObject(View arg0, Object arg1) {
        return arg0 == ((View) arg1);
    }

    @Override
    public Parcelable saveState() {
        return null;
    }

    // }

}

Android Activity (MainActivity.java)

Here in MainActivity we are creating object to ViewPagerAdapter class
and set Adapter to ViewPager object using setAdapter method.


package com.androidsurya.androidviewpager;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.Menu;

public class MainActivity extends Activity {
   
          int noofsize = 6;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ViewPagerAdapter adapter = new ViewPagerAdapter(MainActivity.this,
                noofsize);
        ViewPager myPager = (ViewPager) findViewById(R.id.reviewpager);
        myPager.setAdapter(adapter);
        myPager.setCurrentItem(0);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

}

Register the Activity in AndroidManifest file


  <activity
            android:name="com.androidsurya.androidviewpager.MainActivity"
            android:label="@string/app_name" >

Output Screenshots






































https://docs.google.com/file/d/0B4r4Yoc9-rj3SnhTclktYVdTWjQ/edit?usp=sharing




For More information about ViewPager: Android Developers site

Draw Line Chart in Android using achartengine

Here Below showlineChart() method will be create piechart using Achartengine in Android.
In  showlineChart()  method org.achartengine.GraphicalActivity class is Responsable to create LineChart.


Android Activity(MainActivity.java)
package com.androidsurya.achartengine;

import org.achartengine.ChartFactory;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;

public class MainActivity extends Activity {

private String[] mMonth = new String[] {
"Jan", "Feb" , "Mar", "Apr", "May", "Jun",
};

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        showlineChart();
    }  
    private void showlineChart(){
    int[] x = { 1,2,3,4,5};
    int[] income = { 240,467,259,570,500};
    int[] expense = {200, 521, 290, 219, 457};
   
    // Creating an  XYSeries for Income
    XYSeries incomeSeries = new XYSeries("Income");
    // Creating an  XYSeries for Income
    XYSeries expenseSeries = new XYSeries("Expenses");
    // Adding data to Income and Expense Series
    for(int i=0;i<x.length;i++){
    incomeSeries.add(x[i], income[i]);
    expenseSeries.add(x[i],expense[i]);
    }
   
    // Creating a dataset to hold each series
    XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
    // Adding Income Series to the dataset
    dataset.addSeries(incomeSeries);
    // Adding Expense Series to dataset
    dataset.addSeries(expenseSeries);    
   
   
    // Creating XYSeriesRenderer to customize incomeSeries
    XYSeriesRenderer incomeRenderer = new XYSeriesRenderer();
    incomeRenderer.setColor(Color.WHITE);
    incomeRenderer.setPointStyle(PointStyle.CIRCLE);
    incomeRenderer.setFillPoints(true);
    incomeRenderer.setLineWidth(2);
    incomeRenderer.setDisplayChartValues(true);
   
    // Creating XYSeriesRenderer to customize expenseSeries
    XYSeriesRenderer expenseRenderer = new XYSeriesRenderer();
    expenseRenderer.setColor(Color.BLUE);
    expenseRenderer.setPointStyle(PointStyle.CIRCLE);
    expenseRenderer.setFillPoints(true);
    expenseRenderer.setLineWidth(3);
    expenseRenderer.setDisplayChartValues(true);
   
   
    // Creating a XYMultipleSeriesRenderer to customize the whole chart
    XYMultipleSeriesRenderer multiRenderer = new XYMultipleSeriesRenderer();
    multiRenderer.setXLabels(0);
    multiRenderer.setChartTitle("Income vs Expense Chart");
    multiRenderer.setXTitle("Year 2011");
    multiRenderer.setYTitle("Amount in Rupees");
    multiRenderer.setZoomButtonsVisible(true);        
    for(int i=0;i<x.length;i++){
    multiRenderer.addXTextLabel(i+1, mMonth[i]);    
    }    
   
    // Adding incomeRenderer and expenseRenderer to multipleRenderer
    // Note: The order of adding dataseries to dataset and renderers to multipleRenderer
    // should be same
    multiRenderer.addSeriesRenderer(incomeRenderer);
    multiRenderer.addSeriesRenderer(expenseRenderer);
   
    // Creating an intent to plot line chart using dataset and multipleRenderer
    Intent intent = ChartFactory.getLineChartIntent(getBaseContext(), dataset, multiRenderer);
   
    // Start Activity
    startActivity(intent);
   
    }



}
Android Manifest file

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

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

Note: 
 Don't Forget Register this Below Activity In Manifest File
   <activity android:name="org.achartengine.GraphicalActivity" />

Output Screenshot:

















Wednesday 24 July 2013

Android 4.3 Jelly Bean : New Features announced in San Francisco

By Suhel Sayyad Thursday, July 25, 2013 Android , Android 4.3 , Features , Nexus 7 Leave a Comment
In Android 4.2, Google added the ability to created additional users for a tablet, much the same way that Windows handles users. In Android 4.3, device owners can create restricted profiles that have limits on what a user can do. For users that have skinned versions of Android, this will probably be pretty boring, but stock Android can now auto complete names and phone numbers directly from the dialer. Wi-Fi often does double-duty as a location service if you don't want to leave GPS on all the time. If you switch off Wi-Fi to save battery, though, this brings location services down with it. In Android 4.3, your device can continue scanning for Wi-Fi in a more passive mode that uses much less battery, but still pings for networks so you can keep location-based features. It is available in Nexus 7


Here are the new features in the latest Android .


1. Bluetooth Smart
2. OpenGL ES 3.0 for better 3D graphics
3. DRM APIs
4. Restricted profiles
5. Easier text input
6. Faster user-switching
7. Support for Hebrew and Arabic right-to-left languages
8. Bluetooth AVRCP
9. Background WiFi location
10. Dial pad autocomplete
11. Support for Hindi, Africaans, Amharic, Swahili and Zulu languages

For More information   Android Developers Blog

Thursday 6 June 2013

Draw Piechart in Android using achartengine

Here Below CreatePieChart() method will be create piechart using Achartengine in Android.
In  CreatePieChart()  method org.achartengine.GraphicalActivity class is Responsable to create PieChart.


Android Activity(PieChart.java)

package com.androidsurya.piechart;

import org.achartengine.ChartFactory;
import org.achartengine.model.CategorySeries;
import org.achartengine.renderer.DefaultRenderer;
import org.achartengine.renderer.SimpleSeriesRenderer;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;

public class PieChart extends Activity {

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

private void CreatePieChart() {

// Pie Chart Section Names
String[] code = new String[] { "IOS", "ANDROID" };

// Pie Chart Section Value
double[] distribution = { 40, 60 };

// Color of each Pie Chart Sections
int[] colors = { Color.GRAY, Color.GREEN };

// Instantiating CategorySeries to plot Pie Chart
CategorySeries distributionSeries = new CategorySeries(
"Mobile Platforms");
for (int i = 0; i < distribution.length; i++) {
// Adding a slice with its values and name to the Pie Chart
distributionSeries.add(code[i], distribution[i]);
}
// Instantiating a renderer for the Pie Chart
DefaultRenderer defaultRenderer = new DefaultRenderer();
for (int i = 0; i < distribution.length; i++) {
SimpleSeriesRenderer seriesRenderer = new SimpleSeriesRenderer();
seriesRenderer.setColor(colors[i]);
seriesRenderer.setDisplayChartValues(true);
// Adding a renderer for a slice
defaultRenderer.addSeriesRenderer(seriesRenderer);
}
defaultRenderer.setLegendTextSize(30);
defaultRenderer.setChartTitle("Mobile Platforms");
defaultRenderer.setChartTitleTextSize(20);
defaultRenderer.setZoomButtonsVisible(true);
defaultRenderer.setBackgroundColor(45454545);

// Creating an intent to plot bar chart using dataset and
// multipleRenderer
Intent intent = ChartFactory.getPieChartIntent(getBaseContext(),
distributionSeries, defaultRenderer,
"PieChart");

// Start Activity
startActivity(intent);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}

Android Manifest file

 <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.androidsurya.piechart.PieChart"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

Note: 
 Don't Forget Register this Below Activity In Manifest File
   <activity android:name="org.achartengine.GraphicalActivity" />

Output Screenshot:





















Monday 1 April 2013

Permission is only granted to system app, in Manifest error in Eclipse

MODIFY_PHONE_STATE permission is granted to system apps only. Error while developing Android Application.
Actually in android they are 2 types of Android apps : 

1) System 
2) user

User apps are just all your normal app installations through the Google Play Store, Amazon Appstore. These go into the /data partition of your Android phone, which is the part of the internal memory made available for user data and apps.

System apps are basically the apps that come pre-installed with your ROM. In a standard Android user environment, the user doesn’t have write access to the /system partition and thus, installing or uninstalling system apps directly isn’t possible.

In order to install an app as a system app on your Android device, your device must either be rooted or have a custom recovery installed (or both).

That being said, that error is actually wrong because you have a valid code and compilation should work. It would be better if it gave a warning instead. In Eclipse you can easily fix it. 

Just go to:

Window -> Preferences -> Android -> Lint Error Checking.

Find Protected Permission from the list and set the severity to something other than error(info for example). This way your project will still compile.

Thursday 21 March 2013

Android Splash Screen Example

Here we can See how to create splash screen in Android Application.
Some times the app need to show some company logo and some loading progress before starting Application at this time Splash Screen is main role.

UI Source(splash_layout.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=".SplashActivity" >

    <TextView
        android:id="@+id/textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Please wait Loading....!" />

    <ImageView
        android:id="@+id/logo"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_above="@+id/textview"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="22dp"
        android:src="@drawable/ic_launcher" />

</RelativeLayout>

Android Activity(SplashActivity.java)

This is splash screen activity here we are using theads to wait some time with in this screen.
after finishing sleep time SplashActivity will be  navigate to HomeActivity using Intents.

package com.androidsurya.splashscreenexample;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;

public class SplashActivity extends Activity {
    private static int SLEEP_TIME = 5500;// no of mille seconds sleep

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash_layout);
        // The thread to wait for splash screen events
        Thread splashThread = new Thread() {
            @Override
            public void run() {
                try {
                    synchronized (this) {
                        // Wait given period of time or exit on touch
                        wait(SLEEP_TIME);
                    }
                } catch (InterruptedException ex) {
                }

                finish();

                // Run next activity
                Intent intent = new Intent();
                intent.setClass(SplashActivity.this, HomeActivity.class);
                startActivity(intent);
            }
        };

        splashThread.start();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.splash_layout, menu);
        return true;
    }

}

UI layout(home_layout.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=".SplashActivity" >

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

Android Activity(HomeActivity.java)

package com.androidsurya.splashscreenexample;

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

public class HomeActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home_layout);
    }

}

Register both Activity's in AndroidManifest file

<activity
            android:name="com.androidsurya.splashscreenexample.SplashActivity"
            android:label="@string/app_name" >
          
        </activity>
        <activity
            android:name="com.androidsurya.splashscreenexample.HomeActivity"
            android:label="@string/app_name" >

Output Screenshot






















Monday 4 March 2013

Apply some styles to our list view

In the first step we’re creating a new xml file named styles.xml in res/values/

<?xml version="1.0" encoding="UTF-8"?>
<resources>
 <style name="CustomListViewStyle" parent="@android:style/Widget.ListView">
 <item name="android:background">#3F3F66</item>
 <item name="android:fastScrollEnabled">true</item>
 </style>
</resources>


What is important here? First of all we’ve created a custom style that extends its behavior from the default list view’s style.

In addition, we’re setting a new background color for the element and we’re enabling the fast scroll feature.

Last but not least we have to apply the style to an UI element e.g. modifying our ListView definition in the main.xml by setting a style-attribute


<ListView
 android:id="@android:id/listview"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 style="@style/CustomListViewStyle" >
</ListView>

Thursday 21 February 2013

Android Button Animation Example

Button Animation in Android

Here Below Example shows Animate Button in Android

  1. translate
  2. alpha
  3. scale
  4. rotate
  5. complex
Example :

First Create Below Animation files and place in (res/anim folder)

For Translate Animation(anim_translate.xml)

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/linear_interpolator">
    <translate
        android:fromXDelta="0"
        android:toXDelta="100%p"
        android:duration="500"
        android:repeatCount="1"
        android:repeatMode="reverse"/>
</set>

For Alpha Animation(anim_alpha.xml)

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/linear_interpolator">
    <alpha
        android:fromAlpha="1.0"
        android:toAlpha="0.1"
        android:duration="500"
        android:repeatCount="1"
        android:repeatMode="reverse" />
</set>

For Scale Animation(anim_scale.xml)

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/linear_interpolator">
    <scale
        android:fromXScale="1.0"
        android:toXScale="3.0"
        android:fromYScale="1.0"
        android:toYScale="3.0"
        android:pivotX="50%"
        android:pivotY="50%"
        android:duration="500"
        android:repeatCount="1"
        android:repeatMode="reverse" />
</set>


For Rotate Animation(anim_rotate.xml)

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/linear_interpolator" >

    <rotate
        android:duration="500"
        android:fromDegrees="0"
        android:pivotX="50%"
        android:pivotY="50%"
        android:repeatCount="1"
        android:repeatMode="reverse"
        android:startOffset="0"
        android:toDegrees="360" />

</set>

For Complex Animation

Merge all above 4 animations

Android UI Layout(main.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="fill_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:orientation="vertical" >

        <Button
            android:id="@+id/translate"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_margin="3dp"
            android:text="Translate"
           />

        <Button
            android:id="@+id/alpha"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_margin="3dp"
            android:text="Alpha"
           />

        <Button
            android:id="@+id/scale"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_margin="3dp"
            android:text="Scale"
           />

        <Button
            android:id="@+id/rotate"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_margin="3dp"
            android:text="Rotate"
           />

        <Button
            android:id="@+id/complex"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_margin="3dp"
            android:text="Complex"
           />
    </LinearLayout>

</RelativeLayout>

Android Activity Class(AndroidAnimButtonsActivity.java)

package com.androidsurya.androidbuttonanimation;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.widget.Button;

public class AndroidButtonAnimation extends Activity {

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Animation animTranslate = AnimationUtils.loadAnimation(this,
R.anim.anim_translate);
final Animation animAlpha = AnimationUtils.loadAnimation(this,
R.anim.anim_alpha);
final Animation animScale = AnimationUtils.loadAnimation(this,
R.anim.anim_scale);
final Animation animRotate = AnimationUtils.loadAnimation(this,
R.anim.anim_rotate);

Button btnTranslate = (Button) findViewById(R.id.translate);
Button btnAlpha = (Button) findViewById(R.id.alpha);
Button btnScale = (Button) findViewById(R.id.scale);
Button btnRotate = (Button) findViewById(R.id.rotate);
Button btnComplex = (Button) findViewById(R.id.complex);
btnTranslate.setOnClickListener(new Button.OnClickListener() {

@Override
public void onClick(View view) {
view.startAnimation(animTranslate);
}
});

btnAlpha.setOnClickListener(new Button.OnClickListener() {

@Override
public void onClick(View view) {
view.startAnimation(animAlpha);
}
});

btnScale.setOnClickListener(new Button.OnClickListener() {

@Override
public void onClick(View view) {
view.startAnimation(animScale);
}
});

btnRotate.setOnClickListener(new Button.OnClickListener() {

@Override
public void onClick(View view) {
view.startAnimation(animRotate);
}
});
btnComplex.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View view) {
AnimationSet sets = new AnimationSet(false);
sets.addAnimation(animAlpha);
sets.addAnimation(animScale);
sets.addAnimation(animRotate);
view.startAnimation(sets);
}
});
}
}

Register Android Activity in Android Manifest File

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name="com.androidsurya.androidbuttonanimation.AndroidButtonAnimation"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

Output Screen Shot:
















Monday 18 February 2013

Custom ListView with Image and Text in Android

Listview is nothing but a A view that shows items in a vertically scrolling list.
Here we will see how to show android custom listview(with image and text)

UI layout(activity_main.xml)

activity_main.xml file contains listview object which is used to display listview

<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:id="@+id/banner"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Select your Favorite Social Network"
        android:textSize="15sp" />

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/banner" >
    </ListView>

</RelativeLayout>

(listview_row.xml)

Here (listview_row.xml) layout for ListView rows in a XML file and keep it in res/layout folder.
provides data to each row in ListView.

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

    <ImageView
        android:id="@+id/icon_id"
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:paddingLeft="10dp"
        android:paddingRight="10dp" />

    <TextView
        android:id="@+id/title_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/icon_id"
        android:paddingBottom="10dp"
        android:text="Title"
        android:textColor="#3399FF"
        android:textSize="14dp" />

    <TextView
        android:id="@+id/description_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/title_id"
        android:layout_toRightOf="@+id/icon_id"
        android:paddingLeft="10dp"
        android:text="Description"
        android:textColor="#CC0033"
        android:textSize="12dp" />

</RelativeLayout>

Row.java

This class is usefull to store the data for each row in ListView.

package com.androidsurya.androidcustomlistview;

public class Row {
private int imageId;
private String title;
private String desc;

public Row(int imageId, String title, String desc) {
this.imageId = imageId;
this.title = title;
this.desc = desc;
}

public int getImageId() {
return imageId;
}

public void setImageId(int imageId) {
this.imageId = imageId;
}

public String getDesc() {
return desc;
}

public void setDesc(String desc) {
this.desc = desc;
}

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}

@Override
public String toString() {
return title + "\n" + desc;
}
}

Android Activity class(CustomListView.java)

package com.androidsurya.androidcustomlistview;

import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.app.Activity;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

public class CustomListView extends Activity implements OnItemClickListener {
public static final String[] titles = new String[] { "Facebook",
"Google +", "Orkut", "Twitter" };

public static final String[] descriptions = new String[] {
"Facebook is an online social networking service",
"Google + is an online social networking service",
"Orkut is an online social networking service",
"Twitter is an online social networking service" };

public static final Integer[] images = { R.drawable.facebook,
R.drawable.googleplus, R.drawable.orkut, R.drawable.twitter };

ListView listView;
List<Row> rowItems;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rowItems = new ArrayList<Row>();
for (int i = 0; i < titles.length; i++) {
Row item = new Row(images[i], titles[i], descriptions[i]);
rowItems.add(item);
}

listView = (ListView) findViewById(R.id.listView);
CustomBaseAdapter adapter = new CustomBaseAdapter(this, rowItems);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
Toast toast = Toast.makeText(getApplicationContext(), "Item Selected.."
+ (position + 1) + ": " + rowItems.get(position),
Toast.LENGTH_LONG);
toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}

}

CustomBaseAdapter.java

CustomBaseAdapter is a Class which implements BaseAdapater 
BaseAdapater is job is display data to each row in ListView.

package com.androidsurya.androidcustomlistview;

import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.widget.ImageView;
import android.widget.TextView;

public class CustomBaseAdapter extends BaseAdapter {
Context context;
List<Row> rowItems;

public CustomBaseAdapter(Context context, List<Row> items) {
this.context = context;
this.rowItems = items;
}

/* private view holder class */
private class ViewHolder {
ImageView iconView;
TextView txtTitle;
TextView txtDesc;
}

public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;

LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.listview_row, null);
holder = new ViewHolder();
holder.txtDesc = (TextView) convertView
.findViewById(R.id.description_id);
holder.txtTitle = (TextView) convertView
.findViewById(R.id.title_id);
holder.iconView = (ImageView) convertView
.findViewById(R.id.icon_id);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}

Row rowItem = (Row) getItem(position);
holder.txtDesc.setText(rowItem.getDesc());
holder.txtTitle.setText(rowItem.getTitle());
holder.iconView.setImageResource(rowItem.getImageId());

return convertView;
}

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

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

@Override
public long getItemId(int position) {
return rowItems.indexOf(getItem(position));
}
}

Register Android Activity in AndroidManifest.xml file

 <activity
            android:name="com.androidsurya.androidcustomlistview.CustomListView"
            android:label="@string/app_name" >

Output Screenshot























Android SQLite Database Viewer or Debuging with Stetho

Every Android Developer uses SQLite Database to store data into the Android Application data. But to view the data in SQLite have a lot of...