android

Insert and modify Contact in Android

Android 2.0 provides new Contact API, which is defined in  android.provider.ContactsContract.  After some try on contact api I found a better and easy solution for insertion and modification of contact.

Insert contact -

Intent addContactIntent = new Intent(Intent.ACTION_INSERT, ContactsContract.Contacts.CONTENT_URI);

addContactIntent.putExtra(ContactsContract.Intents.Insert.NAME,

"xyz");

addContactIntent.putExtra(ContactsContract.Intents.Insert.EMAIL,

"abc@gmail.com");

addContactIntent.putExtra(ContactsContract.Intents.Insert.PHONE,"012345678");

startActivity(addContactIntent);

ACTION_INSERT will start .EditContact activity.

Edit contacts -
  • If _ID of contact is known -

Intent intent = new Intent(Intent.ACTION_EDIT);

intent.setData(ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, _ID));

startActivity(intent);

  • If _ID of contact is not known -
i) Find out conatct _ID by phone number .
// CONTENT_FILTER_URI allow to search contact by phone number

Uri lookupUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(getPhone()));

// This query will return NAME and ID of conatct, associated with phone //number.

Cursor mcursor = getContentResolver().query(lookupUri,new String[] { PhoneLookup.DISPLAY_NAME, PhoneLookup._ID                    },null, null, null);

//Now retrive _ID from query result

long idPhone = 0;

try {
if (mcursor != null) {
if (mcursor.moveToFirst()) {
idPhone = Long.valueOf(mcursor.getString(mcursor .getColumnIndex(PhoneLookup._ID)));
Log.d("", "Contact id::" + idPhone);
}
}
} finally {
mcursor.close();
}

ii) Then Edit contact

if (idPhone > 0) {

Intent intent = new Intent(Intent.ACTION_EDIT);
intent.setData(ContentUris.withAppendedId( ContactsContract.Contacts.CONTENT_URI, idPhone));
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), "contact not in list",
Toast.LENGTH_SHORT).show();
}

You can also search _ID by partial name, for this instead of PhoneLookup.CONTENT_FILTER_URI use ContactsContract.Contacts.CONTENT_FILTER_URI
To work with contact, you have to define special permission in AndroidManifest.xml .

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

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


Historical timeline charts related to computer/electronics

Android

iPhone

Apple

Mac

Bill Gates

Linux

Windows CE

Various Mobile OS

Excel

Photoshop

Intel

Sony

Nokia

Social Media

Search Engines

Programming Languages

W3C(Internet)

Game Technology

NFS Car Racing Game

CellPhone

Electronics

Universe(Space)

Software

Hardware


Innovative Test Cases and Expected Results for Accelerometer, Compass And GPS

In current mobile technology, we use accelerometer, compass and GPS in latest mobile models. Here some innovative test cases and expected results of those components, when we test in some places like in the space, on any other planet, satellite, center of gravity of earth and center of magnetic field of earth. Those cases are discussed as following:

1. In space: In space, accelerometer, compass and GPS will not work. because accelerometer and compass have required gravity and magnetic field respectively. But when we use accelerometer and compass nearer any planet, then we get relative values as that planet’s field with some accuracy. and GPS will not work, if we are close to any other planet excluding earth. Because for GPS usage, we require human invented working satellites.

2. On any other planet (excluding earth): Still GPS will not work in any other planet. and we get relative values of accelerometer and compass as that planet.

3. On center of gravity of earth: We cannot predict results for accelerometer and GPS. It is possible that we get garbage values for accelerometer. and compass will work proper because location of center of gravity and location of center of magnetic field of earth are different.

4. On center of magnetic field of earth: In this case, we get garbage values for compass and get proper values for accelerometer and GPS. But still It is possible that if there is any relationship between gravity and magnetic field, then we get unknown results for accelerometer.

For all those cases, I expect results based on physics theories, but still we cannot guess exact results. Those all will work on so many parameters, planet atmosphere and other theories.

-Samir Solanki


Nine Patch Images useful for android

Android devices come in different screen sizes and density, often making it very difficult for developer to design an application for all screen sizes. Use of nine patch images can be very helpful for them. Mostly nine patch images are used as background for Buttons, Texts, Frames. Android provide a tool for creating nine patch images. It is available in android-sdk/tools directory named as draw9patch.
What is nine patch?
Nine patch images are simply PNG images with 9 patches as explained in figure -
1,3,7,9 – Not scalable area
2 – Horizontal scalable area
4 – Vertical scale area
6,8 – Text Area
For scaling purpose you have to give guideline for both area(2,4). Otherwise converted nine patch image will not be proper nine patch.
ex -
So basically the intersection of horizontal and vertical guideline’s pixels will replicate. Guidelines for text area is optional.
Nine patch images can not be scale down, so use of mdpi images are baseline for dp scaling(Ignoring ldpi). Here is a link to learn how to draw nine patch images- http://developer.android.com/guide/developing/tools/draw9patch.html

Batch Insert to SQLite database on Android

Database operations are slow and in a situation where thousands of records have to be inserted, inserting each record consumes a lot of time and affects the performance of the application. In such situations,batch insert saves some overhead. A significant amount of time can be saved if batch inserts are made in a single transaction.

SQLite provides three simple methods in SQLiteDatabase class :
beginTransaction();
setTransactionSuccessful();
endTransaction();

These methods can be used to make all the insert calls in the same batch in a single transaction. Transactions are used when there is a need to perform a series of queries that either all complete or all fail. When a SQLite transaction fails an exception will be thrown. Start a transaction by calling the beginTransaction() method. Perform the database operations and then call the setTransactionSuccessful() to commit the transaction. Once the transaction is complete call the endTransaction() function.

A sample example code is shown below:

// Begin the transaction
db.beginTransaction();
try{
for each record in the list{
ContentValues contentValues=new ContentValues();
contentValues.put(COLUMN_NAME,record);
db.insert(TABLE_NAME,null,contentValues);

}
// Transaction is successful and all the records have been inserted
db.setTransactionSuccessful();
}catch(Exception e){
Log.e(“Error in transaction”,e.toString());
}finally{
//End the transaction
db.endTransaction();
}


How to change foreground & background colors in a webview.

At times we need to change the font or background color of the webview in Android to make it more readable or to conform to a design of your app. This post will show how simple it can be to almost always achieve the result. The latter is more simple as webview provides an API :

setBackgroundColor (int color)

What one must note is if the HTML contains a value for the background it will override the color we set. The same is true for the foreground color too.

For the foreground color we make use of CSS to set the color and add it to the content we want to display in a div element wrapping the html we need to display. Here is the sample code

private final String htmlbegin = "<div style=\"color:#FFFFFF ;  \">";
private final String htmlend = " </div>";
private final String htmlBody = "<p>Summary</p>"
	+ "<p>Strong text</strong> Somemore text"
	+ "and the final line</p>";
WebView body;

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

	body = (WebView) findViewById(R.id.message_body);
	body.setBackgroundColor(0);

	// body.setDef
	body.loadDataWithBaseURL("", htmlbegin + htmlBody + htmlend,
		"text/html", "utf-8", "");
}

As I stated before any css inside the html will override our css settings.


Retrieving Current Network Status in Android

Here is a quick snippet of code which will help us in getting the current status of an Android device’s data connection.  We make use of the ConnectivityManager class to get current active network information. We try to catch a NullPointerException which is thrown by the isConnected method when there is no active data connection.

/**
 * Returns availability of a data connection
 * @param mContext
 *            Context of app
 * @return True is data connection is available , false otherwise
 */
public static boolean isDataConnectionOn(Context mContext) {
	ConnectivityManager connectionManager = (ConnectivityManager) mContext
			.getSystemService(Context.CONNECTIVITY_SERVICE);
	try {
		if (connectionManager.getActiveNetworkInfo().isConnected()) {
			Log.d("ConStatus", "Data Connection On");
			return true;
		} else {
			Log.d("ConStatus", "Data Connection off");
			return false;
		}
	} catch (NullPointerException e) {
		// No Active Connection
		Log.d("ConStatus", "No Active Connection");
		return false;
	}
}

Steps For Publishing Application On Android Market

    Make your application non debuggable
  • Remove the android:debuggable="true" attribute from the <application> element of the manifest.
  • Remove log files, backup files, and other unnecessary files from the application project.
  • Check for private or proprietary data and remove it as necessary.
    Deactivate any calls to Log methods in the source code.
  • Is in your possession
  • Represents the personal, corporate, or organizational entity to be identified with the application
  • Has a validity period that exceeds the expected lifespan of the application or application suite. A validity period of more than 25 years is recommended.
  • If you plan to publish your application(s) on Android Market, note that a validity period ending after 22 October 2033 is a requirement. You can not upload an application if it is signed with a key whose validity expires before that date.
  • Is not the debug key generated by the Android SDK tools.
    Steps for creating the private key

  • Set the following paths for the environmental varialbles JAVA_HOME: C:\Program Files\Java\jdk1.6.0_20 PATH: C:\Program Files\Java\jdk1.6.0_20\bin

    (this value changes depending on where we have stored the jdk)

  • Right click on the project and do the following Androidtools>export signed application>next>select create new keystore>next>next>finish.
  • Open command prompt and type the following.Set the path to where the keystore is stored C:\Documents and Settings\bindu\Desktop>keytool -list -alias [aliasname] -keystore [keystorename]
  • We now have obtained the fingerprint
  • Now open the following link and enter the obtained finger print http://code.google.com/android/maps-api-signup.html
  • Now we have the private key in your google account.
    Register for a Maps API Key,if your application is using Map View element
    If your application uses one or more Mapview elements, you will need to register your application with the Google Maps service and obtain a Maps API Key, before your MapView(s) will be able to retrieve data from Google Maps. To do so, you supply an MD5 fingerprint of your signer certificate to the Maps service.

    Obfuscating the codeWe can use tools like ant and progaurd to obfuscate the code. Detailed steps for this is given in blog. http://android-developers.blogspot.com/

    Licensing the application After we finish all the above steps refer the following link to publish the application in the android market. http://developer.android.com/guide/publishing/licensing.html



Creating a Customized PopOver for MapView

The android developers tutorial guides to create an app that shows a map the user can use to zoom and add overlay items that mark points of interest. Suppose the user wants to display the location of the overlay items that were added,as a callout bubble, a customized layout has to be created and added as a subview of the mapView.

Creating a layout:
Create a new xml file in Layout folder,say popOver.xml.

<FrameLayout xmlns:android=”http://schemas.android.com/apk/res/android”

android:id=”@+id/mapBubbleWrap”

android:layout_width=”wrap_content”

android:layout_height=”wrap_content” >

<LinearLayout android:orientation=”horizontal” android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/bubble_container”>

<FrameLayout android:layout_width=”wrap_content” android:layout_height=”wrap_content”>

<ImageView android:layout_width=”wrap_content” android:layout_height=”wrap_content”

android:id=”@+id/dialogimage” android:src=”@drawable/popup_leftpointer”/>

<ImageView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:paddingLeft=”10dip” android:paddingTop=”7dip”

android:id=”@+id/dialogimage1″/>

</FrameLayout>

<FrameLayout android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:background=”@drawable/popup_middlebg”>

<TextView android:id=”@+id/mapBubble”

android:layout_width=”wrap_content”

android:layout_height=”wrap_content”

android:gravity=”center” android:paddingTop=”7dip”/>

</FrameLayout>

<ImageView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/dialogimage2″

android:src=”@drawable/popup_right” />

</LinearLayout>

</FrameLayout>

The above xml code just contains the image of the popover that is to be displayed onTap of the overlay item. I have 3 images joined together to form a single popover image. One can use a single image and add a text displaying the location inside it. However, 2 images and a text is being displayed in popover so 3 images are being used.

Figure(A)

Figure(B)

Figure(C)

I have used the figure(B) to display the text(location), the left pointer points the top of the item marker.

Figure(D)

Figure(D) shows how the popover will look once we add the above view in the mapview.

Adding the customized view in the MapView

Then,in the MapOverLay class that extends ItemizedOverlay,in the overridden OnTap method, inflate the popOver.xml layout.i.e. protected boolean onTap(int index)

First, we have to get the location of the overlay item. This is done by the getProjection method of the MapView class.

Point point = map.getProjection().toPixels(item.getPoint(), null);

- getProjection() gets a projection for converting between screen-pixel coordinates and latitude/longitude coordinates.

- item is the overlay item (Overlay item = (Overlay) getItem(index);)

Now,we know where we have to place the customized view on the screen. But the point we have got will place the popover on the marker. We need to place it on top of the marker. To get the marker image’s height and width ,use getIntrinsicHeight and getIntrincsicWidth.
height=marker.getIntrinsicHeight();
width=marker.getIntrinsicWidth();

The customized view now has to be moved a few pixels above that corresponds to the marker height and displaced a few pixels in the x-direction that is half the marker’s width.

Set the LayoutParams of the layout that is being inflated.

LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, point.x – width/2, point.y
- height, 0);
layout.setLayoutParams(params);

Now,add the view to the mapView.

mapView.addView(layout);

The x and y parameters being set in the LayoutParams depends on the kind of image being used as the popover. The image that I have used has a pointer that has to be displayed in the middle of the marker and it won’t be set in the middle of the marker if I use the above logic of setting the x and y parameters of the LayoutParams to half the width of the marker and the full height of the marker. If I do so,the left corner of the image will be displayed on the marker as shown. So use it according to the image being used.


Bangalore Android Developers having fun with Arduino and Amarino

Here are some of the pictures from Bangalore Android Developers / User group’s dev event.

Theme: Have fun with Arduino and Amarino toolkit
Location: TechJini Solutions
Participants: Sudar (Our kit sponsor), Amrita, Krishna, Sandeep (our guide 2), Anil (our guide 1) and Amit

For next event please sign up at http://www.meetup.com/blrdroid/


  • TechJini Solutions

  • © Copyright 2009 TechJini Solutions Private Limited. All Rights Reserved
    iDream theme by Templates Next | Powered by WordPress