This example shows how create ImageGallery in android.
Algorithm:
1.) Create a new project by File-> New -> Android Project name it ImageGalleryExample.
2.) Add some sample .png image files to res/drawables folder.
3.) Write following into main.xml file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageSwitcher android:id="@+id/switcher"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
/>
<Gallery android:id="@+id/gallery"
android:background="#55000000"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:gravity="center_vertical"
android:spacing="16dp"
/>
</RelativeLayout>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageSwitcher android:id="@+id/switcher"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
/>
<Gallery android:id="@+id/gallery"
android:background="#55000000"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:gravity="center_vertical"
android:spacing="16dp"
/>
</RelativeLayout>
Steps:
1.) Create a project named ImageGalleryExample and set the information as stated in the image.
Build Target: Android 4.0
Application Name: ImageGalleryExample
Package Name: com. example. ImageGalleryExample
Activity Name: ImageGalleryExample
Min SDK Version: 14
2.) Open ImageGalleryExample.java file and write following code there:
3.) Compile and build the project.
Output
1.) Create a project named ImageGalleryExample and set the information as stated in the image.
Build Target: Android 4.0
Application Name: ImageGalleryExample
Package Name: com. example. ImageGalleryExample
Activity Name: ImageGalleryExample
Min SDK Version: 14
2.) Open ImageGalleryExample.java file and write following code there:
package com.example.ImageGalleryExample;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.Gallery.LayoutParams;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ViewSwitcher;
public class ImageGalleryExample extends Activity implements
AdapterView.OnItemSelectedListener, ViewSwitcher.ViewFactory {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
mSwitcher = (ImageSwitcher) findViewById(R.id.switcher);
mSwitcher.setFactory(this);
mSwitcher.setInAnimation(AnimationUtils.loadAnimation(this,
android.R.anim.fade_in));
mSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this,
android.R.anim.fade_out));
Gallery g = (Gallery) findViewById(R.id.gallery);
g.setAdapter(new ImageAdapter(this));
g.setOnItemSelectedListener(this);
}
public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
mSwitcher.setImageResource(mImageIds[position]);
}
public void onNothingSelected(AdapterView<?> parent) {
}
public View makeView() {
ImageView i = new ImageView(this);
i.setBackgroundColor(0xFF000000);
i.setScaleType(ImageView.ScaleType.FIT_CENTER);
i.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
return i;
}
private ImageSwitcher mSwitcher;
public class ImageAdapter extends BaseAdapter {
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(mContext);
i.setImageResource(mThumbIds[position]);
i.setAdjustViewBounds(true);
i.setLayoutParams(new Gallery.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
i.setBackgroundResource(R.drawable.picture_frame);
return i;
}
private Context mContext;
}
private Integer[] mThumbIds = {
R.drawable.sample_thumb_0, R.drawable.sample_thumb_1,
R.drawable.sample_thumb_2, R.drawable.sample_thumb_3};
private Integer[] mImageIds = {
R.drawable.sample_0, R.drawable.sample_1, R.drawable.sample_2,
R.drawable.sample_3};
}
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.Gallery.LayoutParams;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ViewSwitcher;
public class ImageGalleryExample extends Activity implements
AdapterView.OnItemSelectedListener, ViewSwitcher.ViewFactory {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
mSwitcher = (ImageSwitcher) findViewById(R.id.switcher);
mSwitcher.setFactory(this);
mSwitcher.setInAnimation(AnimationUtils.loadAnimation(this,
android.R.anim.fade_in));
mSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this,
android.R.anim.fade_out));
Gallery g = (Gallery) findViewById(R.id.gallery);
g.setAdapter(new ImageAdapter(this));
g.setOnItemSelectedListener(this);
}
public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
mSwitcher.setImageResource(mImageIds[position]);
}
public void onNothingSelected(AdapterView<?> parent) {
}
public View makeView() {
ImageView i = new ImageView(this);
i.setBackgroundColor(0xFF000000);
i.setScaleType(ImageView.ScaleType.FIT_CENTER);
i.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
return i;
}
private ImageSwitcher mSwitcher;
public class ImageAdapter extends BaseAdapter {
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(mContext);
i.setImageResource(mThumbIds[position]);
i.setAdjustViewBounds(true);
i.setLayoutParams(new Gallery.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
i.setBackgroundResource(R.drawable.picture_frame);
return i;
}
private Context mContext;
}
private Integer[] mThumbIds = {
R.drawable.sample_thumb_0, R.drawable.sample_thumb_1,
R.drawable.sample_thumb_2, R.drawable.sample_thumb_3};
private Integer[] mImageIds = {
R.drawable.sample_0, R.drawable.sample_1, R.drawable.sample_2,
R.drawable.sample_3};
}
Output
Live Wallpaper in Android
This example explains how to create and set live wallpaper in android.
Algorithm:
1.) Create a new project by File-> New -> Android Project name it LiveWallpaper.
2.) Write following into manifest file:
3.) Create “xml” folder into res directory and create and write following into mywallpaper.xml:
4.) Create and write following into prefs.xml:
5.) Create and write following code into src/MyPoints.java:
6.) Create a service class to make the wallpaper application run from background. Write following into MyWallpaperService.java:
7.) Run for output.
Steps:
1.) Create a project named LiveWallpaper and set the information as stated in the image.
Build Target: Android 4.0
Application Name: LiveWallpaper
Package Name: com. example. LiveWallpaper
Activity Name: LiveWallpaperActivity
Min SDK Version: 14
2.) Open LiveWallpaperActivity.java file and write following code there:
3.) Compile and build the project.
Output
Algorithm:
1.) Create a new project by File-> New -> Android Project name it LiveWallpaper.
2.) Write following into manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.LiveWallpaper" android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/ic_launcher" android:label="@string/app_name">
<service android:name="MyWallpaperService" android:enabled="true"
android:permission="android.permission.BIND_WALLPAPER" android:label="Wallpaper Example ">
<intent-filter>
<action android:name="android.service.wallpaper.WallpaperService"></action>
</intent-filter>
<meta-data android:name="android.service.wallpaper"
android:resource="@xml/mywallpaper"></meta-data>
</service>
<activity android:label="@string/app_name" android:name=".LiveWallpaperActivity"
android:theme="@android:style/Theme.Light.WallpaperSettings"
android:exported="true">
</activity>
</application>
<uses-sdk android:minSdkVersion="10" />
<uses-feature android:name="android.software.live_wallpaper"
android:required="true"></uses-feature>
</manifest>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.LiveWallpaper" android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/ic_launcher" android:label="@string/app_name">
<service android:name="MyWallpaperService" android:enabled="true"
android:permission="android.permission.BIND_WALLPAPER" android:label="Wallpaper Example ">
<intent-filter>
<action android:name="android.service.wallpaper.WallpaperService"></action>
</intent-filter>
<meta-data android:name="android.service.wallpaper"
android:resource="@xml/mywallpaper"></meta-data>
</service>
<activity android:label="@string/app_name" android:name=".LiveWallpaperActivity"
android:theme="@android:style/Theme.Light.WallpaperSettings"
android:exported="true">
</activity>
</application>
<uses-sdk android:minSdkVersion="10" />
<uses-feature android:name="android.software.live_wallpaper"
android:required="true"></uses-feature>
</manifest>
<?xml version="1.0" encoding="UTF-8"?>
<wallpaper
android:settingsActivity="de.vogella.android.wallpaper.MyPreferencesActivity"
xmlns:android="http://schemas.android.com/apk/res/android"
android:description="@string/wallpaper_description"
android:thumbnail="@drawable/ic_launcher" />
<wallpaper
android:settingsActivity="de.vogella.android.wallpaper.MyPreferencesActivity"
xmlns:android="http://schemas.android.com/apk/res/android"
android:description="@string/wallpaper_description"
android:thumbnail="@drawable/ic_launcher" />
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<CheckBoxPreference android:key="touch"
android:title="Enable Touch"></CheckBoxPreference>
<EditTextPreference android:key="numberOfCircles"
android:title="Number of Circles"></EditTextPreference>
</PreferenceScreen>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<CheckBoxPreference android:key="touch"
android:title="Enable Touch"></CheckBoxPreference>
<EditTextPreference android:key="numberOfCircles"
android:title="Number of Circles"></EditTextPreference>
</PreferenceScreen>
package com.example.LiveWallpaper;
import java.util.ArrayList;
import java.util.List;
import android.content.SharedPreferences;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.service.wallpaper.WallpaperService;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
public class MyWallpaperService extends WallpaperService {
@Override
public Engine onCreateEngine() {
return new MyWallpaperEngine();
}
private class MyWallpaperEngine extends Engine {
private final Handler handler = new Handler();
private final Runnable drawRunner = new Runnable() {
@Override
public void run() {
draw();
}
};
private List<MyPoint> circles;
private Paint paint = new Paint();
private int width;
int height;
private boolean visible = true;
private int maxNumber;
private boolean touchEnabled;
public MyWallpaperEngine() {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(MyWallpaperService.this);
maxNumber = Integer
.valueOf(prefs.getString("numberOfCircles", "10"));
touchEnabled = prefs.getBoolean("touch", false);
circles = new ArrayList<MyPoint>();
paint.setAntiAlias(true);
paint.setColor(Color.GREEN);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeWidth(10f);
handler.post(drawRunner);
}
@Override
public void onVisibilityChanged(boolean visible) {
this.visible = visible;
if (visible) {
handler.post(drawRunner);
} else {
handler.removeCallbacks(drawRunner);
}
}
@Override
public void onSurfaceDestroyed(SurfaceHolder holder) {
super.onSurfaceDestroyed(holder);
this.visible = false;
handler.removeCallbacks(drawRunner);
}
@Override
public void onSurfaceChanged(SurfaceHolder holder, int format,
int width, int height) {
this.width = width;
this.height = height;
super.onSurfaceChanged(holder, format, width, height);
}
@Override
public void onTouchEvent(MotionEvent event) {
if (touchEnabled) {
float x = event.getX();
float y = event.getY();
SurfaceHolder holder = getSurfaceHolder();
Canvas canvas = null;
try {
canvas = holder.lockCanvas();
if (canvas != null) {
canvas.drawColor(Color.BLACK);
circles.clear();
circles.add(new MyPoint(
String.valueOf(circles.size() + 1), x, y));
drawCircles(canvas, circles);
}
} finally {
if (canvas != null)
holder.unlockCanvasAndPost(canvas);
}
super.onTouchEvent(event);
}
}
private void draw() {
SurfaceHolder holder = getSurfaceHolder();
Canvas canvas = null;
try {
canvas = holder.lockCanvas();
if (canvas != null) {
if (circles.size() >= maxNumber) {
circles.clear();
}
int x = (int) (width * Math.random());
int y = (int) (height * Math.random());
circles.add(new MyPoint(String.valueOf(circles.size() + 1),
x, y));
drawCircles(canvas, circles);
}
} finally {
if (canvas != null)
holder.unlockCanvasAndPost(canvas);
}
handler.removeCallbacks(drawRunner);
if (visible) {
handler.postDelayed(drawRunner, 5000);
}
}
// Surface view requires that all elements are drawn completely
private void drawCircles(Canvas canvas, List<MyPoint> circles) {
canvas.drawColor(Color.BLACK);
for (MyPoint point : circles) {
canvas.drawCircle(point.x, point.y, 20.0f, paint);
}
}
}
}
import java.util.ArrayList;
import java.util.List;
import android.content.SharedPreferences;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.service.wallpaper.WallpaperService;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
public class MyWallpaperService extends WallpaperService {
@Override
public Engine onCreateEngine() {
return new MyWallpaperEngine();
}
private class MyWallpaperEngine extends Engine {
private final Handler handler = new Handler();
private final Runnable drawRunner = new Runnable() {
@Override
public void run() {
draw();
}
};
private List<MyPoint> circles;
private Paint paint = new Paint();
private int width;
int height;
private boolean visible = true;
private int maxNumber;
private boolean touchEnabled;
public MyWallpaperEngine() {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(MyWallpaperService.this);
maxNumber = Integer
.valueOf(prefs.getString("numberOfCircles", "10"));
touchEnabled = prefs.getBoolean("touch", false);
circles = new ArrayList<MyPoint>();
paint.setAntiAlias(true);
paint.setColor(Color.GREEN);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeWidth(10f);
handler.post(drawRunner);
}
@Override
public void onVisibilityChanged(boolean visible) {
this.visible = visible;
if (visible) {
handler.post(drawRunner);
} else {
handler.removeCallbacks(drawRunner);
}
}
@Override
public void onSurfaceDestroyed(SurfaceHolder holder) {
super.onSurfaceDestroyed(holder);
this.visible = false;
handler.removeCallbacks(drawRunner);
}
@Override
public void onSurfaceChanged(SurfaceHolder holder, int format,
int width, int height) {
this.width = width;
this.height = height;
super.onSurfaceChanged(holder, format, width, height);
}
@Override
public void onTouchEvent(MotionEvent event) {
if (touchEnabled) {
float x = event.getX();
float y = event.getY();
SurfaceHolder holder = getSurfaceHolder();
Canvas canvas = null;
try {
canvas = holder.lockCanvas();
if (canvas != null) {
canvas.drawColor(Color.BLACK);
circles.clear();
circles.add(new MyPoint(
String.valueOf(circles.size() + 1), x, y));
drawCircles(canvas, circles);
}
} finally {
if (canvas != null)
holder.unlockCanvasAndPost(canvas);
}
super.onTouchEvent(event);
}
}
private void draw() {
SurfaceHolder holder = getSurfaceHolder();
Canvas canvas = null;
try {
canvas = holder.lockCanvas();
if (canvas != null) {
if (circles.size() >= maxNumber) {
circles.clear();
}
int x = (int) (width * Math.random());
int y = (int) (height * Math.random());
circles.add(new MyPoint(String.valueOf(circles.size() + 1),
x, y));
drawCircles(canvas, circles);
}
} finally {
if (canvas != null)
holder.unlockCanvasAndPost(canvas);
}
handler.removeCallbacks(drawRunner);
if (visible) {
handler.postDelayed(drawRunner, 5000);
}
}
// Surface view requires that all elements are drawn completely
private void drawCircles(Canvas canvas, List<MyPoint> circles) {
canvas.drawColor(Color.BLACK);
for (MyPoint point : circles) {
canvas.drawCircle(point.x, point.y, 20.0f, paint);
}
}
}
}
Steps:
1.) Create a project named LiveWallpaper and set the information as stated in the image.
Build Target: Android 4.0
Application Name: LiveWallpaper
Package Name: com. example. LiveWallpaper
Activity Name: LiveWallpaperActivity
Min SDK Version: 14
2.) Open LiveWallpaperActivity.java file and write following code there:
package com.example.LiveWallpaper;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceActivity;
import android.widget.Toast;
public class LiveWallpaperActivity extends PreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefs);
// We want to add a validator to the number of circles so that it only
// accepts numbers
Preference circlePreference = getPreferenceScreen().findPreference(
"numberOfCircles");
// Add the validator
circlePreference.setOnPreferenceChangeListener(numberCheckListener);
}
Preference.OnPreferenceChangeListener numberCheckListener = new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
// Check that the string is an integer
if (newValue != null && newValue.toString().length() > 0
&& newValue.toString().matches("\\d*")) {
return true;
}
// If now create a message to the user
Toast.makeText(LiveWallpaperActivity.this, "Invalid Input",
Toast.LENGTH_SHORT).show();
return false;
}
};
}
import android.os.Bundle;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceActivity;
import android.widget.Toast;
public class LiveWallpaperActivity extends PreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefs);
// We want to add a validator to the number of circles so that it only
// accepts numbers
Preference circlePreference = getPreferenceScreen().findPreference(
"numberOfCircles");
// Add the validator
circlePreference.setOnPreferenceChangeListener(numberCheckListener);
}
Preference.OnPreferenceChangeListener numberCheckListener = new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
// Check that the string is an integer
if (newValue != null && newValue.toString().length() > 0
&& newValue.toString().matches("\\d*")) {
return true;
}
// If now create a message to the user
Toast.makeText(LiveWallpaperActivity.this, "Invalid Input",
Toast.LENGTH_SHORT).show();
return false;
}
};
}
Output
Layout Animation in Android
This example explains about the default layout animation in android.
Algorithm:
1.) Create a new project by File-> New -> Android Project name it LayoutAnimation.
2.) Write following into main.xml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/gridContainer"
android:animateLayoutChanges="true"
/>
</LinearLayout>
android:animateLayoutChanges="true"
/>
</LinearLayout>
Steps:
1.) Create a project named LayoutAnimation and set the information as stated in the image.
Build Target: Android 4.0
Application Name: LayoutAnimation
Package Name: com. example. LayoutAnimation
Activity Name: LayoutAnimationActivity
Min SDK Version: 14
2.) Open LayoutAnimationActivity.java file and write following code there:
package com.example.layoutanimation;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.GridLayout;
public class LayoutAnimationActivity extends Activity {
private int numButtons = 1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final GridLayout gridContainer = (GridLayout) findViewById(R.id.gridContainer);
Button addButton = (Button) findViewById(R.id.addNewButton);
addButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Button newButton = new Button(LayoutAnimationActivity.this);
newButton.setText(String.valueOf(numButtons++));
newButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
gridContainer.removeView(v);
}
});
gridContainer.addView(newButton, Math.min(1, gridContainer.getChildCount()));
}
});
}
}
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.GridLayout;
public class LayoutAnimationActivity extends Activity {
private int numButtons = 1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final GridLayout gridContainer = (GridLayout) findViewById(R.id.gridContainer);
Button addButton = (Button) findViewById(R.id.addNewButton);
addButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Button newButton = new Button(LayoutAnimationActivity.this);
newButton.setText(String.valueOf(numButtons++));
newButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
gridContainer.removeView(v);
}
});
gridContainer.addView(newButton, Math.min(1, gridContainer.getChildCount()));
}
});
}
}
Output
Calendar Application
This example explains how to call and use system calendar into your application.
Algorithm:
1.) Create a new project by File-> New -> Android Project name it CalendarApplication.
2.) Write following into main.xml file:
<?xml version=<em>"1.0"</em> encoding=<em>"utf-8"</em>?>
<LinearLayout xmlns:android=<em>"http://schemas.android.com/apk/res/android"</em>
android:layout_width=<em>"fill_parent"</em>
android:layout_height=<em>"fill_parent"</em>
android:orientation=<em>"vertical"</em> >
<Button
android:id=<em>"@+id/button1"</em>
android:layout_width=<em>"wrap_content"</em>
android:layout_height=<em>"wrap_content"</em>
android:onClick=<em>"onClick"</em>
android:text=<em>"Create Event"</em> />
<Button
android:id=<em>"@+id/button2"</em>
android:layout_width=<em>"wrap_content"</em>
android:layout_height=<em>"wrap_content"</em>
android:onClick=<em>"queryCalendar"</em>
android:text=<em>"Query Calendar"</em> />
</LinearLayout>
<LinearLayout xmlns:android=<em>"http://schemas.android.com/apk/res/android"</em>
android:layout_width=<em>"fill_parent"</em>
android:layout_height=<em>"fill_parent"</em>
android:orientation=<em>"vertical"</em> >
<Button
android:id=<em>"@+id/button1"</em>
android:layout_width=<em>"wrap_content"</em>
android:layout_height=<em>"wrap_content"</em>
android:onClick=<em>"onClick"</em>
android:text=<em>"Create Event"</em> />
<Button
android:id=<em>"@+id/button2"</em>
android:layout_width=<em>"wrap_content"</em>
android:layout_height=<em>"wrap_content"</em>
android:onClick=<em>"queryCalendar"</em>
android:text=<em>"Query Calendar"</em> />
</LinearLayout>
<uses-permission
android:name=“android.permission.READ_CALENDAR”>
</uses-permission>
<uses-permission
android:name=“android.permission.WRITE_CALENDAR”>
</uses-permission>
4.) Run for output.
Steps:
1.) Create a project named CalendarApplication and set the information as stated in the image.
Build Target: Android 4.0
Application Name: CalendarApplication
Package Name: com. example. CalendarApplication
Activity Name: CalendarApplicationActivity
Min SDK Version: 14
2.) Open CalendarApplicationActivity.java file and write following code there:
<strong>package</strong> com.example.CalendarApplication;
<strong>import</strong> java.util.GregorianCalendar;
<strong>import</strong> android.app.Activity;
<strong>import</strong> android.content.ContentResolver;
<strong>import</strong> android.content.Intent;
<strong>import</strong> android.database.Cursor;
<strong>import</strong> android.net.Uri;
<strong>import</strong> android.os.Bundle;
<strong>import</strong> android.provider.CalendarContract;
<strong>import</strong> android.provider.CalendarContract.Calendars;
<strong>import</strong> android.provider.CalendarContract.Events;
<strong>import</strong> android.view.View;
<strong>import</strong> android.widget.Toast;
<strong>public</strong> <strong>class</strong> CalendarApplicationActivity <strong>extends</strong> Activity {
<strong>public</strong> <strong>static</strong> <strong>final</strong> String[] <em>EVENT_PROJECTION</em> = <strong>new</strong> String[] {
Calendars.<em>_ID</em>, // 0
Calendars.<em>ACCOUNT_NAME</em>, // 1
Calendars.<em>CALENDAR_DISPLAY_NAME</em> // 2
};
<strong>private</strong> <strong>static</strong> <strong>final</strong> <strong>int</strong> <em>PROJECTION_DISPLAY_NAME_INDEX</em> = 2;
@Override
<strong>public</strong> <strong>void</strong> onCreate(Bundle savedInstanceState) {
<strong>super</strong>.onCreate(savedInstanceState);
setContentView(R.layout.<em>main</em>);
}
<strong>public</strong> <strong>void</strong> onClick(View view) {
Intent intent = <strong>new</strong> Intent(Intent.<em>ACTION_INSERT</em>);
intent.setType("vnd.android.cursor.item/event");
intent.putExtra(Events.<em>TITLE</em>, "Learn Android");
intent.putExtra(Events.<em>EVENT_LOCATION</em>, "Home suit home");
intent.putExtra(Events.<em>DESCRIPTION</em>, "Download Examples");
GregorianCalendar calDate = <strong>new</strong> GregorianCalendar(2012, 10, 02);
intent.putExtra(CalendarContract.<em>EXTRA_EVENT_BEGIN_TIME</em>,
calDate.getTimeInMillis());
intent.putExtra(CalendarContract.<em>EXTRA_EVENT_END_TIME</em>,
calDate.getTimeInMillis());
intent.putExtra(CalendarContract.<em>EXTRA_EVENT_ALL_DAY</em>, <strong>true</strong>);
intent.putExtra(Events.<em>RRULE</em>,
"FREQ=WEEKLY;COUNT=11;WKST=SU;BYDAY=TU,TH");
intent.putExtra(Events.<em>ACCESS_LEVEL</em>, Events.<em>ACCESS_PRIVATE</em>);
intent.putExtra(Events.<em>AVAILABILITY</em>, Events.<em>AVAILABILITY_BUSY</em>);
startActivity(intent);
}
<strong>public</strong> <strong>void</strong> queryCalendar(View view) {
Cursor cur = <strong>null</strong>;
ContentResolver cr = getContentResolver();
Uri uri = Calendars.<em>CONTENT_URI</em>;
String selection = "((" + Calendars.<em>ACCOUNT_NAME</em> + " = ?) AND ("
+ Calendars.<em>ACCOUNT_TYPE</em> + " = ?))";
String[] selectionArgs = <strong>new</strong> String[] { "Lars.Vogel@gmail.com",
"com.google" };
cur = cr.query(uri, <em>EVENT_PROJECTION</em>, selection, selectionArgs, <strong>null</strong>);
<strong>while</strong> (cur.moveToNext()) {
String displayName = <strong>null</strong>;
displayName = cur.getString(<em>PROJECTION_DISPLAY_NAME_INDEX</em>);
Toast.<em>makeText</em>(<strong>this</strong>, "Calendar " + displayName, Toast.<em>LENGTH_SHORT</em>)
.show();
}
}
}
<strong>import</strong> java.util.GregorianCalendar;
<strong>import</strong> android.app.Activity;
<strong>import</strong> android.content.ContentResolver;
<strong>import</strong> android.content.Intent;
<strong>import</strong> android.database.Cursor;
<strong>import</strong> android.net.Uri;
<strong>import</strong> android.os.Bundle;
<strong>import</strong> android.provider.CalendarContract;
<strong>import</strong> android.provider.CalendarContract.Calendars;
<strong>import</strong> android.provider.CalendarContract.Events;
<strong>import</strong> android.view.View;
<strong>import</strong> android.widget.Toast;
<strong>public</strong> <strong>class</strong> CalendarApplicationActivity <strong>extends</strong> Activity {
<strong>public</strong> <strong>static</strong> <strong>final</strong> String[] <em>EVENT_PROJECTION</em> = <strong>new</strong> String[] {
Calendars.<em>_ID</em>, // 0
Calendars.<em>ACCOUNT_NAME</em>, // 1
Calendars.<em>CALENDAR_DISPLAY_NAME</em> // 2
};
<strong>private</strong> <strong>static</strong> <strong>final</strong> <strong>int</strong> <em>PROJECTION_DISPLAY_NAME_INDEX</em> = 2;
@Override
<strong>public</strong> <strong>void</strong> onCreate(Bundle savedInstanceState) {
<strong>super</strong>.onCreate(savedInstanceState);
setContentView(R.layout.<em>main</em>);
}
<strong>public</strong> <strong>void</strong> onClick(View view) {
Intent intent = <strong>new</strong> Intent(Intent.<em>ACTION_INSERT</em>);
intent.setType("vnd.android.cursor.item/event");
intent.putExtra(Events.<em>TITLE</em>, "Learn Android");
intent.putExtra(Events.<em>EVENT_LOCATION</em>, "Home suit home");
intent.putExtra(Events.<em>DESCRIPTION</em>, "Download Examples");
GregorianCalendar calDate = <strong>new</strong> GregorianCalendar(2012, 10, 02);
intent.putExtra(CalendarContract.<em>EXTRA_EVENT_BEGIN_TIME</em>,
calDate.getTimeInMillis());
intent.putExtra(CalendarContract.<em>EXTRA_EVENT_END_TIME</em>,
calDate.getTimeInMillis());
intent.putExtra(CalendarContract.<em>EXTRA_EVENT_ALL_DAY</em>, <strong>true</strong>);
intent.putExtra(Events.<em>RRULE</em>,
"FREQ=WEEKLY;COUNT=11;WKST=SU;BYDAY=TU,TH");
intent.putExtra(Events.<em>ACCESS_LEVEL</em>, Events.<em>ACCESS_PRIVATE</em>);
intent.putExtra(Events.<em>AVAILABILITY</em>, Events.<em>AVAILABILITY_BUSY</em>);
startActivity(intent);
}
<strong>public</strong> <strong>void</strong> queryCalendar(View view) {
Cursor cur = <strong>null</strong>;
ContentResolver cr = getContentResolver();
Uri uri = Calendars.<em>CONTENT_URI</em>;
String selection = "((" + Calendars.<em>ACCOUNT_NAME</em> + " = ?) AND ("
+ Calendars.<em>ACCOUNT_TYPE</em> + " = ?))";
String[] selectionArgs = <strong>new</strong> String[] { "Lars.Vogel@gmail.com",
"com.google" };
cur = cr.query(uri, <em>EVENT_PROJECTION</em>, selection, selectionArgs, <strong>null</strong>);
<strong>while</strong> (cur.moveToNext()) {
String displayName = <strong>null</strong>;
displayName = cur.getString(<em>PROJECTION_DISPLAY_NAME_INDEX</em>);
Toast.<em>makeText</em>(<strong>this</strong>, "Calendar " + displayName, Toast.<em>LENGTH_SHORT</em>)
.show();
}
}
}
Output
4.) If your phone doesn’t have any default calendar installed you will see the screen as below. Follow the instructions and see your calendar.
No comments:
Post a Comment