Android Project

Android Project
Android Project

Monday, November 21, 2011

Running a service in background on Android


Here the code is generate to run some process in background through service. For example we are running the time in background and displaying it in the UI. The service coding will be in a seperate class MyService.java


MyService.java
package com.services.demo;

import java.util.Date;
import android.app.Service; import android.content.Intent; import android.os.Handler; import android.os.IBinder; public class MyService extends Service { public static final String BROADCAST_ACTION = "com.services.demo.ServiceDemoActivity"; private final Handler handler = new Handler(); Intent intent;

int counter = 0; @Override public void onCreate() { // Called on service created intent = new Intent(BROADCAST_ACTION); } @Override

public void onDestroy() { // Called on service stopped }

@Override public void onStart(Intent intent, int startid) { int i = 0; while (i < 101) { if (i > 100) { this.onDestroy(); } else { counter = i; i++; handler.removeCallbacks(sendUpdatesToUI); handler.postDelayed(sendUpdatesToUI, 1 * 1000); // 1 sec }

} } private Runnable sendUpdatesToUI = new Runnable() { public void run() { DisplayLoggingInfo(); handler.postDelayed(this, 1 * 1000); // 1 sec }

}; private void DisplayLoggingInfo() { intent.putExtra("time", new Date().toLocaleString()); intent.putExtra("counter", String.valueOf(counter)); sendBroadcast(intent); }

public static boolean isRunning() { return true; } @Override

public IBinder onBind(Intent intent) { return null; } }

So for starting the service and stopping the service we will be using


Java
startService(new Intent(ServiceDemoActivity.this, MyService.class));
stopService(new Intent(ServiceDemoActivity.this, MyService.class));

For updating the UI we need to use the broadcast service. In that BroadcastReceiver we will update the UI

Java
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
updateDate(intent);
}

}; private void updateDate(Intent intent) { String time = intent.getStringExtra("time"); TextView date = (TextView) findViewById(R.id.date); date.setText(time); }
In the MyService.java the method DisplayLoggingInfo() will send the broadcast to the activity to update the UI, the UI xml code is
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 >
<TextView
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:text="@string/hello"
 android:id="@+id/notification"
 />

 <TextView
 android:layout_width="fill_parent" android:id="@+id/date"
 android:layout_height="wrap_content" android:text="" android:gravity="center" android:textSize="20sp" android:padding="20dp"/>
 <Button android:id="@+id/stop" android:text="Stop Service" android:layout_width="wrap_content" android:layout_height="wrap_content" />
</LinearLayout>

If we are opening the application on the first time means, it will be like this

and if we go out and come back to the page means, it will be showing a message like this

and if we stop the service means, it will be showing a message like this



You can download the full source code



Download source


Have a good day.

Tuesday, November 8, 2011

Android Keyboard Shortcuts - hotkeys

We are going to see a set of keyboard shortcuts of Android OS to help you. Some hotkeys may vary from each device. Most of the them are listed here,

Android Keyboard Shortcuts:

Spacebar: Page down in any Web page/document view

Shift + Spacebar: Page up in any Web page/document view

Android Keyboard Shortcuts: Typing

Alt + Spacebar: Insert a special character

Shift + Del: Delete the character to the right of the cursor

Alt + Del: Delete an entire line

Shift + Shift (press it twice): Activate caps-lock; press shift once more to exit

Alt + Trackball-Left: Move cursor to beginning of line

Alt + Trackball-Right: Move cursor to end of line

Alt + Trackball-Up: Move cursor to top of page

Alt + Trackball-Down: Move cursor to bottom of page

Shift + Trackball-Left/Right: Highlight text for cutting or copying

Menu + X: Cut text (will cut all text on-screen unless specific characters are highlighted)

Menu + C: Copy text to clipboard (will copy all text on-screen unless specific characters are highlighted)

Menu + V: Paste text from clipboard

Menu + A: Select all text in the current field

Android Keyboard Shortcuts: Browsing

Menu + I: Zoom in

Menu + O: Zoom out

Menu + J: Go back a page

Menu + K: Go forward a page

Menu + R: Refresh current page

Menu + F: Find on page

Menu + B: Open bookmarks

Menu + S: Open social network sharing menu

Menu + H: View browsing history

Menu + S: Open browser settings

Android Keyboard Shortcuts: Gmail

F: Forward current message (works only while inside the message)

R: Reply to current message (works only while inside the message)

A: Reply-all to current message (works only while inside the message)

Y: Archive message (works from within message or while on main inbox list)

Menu + U: Refresh inbox

Menu + C: Compose new e-mail

Enter: Open an e-mail (from the main inbox list)

Alt + Trackball-Up: Jump to top of inbox

Alt + Trackball-Down: Jump to bottom of inbox

Android Keyboard Shortcuts: Apps

Search + B: Open browser

Search + C: Open contacts

Search + E: Open e-mail

Search + G: Open Gmail

Search + I: Open calendar

Search + M: Open maps

Search + P: Open music

Search + S: Open text messaging

Search + Y: Open YouTube

You can also customize the keyboard shortcuts for applications: Just go into "Applications" off the main system settings menu, then select "Quick Launch." From there, you can change any of the above app-controlling hotkeys and add in your own.

Monday, November 7, 2011

Show or Hide soft keyboard on opening a dialog or activity in android

For showing the soft keyboard on entering into the activity or to the dialog we can use this coding


Java


InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);



and for hiding the keyboard



Java

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(singleedittext.getWindowToken(),0);



Have a nice day!

Tuesday, November 1, 2011

Animation for view and activities with and without viewflipper in Android

Now we are going to see some animations in android, three types of animation are given on this pack



Yes as shown in the image we are going to see all these types.
First we can see about Animation using ViewFlipper



Here i had added three views in the viewflipper and i had called the animation changes on scrolling using touchevent, the xml section will be like this


viewer.xml

<?xml version="1.0" encoding="utf-8"?>

<ViewFlipper xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_margin="5dip"
android:id="@+id/layoutswitcher"
android:layout_width="fill_parent"
android:layout_height="500dp">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_height="wrap_content"
android:padding="20dip"
android:background="@android:color/background_light"
android:text="Currently you are in Page 1. Scroll right or left to see next page"
android:layout_width="fill_parent"
android:layout_weight="1"
android:textStyle="bold" >
</TextView>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_height="wrap_content"
android:padding="20dip"
android:background="@android:color/darker_gray"
android:text="Currently you are in Page 2. Scroll right or left to see next page"
android:layout_width="fill_parent"
android:layout_weight="1"
android:textStyle="bold" >
</TextView>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_height="wrap_content"
android:padding="20dip"
android:background="@android:color/white"
android:text="Currently you are in Page 3. Scroll right or left to see next page"
android:layout_width="fill_parent"
android:layout_weight="1"
android:textStyle="bold" >
</TextView>
</LinearLayout>
</ViewFlipper>



and in the java we need to apply the animation on touchevent as



ViewerEffect.java

package com.animmer;

import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ViewFlipper;

public class ViewerEffect extends Activity {

private ViewFlipper vf;
private float oldTouchValue;

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

vf = (ViewFlipper) findViewById(R.id.layoutswitcher);
}

//for the previous movement
public static Animation inFromRightAnimation() {

Animation inFromRight = new TranslateAnimation(
Animation.RELATIVE_TO_PARENT, +1.0f, Animation.RELATIVE_TO_PARENT, 0.0f,
Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f
);
inFromRight.setDuration(400);
inFromRight.setInterpolator(new AccelerateInterpolator());
return inFromRight;
}
public static Animation outToLeftAnimation() {
Animation outtoLeft = new TranslateAnimation(
Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, -1.0f,
Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f
);
outtoLeft.setDuration(400);
outtoLeft.setInterpolator(new AccelerateInterpolator());
return outtoLeft;
}
// for the next movement
public static Animation inFromLeftAnimation() {
Animation inFromLeft = new TranslateAnimation(
Animation.RELATIVE_TO_PARENT, -1.0f, Animation.RELATIVE_TO_PARENT, 0.0f,
Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f
);
inFromLeft.setDuration(400);
inFromLeft.setInterpolator(new AccelerateInterpolator());
return inFromLeft;
}
public static Animation outToRightAnimation() {
Animation outtoRight = new TranslateAnimation(
Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, +1.0f,
Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f
);
outtoRight.setDuration(400);
outtoRight.setInterpolator(new AccelerateInterpolator());
return outtoRight;
}

@Override
public boolean onTouchEvent(MotionEvent touchevent) {
switch (touchevent.getAction())
{
case MotionEvent.ACTION_DOWN:
{
oldTouchValue = touchevent.getX();
break;
}
case MotionEvent.ACTION_UP:
{
float currentX = touchevent.getX();
if (oldTouchValue < currentX)
{
vf.setInAnimation(inFromLeftAnimation());
vf.setOutAnimation(outToRightAnimation());
vf.showNext();
}
if (oldTouchValue > currentX)
{
vf.setInAnimation(inFromRightAnimation());
vf.setOutAnimation(outToLeftAnimation());
vf.showPrevious();
}
break;
}
}
return false;
}
}




Likewise the next is animation between activities



Yes we here we will be giving animation effect between activities
For animation effects we need to put four files in the anim folder, they are slide_in_left, slide_out_left, slide_in_right and slide_out_right.


Java

overridePendingTransition( R.anim.slide_in_left, R.anim.slide_out_left );


The above code is used to move left to right



Java

overridePendingTransition( R.anim.slide_in_right, R.anim.slide_out_right );


The above code is used to move right to left

The final animation technique is to hide and show the views



Here we will be using touch event to assign the animation part, the animation objects will be assigned as shown below


Java

mAnimShow = AnimationUtils.loadAnimation(this, R.anim.slide_in_left);
mAnimHide = AnimationUtils.loadAnimation(this, R.anim.slide_out_right);

mAnimShow.setAnimationListener(new AnimationListener() {

@Override
public void onAnimationRepeat(Animation animation) {
// TODO Auto-generated method stub

}

@Override
public void onAnimationStart(Animation animation) {
overridePendingTransition( R.anim.slide_in_left, R.anim.slide_out_left );

}

@Override
public void onAnimationEnd(Animation animation) {


}

});

mAnimHide.setAnimationListener(new AnimationListener() {

@Override
public void onAnimationRepeat(Animation animation) {
// TODO Auto-generated method stub

}

@Override
public void onAnimationStart(Animation animation) {
overridePendingTransition( R.anim.slide_in_right, R.anim.slide_out_right );

}

@Override
public void onAnimationEnd(Animation animation) {


}

});


The full source code is provided below, you can apply these animation for any other purpose also, the animation technique is same, we need to put this in our logic.


You can download the full source code


Download source


Have a good day.

Monday, October 24, 2011

Google unveils what's new in Android 4 'Ice Cream Sandwich'

Unified mobile OS for tablets and smartphones clones some iOS features and focuses on a slicker UI and new developer APIs


Google has finally unveiled Android 4.0, the unified version of its mobile OS for smartphones and tablets best known by its "Ice Cream Sandwich" code name. The revised Android, which made its debut on a Samsung Galaxy Nexus smartphone (video) also unveiled Tuesday, features a bevy of UI enhancements, social networking integration, and other APIs meant to encourage human and application-based sharing. Android has also beefed up some of its security capabilities, though most are in the form of API support that developers can use as desired.

Google did not provide a release date for Android 4, but did say the Galaxy Nexus running it would be available in November. Available now is the updated Android SDK, so developers can begin modifying or creating applications for Android 4.

[ Paul Krill shares developers' expectations for Android 4. | See how badly Apple's iOS 5 trounced Android 3.2 "Honeycomb" and Android 2.3 "Gingerbread" in InfoWorld's tests. | Subscribe to InfoWorld's Mobilize newsletter for the latest developments in mobile technology. ]

For business users, Android 4 integrates multiple email accounts more completely and now supports Exchange email folders. It also lets users take screenshots from their devices. (Both are longtime iOS capabilities.) Google made some minor adjustments to Android's security and management capabilities by supporting the most recent version of Microsoft's Exchange ActiveSync (EAS) protocol, including newfound support for EAS certificate authentication, use of ABQ strings for device type and mode, an option for IT to disable automatic sync while roaming, and an option for IT to limit attachment size or disable attachments. Also added is support for disabling the device's camera via EAS.

On the security front, Android 4 adopts the better security capabilities found in the tablet version of Android ("Honeycomb") such as on-device encryption, but appears to be leaving deeper management APIs to third parties such as 3LM.

But Android 4 does have a new keychain API, and underlying encrypted storage lets applications store and retrieve private keys and their corresponding certificate chains. Applications can use the keychain API to install and store user certificates and certificate authorities. Android 4 also provides address space layout randomization (ASLR) -- a feature that has helped iOS lead in terms of onboard security capabilities -- to protect system and third-party applications from exploitation due to memory-management issues.


Android 4 also borrows some features introduced in Apple's iOS 5, such as the ability to apply silly effects to video (using the Photo Booth app in iOS), to edit and adjust photos (an enhancement to iOS 5's Photos app), and to sync Chrome browser bookmarks via the cloud (one component of Apple's iCloud service). Camera enhancements include single-motion panoramic capture, automatic facial focus, and stabilized image zoom. The latter two are enhancements found in the recently released Apple iPhone 4S.

Unique capabilities in Android 4 include face identification that can be used in lieu of passwords and the ability in the Chrome browser to tell websites to provide their full desktop vesions rather than their mobile-optimized versions.

In the revised OS, a new social API lets developers create applications that can integrate contacts, profile data, and calendar events from any of the user's activities or social networks. Calendar services are also now made accessible to apps. A new sharing API lets apps share data through a standard mechanism across the OS.

Android 4 also supports Wi-Fi Direct, a recent standard for creating ad hoc wireless networks among devices, and Bluetooth-based health care devices, such as wireless monitoring equipment. Android 4 now supports styli with a set of APIs that can distinguish pressure, angle, and other pen-oriented input nuances. The combination of support for Bluetooth-enabled medical equipment and pen input suggests Google may be making a push into the health care market with its tablets.

As previously promised, Android 4 also supports near-field communications for use in mobile payment systems and for "beaming" bursts of data between devices.

The UI changes appear meant to provide more customized information to users, such as sizable widgets and configurable alert displays, as well as more gesture controls for interacting with tasks rather than relying so heavily on Android's menus. Google has published a summary of the Android 4 changes at its website.

source is taken from http://www.infoworld.com/d/mobile-technology/google-unveils-whats-new-in-android-4-ice-cream-sandwich-176549?page=0,0&source=IFWNLE_nlt_daily_2011-10-19


Tuesday, October 18, 2011

Check whether service is running or not in android application

Using the below given code we can check whether a particular service in our application is running or not


Java

private boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if ("com.dir.pack.DemoService".equals(service.service.getClassName())) {
return true;
}
}
return false;
}


Here in the if condition we need to give the service file name with the package. So on the checking area you can simply call this function in the if statement like



Java

if(isMyServiceRunning()) {
System.out.println("Service is running");
} else {
System.out.println("Service is not running");
}


Have a nice day

Friday, September 23, 2011

Image and content is populated from Sqlite in Android

In this below application we had populated the listview's data and image from the sqlite



Here we are using a java class for creating the table


PlaceDataSQL.java
package com.data.pack;

package com.data.pack;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/** Helper to the database, manages versions and creation */
public class PlaceDataSQL extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "sample.db";
private static final int DATABASE_VERSION = 1;

private Context context;

public PlaceDataSQL(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE gallery (id varchar(20), image BLOB,caption varchar(160),description varchar(200))");
}

private void versionUpdation(SQLiteDatabase db) {

}

/**
* Check if the database already exist to avoid re-copying the file each
* time you open the application.
*
* @return true if it exists, false if it doesn't
*/
public boolean checkDataBase(String db) {

SQLiteDatabase checkDB = null;

try {
String myPath = "data/data/com.data.pack/databases/" + db;
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);

} catch (SQLiteException e) {

// database does't exist yet.

} catch (Exception e) {

}

if (checkDB != null) {

checkDB.close();

}

return checkDB != null ? true : false;
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion >= newVersion)
return;

if (oldVersion == 1) {
Log.d("New Version", "Datas can be upgraded");
}

Log.d("Sample Data", "onUpgrade : " + newVersion);
}

}



Here in the onCreate function the table is created, here for image we are using blog, so that we can insert the image inside the table itself and the onUpgrade function is used to upgrade the table on the next release, for example you had create an application and published it in market and a guy is using your application, now suddenly you like to add another field on your table means you need to change the " DATABASE_VERSION " to 2 and in the onUpgrade funtion you need to write the alter query there. Likewise i had using a funtion checkDataBase(), this is to check whether the database is exist or not.

Then in the main activity we are calling delete to delete the table content, likewise we will be using a function insertData, inside this function we will be inserting data to the table, like that we will be using getDataAndPopulate(), here we will be retrieving data from the table and displaying in the list.

The main thing is we inserting the image to database for this we are using HttpClient and on the retriving time it is very easy to assign the data, so while calling on the next time we can assign and there is no need of url call for showing image.


SqliteDBActivity.java
package com.data.pack;


package com.data.pack;


import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.ListActivity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class SqliteDBActivity extends ListActivity {
private static PlaceDataSQL placeData;
private ArrayList id = new ArrayList();
private ArrayList image = new ArrayList();
private ArrayList caption = new ArrayList();
private ArrayList description = new ArrayList();
private Button populate;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
populate = (Button) findViewById(R.id.populate);
placeData = new PlaceDataSQL(this);

SQLiteDatabase db = placeData.getWritableDatabase();

Cursor cursors = getRawEvents("select * from gallery");

if (cursors.moveToNext()) {
populate.setVisibility(View.GONE);
getDataAndPopulate();
} else {
populate.setVisibility(View.VISIBLE);
}


db.delete("gallery", "id=?", new String[] {
"12" });
populate.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
try {
callInsertion("1","http://2.bp.blogspot.com/-bkmnlZUKXPs/TjZeTVCgp9I/AAAAAAAAAHI/SPnWJYqq4uQ/s1600/twitter_follow.gif","First","This is the first item");
callInsertion("2","http://1.bp.blogspot.com/-HDNFnyRU2Cw/TcuMbBaL70I/AAAAAAAAAGc/7eWN1qnZbAw/s320/seek.JPG","Second","This is the second item");
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

getDataAndPopulate();
}
});

}

private void callInsertion(String id, String url, String caption, String description) throws ClientProtocolException, IOException {
DefaultHttpClient mHttpClient = new DefaultHttpClient();
HttpGet mHttpGet = new HttpGet(url);
HttpResponse mHttpResponse = mHttpClient.execute(mHttpGet);
if (mHttpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = mHttpResponse.getEntity();
if ( entity != null) {
// insert to database
insertData(id,EntityUtils.toByteArray(entity),caption,description);
}
}
}

private void insertData(String id, byte[] image, String caption, String description) {
SQLiteDatabase db = placeData.getWritableDatabase();
ContentValues values;
values = new ContentValues();
values.put("id", id);
values.put("image", image);
values.put("caption", caption);
values.put("description", description);

db.insert("gallery", null, values);
}

private void getDataAndPopulate() {
id = new ArrayList();
image = new ArrayList();
caption = new ArrayList();
description = new ArrayList();
Cursor cursor = getEvents("gallery");
while (cursor.moveToNext()) {
String temp_id = cursor.getString(0);
byte[] temp_image = cursor.getBlob(1);
String temp_caption = cursor.getString(2);
String temp_description = cursor.getString(3);
id.add(temp_id);
image.add(temp_image);
caption.add(temp_caption);
description.add(temp_description);
}
String[] captionArray = (String[]) caption.toArray(
new String[caption.size()]);

ItemsAdapter itemsAdapter = new ItemsAdapter(
SqliteDBActivity.this, R.layout.item,
captionArray);
setListAdapter(itemsAdapter);
populate.setVisibility(View.GONE);
}


private class ItemsAdapter extends BaseAdapter {
String[] items;

public ItemsAdapter(Context context, int textViewResourceId,
String[] items) {
this.items = items;
}

@Override
public View getView(final int POSITION, View convertView,
ViewGroup parent) {
TextView desc;
TextView cap;
View view = convertView;
ImageView img;
if (view == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.item, null);

}
img = (ImageView) view.findViewById(R.id.image);
cap = (TextView) view.findViewById(R.id.caption);

desc = (TextView) view.findViewById(R.id.description);

cap.setText(caption.get(POSITION));
desc.setText(description.get(POSITION));
img.setImageBitmap(BitmapFactory.decodeByteArray(image.get(POSITION), 0, image.get(POSITION).length));


return view;
}

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

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

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

private Cursor getRawEvents(String sql) {
SQLiteDatabase db = (placeData).getReadableDatabase();
Cursor cursor = db.rawQuery(sql, null);

startManagingCursor(cursor);
return cursor;
}

private Cursor getEvents(String table) {
SQLiteDatabase db = (placeData).getReadableDatabase();
Cursor cursor = db.query(table, null, null, null, null, null, null);

startManagingCursor(cursor);
return cursor;
}
}


In this example i had wrote two types of retrieving methods from the table, by writing the query and specifying the table name itself.

You can download the full source code


Download source


Have a good day.

Monday, September 19, 2011

Customize the tab in Android

I had attached two tab examples






First we are going to see about First example


CustomTabActivity.java

package com.customs.tabs;

import com.customs.tabs.R;
import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TextView;

public class CustomTabActivity extends TabActivity{
private TabHost tabHost;

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

private void setTabs() {
tabHost = getTabHost();

addTab(R.string.tab_1, R.drawable.info);
addTab(R.string.tab_2, R.drawable.info);
addTab(R.string.tab_3, R.drawable.info);
}

private void addTab(int labelId, int drawableId) {
Intent intent = new Intent(this, TabAct.class);
TabHost.TabSpec spec = tabHost.newTabSpec("tab" + labelId);

View tabIndicator = LayoutInflater.from(this).inflate(R.layout.indicator, getTabWidget(), false);

TextView title = (TextView) tabIndicator.findViewById(R.id.title);
title.setText(labelId);
ImageView icon = (ImageView) tabIndicator.findViewById(R.id.icon);
icon.setImageResource(drawableId);

spec.setIndicator(tabIndicator);
spec.setContent(intent);
tabHost.addTab(spec);

}
}


The class extends TabActivity and the header of the tab is provided in seperate activity which is called on the addTab method. The selection / unselection / active colors are mentioned in the indicator xml file in the layout



indicator.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="0dip"
android:layout_height="64dip"
android:layout_weight="1"
android:orientation="vertical"
android:background="@drawable/indicator"
android:padding="5dp">

<ImageView android:id="@+id/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
/>

<TextView android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
style="?android:attr/tabWidgetStyle"
/>
</RelativeLayout>


Now we can see the Second example of Tab

Here we are not going to extend the tabactivity, instead of that we can set the tab headers through setting background images or colors using xml and without using xml


CustomTabs.java

package com.customized.tabs;

import com.customized.tabs.R;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.TabHost.TabContentFactory;
import android.widget.TabHost.TabSpec;

public class CustomTabs extends Activity {

private TabHost mTabHost;
private TextView mTabLayout;

private void setupTabHost() {
mTabHost = (TabHost) findViewById(android.R.id.tabhost);
mTabHost.setup();
mTabLayout = (TextView) findViewById(R.id.taber);
mTabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {

@Override
public void onTabChanged(String tabId) {
mTabHost.getTabWidget().getChildAt(0)
.setBackgroundResource(R.drawable.m2);
if ("Tab 1".equals(tabId)) {
mTabHost.getTabWidget().getChildAt(0)
.setBackgroundResource(R.drawable.m1);
mTabLayout.setText("This is Tab 1");
} else if("Tab 2".equals(tabId)) {
mTabLayout.setText("This is Tab 2");
} else {
mTabLayout.setText("This is Tab 3");
}
}
});
}

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// construct the tabhost
setContentView(R.layout.main);

setupTabHost();

//mTabHost.getTabWidget().setDividerDrawable(R.drawable.divider);

setupTab(new TextView(this), "Tab 1");
setupTab(new TextView(this), "Tab 2");
setupTab(new TextView(this), "Tab 3");
}

private void setupTab(final View view, final String tag) {
View tabview = createTabView(mTabHost.getContext(), tag);

TabSpec setContent = mTabHost.newTabSpec(tag).setIndicator(tabview).setContent(new TabContentFactory() {
public View createTabContent(String tag) {return view;}
});
mTabHost.addTab(setContent);
if ("Tab 1".equals(tag))
mTabHost.getTabWidget().getChildAt(0).setBackgroundResource(
R.drawable.m1);


}

private static View createTabView(final Context context, final String text) {
View view = LayoutInflater.from(context).inflate(R.layout.bg, null);
TextView tv = (TextView) view.findViewById(R.id.tabsText);
tv.setText(text);
return view;
}
}


In the above code i had commented the divider between each header, if you need means you can uncomment and i had set a different image for the Tab 1 alone, if you need you can set different images for each tab like that. Then in the bg_selector.xml i had commented the xml files for background color and i had set images for that

You can download the full source code


Download source


Have a good day.

Using Sqlite to populate a ListView in Android

In this below application we had populated the listview using the data from the sqlite



Here we are using a java class for creating the table


PlaceDataSQL.java
package com.data.pack;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/** Helper to the database, manages versions and creation */
public class PlaceDataSQL extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "sample.db";
private static final int DATABASE_VERSION = 1;

private Context context;

public PlaceDataSQL(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE gallery (id varchar(20), image varchar(2000),caption varchar(160),description varchar(200))");
}

private void versionUpdation(SQLiteDatabase db) {

}

/**
* Check if the database already exist to avoid re-copying the file each
* time you open the application.
*
* @return true if it exists, false if it doesn't
*/
public boolean checkDataBase(String db) {

SQLiteDatabase checkDB = null;

try {
String myPath = "data/data/com.data.pack/databases/" + db;
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);

} catch (SQLiteException e) {

// database does't exist yet.

} catch (Exception e) {

}

if (checkDB != null) {

checkDB.close();

}

return checkDB != null ? true : false;
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion >= newVersion)
return;

if (oldVersion == 1) {
Log.d("New Version", "Datas can be upgraded");
}

Log.d("Sample Data", "onUpgrade : " + newVersion);
}

}


Here in the onCreate function the table is created and the onUpgrade function is used to upgrade the table on the next release, for example you had create an application and published it in market and a guy is using your application, now suddenly you like to add another field on your table means you need to change the " DATABASE_VERSION " to 2 and in the onUpgrade funtion you need to write the alter query there. Likewise i had using a funtion checkDataBase(), this is to check whether the database is exist or not.

Then in the main activity we are calling delete to delete the table content, likewise we will be using a function insertData, inside this function we will be inserting data to the table, like that we will be using getDataAndPopulate(), here we will be retrieving data from the table and displaying in the list.



SqliteDBActivity.java
package com.data.pack;


import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import android.app.ListActivity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class SqliteDBActivity extends ListActivity {
private static PlaceDataSQL placeData;
private ArrayList id = new ArrayList();
private ArrayList image = new ArrayList();
private ArrayList caption = new ArrayList();
private ArrayList description = new ArrayList();
private Button populate;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
populate = (Button) findViewById(R.id.populate);
placeData = new PlaceDataSQL(this);

SQLiteDatabase db = placeData.getWritableDatabase();

Cursor cursors = getRawEvents("select * from gallery");

if (cursors.moveToNext()) {
populate.setVisibility(View.GONE);
getDataAndPopulate();
} else {
populate.setVisibility(View.VISIBLE);
}


db.delete("gallery", "id=?", new String[] {
"12" });
populate.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
insertData("1","http://2.bp.blogspot.com/-bkmnlZUKXPs/TjZeTVCgp9I/AAAAAAAAAHI/SPnWJYqq4uQ/s1600/twitter_follow.gif","First","This is the first item");
insertData("2","http://1.bp.blogspot.com/-HDNFnyRU2Cw/TcuMbBaL70I/AAAAAAAAAGc/7eWN1qnZbAw/s320/seek.JPG","Second","This is the second item");
getDataAndPopulate();
}
});

}

private void insertData(String id, String image, String caption, String description) {
SQLiteDatabase db = placeData.getWritableDatabase();
ContentValues values;
values = new ContentValues();
values.put("id", id);
values.put("image", image);
values.put("caption", caption);
values.put("description", description);

db.insert("gallery", null, values);
}

private void getDataAndPopulate() {
id = new ArrayList();
image = new ArrayList();
caption = new ArrayList();
description = new ArrayList();
Cursor cursor = getEvents("gallery");
while (cursor.moveToNext()) {
String temp_id = cursor.getString(0);
String temp_image = cursor.getString(1);
String temp_caption = cursor.getString(2);
String temp_description = cursor.getString(3);
id.add(temp_id);
image.add(temp_image);
caption.add(temp_caption);
description.add(temp_description);
}
String[] captionArray = (String[]) caption.toArray(
new String[caption.size()]);

ItemsAdapter itemsAdapter = new ItemsAdapter(
SqliteDBActivity.this, R.layout.item,
captionArray);
setListAdapter(itemsAdapter);
populate.setVisibility(View.GONE);
}


private class ItemsAdapter extends BaseAdapter {
String[] items;

public ItemsAdapter(Context context, int textViewResourceId,
String[] items) {
this.items = items;
}

@Override
public View getView(final int POSITION, View convertView,
ViewGroup parent) {
TextView desc;
TextView cap;
View view = convertView;
ImageView img;
if (view == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.item, null);

}
img = (ImageView) view.findViewById(R.id.image);
cap = (TextView) view.findViewById(R.id.caption);

desc = (TextView) view.findViewById(R.id.description);

cap.setText(caption.get(POSITION));
desc.setText(description.get(POSITION));
try {
URL url = new URL(image.get(POSITION));
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
BitmapFactory.Options bfOptions = new BitmapFactory.Options();
bfOptions.inDither = false; // Disable Dithering
// mode
bfOptions.inPurgeable = true; // Tell to gc that
// whether it needs
// free memory, the
// Bitmap can be
// cleared
bfOptions.inInputShareable = true; // Which kind of
// reference
// will be used
// to recover
// the Bitmap
// data after
// being clear,
// when it will
// be used in
// the future
bfOptions.inTempStorage = new byte[16 * 1024];
Bitmap bmp = null;
bmp = BitmapFactory.decodeStream(input, null,
bfOptions);
img.setImageBitmap(bmp);
connection.disconnect();
input.close();

} catch (MalformedURLException e) {
} catch (IOException e) {
} catch (IllegalAccessError e) {
} catch (NullPointerException e) {
}

return view;
}

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

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

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

private Cursor getRawEvents(String sql) {
SQLiteDatabase db = (placeData).getReadableDatabase();
Cursor cursor = db.rawQuery(sql, null);

startManagingCursor(cursor);
return cursor;
}

private Cursor getEvents(String table) {
SQLiteDatabase db = (placeData).getReadableDatabase();
Cursor cursor = db.query(table, null, null, null, null, null, null);

startManagingCursor(cursor);
return cursor;
}
}


In this example i had wrote two types of retrieving methods from the table, by writing the query and specifying the table name itself.

You can download the full source code


Download source


Have a good day.

Sunday, July 31, 2011

Creating keystore and google api key for android google maps

Open the command prompt and follow the steps

D:\android-sdk-windows-1.6_r1\tools>keytool -genkey -v -keystore projectkey.keystore -alias aliasname -keyalg RSA -keysize 2048 -validity 15000
Enter keystore password: ------------
What is your first and last name?
[Unknown]: ------------
What is the name of your organizational unit?
[Unknown]: ------------
What is the name of your organization?
[Unknown]: ------------
What is the name of your City or Locality?
[Unknown]: ------------
What is the name of your State or Province?
[Unknown]: ------------
What is the two-letter country code for this unit?
[Unknown]: ------------

D:\android-sdk-windows-1.6_r1\tools>keytool -list -alias aliasname -keystore projectkey.keystore
Enter keystore password:
aliasname, Dec 7, 2010, PrivateKeyEntry,
Certificate fingerprint (MD5): CA:CF:AA:0E:5A:2B:88:C8:64:F1:FA:F7:29:21:50:FF

Using your Certificate fingerprint (MD5) get google api key from this site
http://code.google.com/android/maps-api-signup.html

Saturday, July 30, 2011

How to Install APK Files on Android Emulator using command prompt (cmd) without eclipse

Here we are going to see how to run (install) the apk file to the Android emulator without using eclipse.

Installing in different OS:

1. a Windows, Mac OS X (intel) or Linux (i386) powered computer
2. the Android Software Development Kit (SDK).


You do not need Eclipse or Eclipse-plugin the Android Development Tools (ADT). The last two are required for the software development for Android, but are not necessary for application evaluation on emulator.

First download the Android SDK, which may be obtained here: http://code.google.com/android/download.html

Follow the instruction, described in the topic "Installing SDK" from the Google manual, which is located here: http://code.google.com/android/intro/installing.html#installingsdk or you can go with http://android-codes-examples.blogspot.com/search/label/installation

Steps need to be followed:

Installing the SDK

After downloading the SDK, unpack the .zip archive to a suitable location on your machine. For the rest of this document, we will refer to the directory where you installed the SDK as $SDK_ROOT.

Optionally, you can add $SDK_ROOT/tools and $SDK_ROOT/platform-tools to your path:

On Linux, edit your ~/.bash_profile or ~/.bashrc file. Look for a line that sets the PATH environment variable and add the full path to your $SDK_ROOT/tools to it. If you don't see a line setting the path, you can add one:

export PATH=${PATH}:
On a Mac, look in your home directory for .bash_profile and proceed as for Linux. You can create the .bash_profile, if you haven't already set one up on your machine.
On Windows, right click on My Computer, and select Properties. Under the Advanced tab, hit the Environment Variables button, and in the dialog that comes up, double-click on Path under System Variables, and add the full path to the tools/ directory under $SDK_ROOT to it.

Adding $SDK_ROOT/tools to your path lets you run Android Debug Bridge (adb) and the other command line tools without needing to supply the full path to the tools directory. Note that, if you update your SDK, you should remember to update your PATH settings to point to the new location, if different.


-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-

Now navigate to the $SDK_ROOT/tools directory and execute the file 'emulator.exe'. This is the Android emulator itself. Wait couple of minutes until it loads. Now you must see the home screen of Android - wallpapers with snowy mountains on the background and the navigation bar below.

Enjoyed? Ok! Let's continue. Download and save locally a APK-file which you want to install/evaluate on the emulator. We recommend to save the APK file directly in the $SDK_ROOT/tools directory.

Note: APK probably stands for "Android package". It's an application distribution unit in the Android environment. If you are coming from the Windows Mobile world, think of APK as of CAB-files.

Ok, now start the console ("Start -> Run... -> type 'cmd'" for Windows computers). Type-in the following command: adb install $APK where $APK is the name of the APK file. For example: adb install Snake.apk

If you receive a "path not found" error, then you probably either didn't add path to the $SDK_ROOT/tools directory to your system PATH settings or the application you are trying to install is not in the $SDK_ROOT/tools or $SDK_ROOT/platform-tools directory.

If all went without errors then you should be seeing your newly installed APK on the emulator.

Sponser