Many times we want to display our toast in custom manner, We can modify a Toast by setting its display position and assigning it alternative views or layouts.
Friday, 23 September 2011
Thursday, 22 September 2011
Smooth List View
Listview is very common in android, and easy to make. But main issue is how can we make it smooth and maintain it's performance. when data may be collection of images and text. Now here is a quite good technique to represent our data in list view.
for example we have to display :
public class DataValues{
private String imgURL, text;
public void setData(String imgURL, String text){
this.imgURL = imgURL;
this.text = text;
}
public String getImgURL()
{
return imgURL;
}
public String getText()
{
return text;
}
}
Now, let's create xml layout. row_data_image.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<ImageView android:id="@+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/icon"/>
<TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
Now we will create AsyncImageLoader; This functionality can be done "AsyncTask" but here we are going to use thread and handler.
Note: in the given code we are using "SoftReference" for caching images.
public class AsyncImageLoader {
private HashMap<String, SoftReference<Drawable>> imgCache;
public AsyncImageLoader() {
imgCache = new HashMap<String, SoftReference<Drawable>>();
}
public Drawable loadDrawable(final String imgURL, final ImageCallback imageCallback) {
if (drawableMap.containsKey(imgURL)) {
SoftReference<Drawable> softReference = imgCache.get(imgURL);
Drawable drawable = softReference.get();
if (drawable != null) {
return drawable;
}
}
final Handler handler = new Handler() {
@Override
public void handleMessage(Message message) {
imageCallback.imageLoaded((Drawable) message.obj, imgURL);
}
};
new Thread() {
@Override
public void run() {
Drawable drawableImg = loadImageFromUrl(imgURL);
imgCache.put(imgURL, new SoftReference<Drawable>(drawableImg ));
Message message = handler.obtainMessage(0, drawableImg );
handler.sendMessage(message);
}
}.start();
return null;
}
// Download image from internet
public static Drawable loadImageFromUrl(String url) {
InputStream inputStream;
try {
inputStream = new URL(url).openStream();
} catch (IOException e) {
throw new RuntimeException(e);
}
return Drawable.createFromStream(inputStream, "src");
}
public interface ImageCallback {
public void imageLoaded(Drawable imageDrawable, String imgURL);
}
Create ViewWrap class for get ids of views:
public class ViewWrap{
private View mainView;
private TextView textView;
private ImageView imgView;
public ViewCache(View mainView) {
this.mainView = mainView;
}
public TextView getTextView() {
if (textView == null) {
textView = (TextView) mainView.findViewById(R.id.text);
}
return titleView;
}
public ImageView getImageView() {
if (imgView == null) {
imgView = (ImageView) mainView.findViewById(R.id.image);
}
return imgView;
}
for example we have to display :
Here we need to display images and text . And data should be downloaded from internet. Now we will create a getter and setter class for image and text. The name should be: DataValues
public class DataValues{
private String imgURL, text;
public void setData(String imgURL, String text){
this.imgURL = imgURL;
this.text = text;
}
public String getImgURL()
{
return imgURL;
}
public String getText()
{
return text;
}
}
Now, let's create xml layout. row_data_image.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<ImageView android:id="@+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/icon"/>
<TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
Now we will create AsyncImageLoader; This functionality can be done "AsyncTask" but here we are going to use thread and handler.
Note: in the given code we are using "SoftReference" for caching images.
public class AsyncImageLoader {
private HashMap<String, SoftReference<Drawable>> imgCache;
public AsyncImageLoader() {
imgCache = new HashMap<String, SoftReference<Drawable>>();
}
public Drawable loadDrawable(final String imgURL, final ImageCallback imageCallback) {
if (drawableMap.containsKey(imgURL)) {
SoftReference<Drawable> softReference = imgCache.get(imgURL);
Drawable drawable = softReference.get();
if (drawable != null) {
return drawable;
}
}
final Handler handler = new Handler() {
@Override
public void handleMessage(Message message) {
imageCallback.imageLoaded((Drawable) message.obj, imgURL);
}
};
new Thread() {
@Override
public void run() {
Drawable drawableImg = loadImageFromUrl(imgURL);
imgCache.put(imgURL, new SoftReference<Drawable>(drawableImg ));
Message message = handler.obtainMessage(0, drawableImg );
handler.sendMessage(message);
}
}.start();
return null;
}
// Download image from internet
public static Drawable loadImageFromUrl(String url) {
InputStream inputStream;
try {
inputStream = new URL(url).openStream();
} catch (IOException e) {
throw new RuntimeException(e);
}
return Drawable.createFromStream(inputStream, "src");
}
public interface ImageCallback {
public void imageLoaded(Drawable imageDrawable, String imgURL);
}
Create ViewWrap class for get ids of views:
public class ViewWrap{
private View mainView;
private TextView textView;
private ImageView imgView;
public ViewCache(View mainView) {
this.mainView = mainView;
}
public TextView getTextView() {
if (textView == null) {
textView = (TextView) mainView.findViewById(R.id.text);
}
return titleView;
}
public ImageView getImageView() {
if (imgView == null) {
imgView = (ImageView) mainView.findViewById(R.id.image);
}
return imgView;
}
Wednesday, 21 September 2011
Android Device Information
Android provides some classes and methods by which we can get the information of android devices. some examaples are given bellow.
Get sim serial number:
TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String getSimSerialNumber=tm.getSimSerialNumber();
Get Device ID :
TelephonyManager tManager = (TelephonyManager)myActivity.getSystemService(Context.TELEPHONY_SERVICE);
String uid = tManager.getDeviceId();
Get Ram size :
MemoryInfo mi = new MemoryInfo();
ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
activityManager.getMemoryInfo(mi);
long availableMegs = mi.availMem / 1048576L;
Get Manufacture info:
String m = Build.MANUFACTURER;
Get Networkoperator & SIM operator name:
String m = Build.MANUFACTURER;
TelephonyManager telephonyManager =((TelephonyManager) Context.getSystemService(Context.TELEPHONY_SERVICE));
//<------------ Network Operator-----------------
String operatorName = telephonyManager.getNetworkOperatorName();
//<------------SIM Operator------------
String operatorName = telephonyManager.getSimOperatorName();
Get Network Type :
if(telephonyManager.getNetworkType() == TelephonyManager.NETWORK_TYPE_UMTS)
Log.v(TAG, "3G");
if(telephonyManager.getNetworkType() == TelephonyManager.NETWORK_TYPE_EDGE )
Log.v(TAG, "GSM");
if(telephonyManager.getNetworkType() == TelephonyManager.TelephonyManager.NETWORK_TYPE_CDMA)
Log.v(TAG, "CDMA");
Get sim serial number:
TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String getSimSerialNumber=tm.getSimSerialNumber();
Get Device ID :
TelephonyManager tManager = (TelephonyManager)myActivity.getSystemService(Context.TELEPHONY_SERVICE);
String uid = tManager.getDeviceId();
Get Ram size :
MemoryInfo mi = new MemoryInfo();
ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
activityManager.getMemoryInfo(mi);
long availableMegs = mi.availMem / 1048576L;
Get Manufacture info:
String m = Build.MANUFACTURER;
Get Networkoperator & SIM operator name:
String m = Build.MANUFACTURER;
TelephonyManager telephonyManager =((TelephonyManager) Context.getSystemService(Context.TELEPHONY_SERVICE));
//<------------ Network Operator-----------------
String operatorName = telephonyManager.getNetworkOperatorName();
//<------------SIM Operator------------
String operatorName = telephonyManager.getSimOperatorName();
Sim number:
mPhoneNumber =
telephonyManager.getLine1Number();
Get Network Type :
if(telephonyManager.getNetworkType() == TelephonyManager.NETWORK_TYPE_UMTS)
Log.v(TAG, "3G");
if(telephonyManager.getNetworkType() == TelephonyManager.NETWORK_TYPE_EDGE )
Log.v(TAG, "GSM");
if(telephonyManager.getNetworkType() == TelephonyManager.TelephonyManager.NETWORK_TYPE_CDMA)
Log.v(TAG, "CDMA");
Tuesday, 20 September 2011
Android database Basic
In android we create our database through SQLiteOpenHelper class. this class takes care of opening the database if it exists, creating it if it does not, and upgrading it as necessary. Transactions are used to make sure the database is always in a sensible state, with the help of it's methods, we can easly tackcare of our database.
Best practice is that we have to create our application modulewise. So we will create our database class in
{
private static final String DATABASE_NAME = "my_database";
private static final String DATABASE_TABLE = "records";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE =
"create table titles (_id integer primary key autoincrement, "
+ "name text not null, address text not null, "
+ "city text not null);";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
public class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(DATABASE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion)
{
Log.w(TAG, "Upgrading database from version " + oldVersion
+ " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS titles");
onCreate(db);
}
}
//---opens the database---
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database---
public void close()
{
DBHelper.close();
}
//---insert a values into the database---
public long insertTitle(String name, String add, String city)
{
ContentValues initialValues = new ContentValues();
initialValues.put("name", name);
initialValues.put("address", add);
initialValues.put("city", city);
return db.insert(DATABASE_TABLE, null, initialValues);
}
//--- update the record------
public boolean updateName(int id, String name)
{
ContentValues args = new ContentValues();
args.put("name", name);
return db.update(DATABASE_TABLE, args,
"_id"+ "=" + id, null) > 0;
}
//---deletes a particular title---
public boolean deleteName(long rowId)
{
return db.delete(DATABASE_TABLE, "_id"+
"=" + rowId, null) > 0;
}
}
You can also copy your database from sdcard and asset folder through code
Code copy database from SD
public void sdCardDatabase() {
private String databasePath = Environment.getExternalStorageDirectory().getAbsoluteFile()+ "/database.db";
try {
File f1 = new File("path of your database");
if (f1.exists()) {
File f2 = new File(databasePath);
f2.createNewFile();
InputStream in = new FileInputStream(f1);
OutputStream out = new FileOutputStream(f2);
byte[] bufer = new byte[1024];
int len;
while ((len = in.read(bufer)) > 0) {
out.write(bufer, 0, len);
}
in.close();
out.close();
}
} catch (FileNotFoundException e) {
Log.e(TAG, e.getMessage());
} catch (IOException e) {
}
}
Best practice is that we have to create our application modulewise. So we will create our database class in
separate manner. The name of our class is "DatabaseHelper".
Lets start:
package com.android.appdemo.database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBAdapter import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
{
private static final String DATABASE_NAME = "my_database";
private static final String DATABASE_TABLE = "records";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE =
"create table titles (_id integer primary key autoincrement, "
+ "name text not null, address text not null, "
+ "city text not null);";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
public class DatabaseHelper extends SQLiteOpenHelper {
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(DATABASE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion)
{
Log.w(TAG, "Upgrading database from version " + oldVersion
+ " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS titles");
onCreate(db);
}
}
//---opens the database---
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database---
public void close()
{
DBHelper.close();
}
//---insert a values into the database---
public long insertTitle(String name, String add, String city)
{
ContentValues initialValues = new ContentValues();
initialValues.put("name", name);
initialValues.put("address", add);
initialValues.put("city", city);
return db.insert(DATABASE_TABLE, null, initialValues);
}
//--- update the record------
public boolean updateName(int id, String name)
{
ContentValues args = new ContentValues();
args.put("name", name);
return db.update(DATABASE_TABLE, args,
"_id"+ "=" + id, null) > 0;
}
//---deletes a particular title---
public boolean deleteName(long rowId)
{
return db.delete(DATABASE_TABLE, "_id"+
"=" + rowId, null) > 0;
}
}
You can also copy your database from sdcard and asset folder through code
Code copy database from SD
public void sdCardDatabase() {
private String databasePath = Environment.getExternalStorageDirectory().getAbsoluteFile()+ "/database.db";
try {
File f1 = new File("path of your database");
if (f1.exists()) {
File f2 = new File(databasePath);
f2.createNewFile();
InputStream in = new FileInputStream(f1);
OutputStream out = new FileOutputStream(f2);
byte[] bufer = new byte[1024];
int len;
while ((len = in.read(bufer)) > 0) {
out.write(bufer, 0, len);
}
in.close();
out.close();
}
} catch (FileNotFoundException e) {
Log.e(TAG, e.getMessage());
} catch (IOException e) {
}
}
Monday, 19 September 2011
Layout design for different - 2 screen resolution
In Android this is the main thing to maintain the layout according to screen resolution. But thid can be done now easly. Android 3.2 has introduced new APIs that allow you to more precisely control the layout resources your application uses for different screen sizes.
example:
res/layout/my_layout.xml // layout for normal screen size ("default")
res/layout-small/my_layout.xml // layout for small screen size
res/layout-large/my_layout.xml // layout for large screen size
res/layout-xlarge/my_layout.xml // layout for extra large screen size
res/layout-xlarge-land/my_layout.xml // layout for extra large in landscape orientation
Same thing will be happend with your images :
res/drawable-mdpi/my_icon.png // bitmap for medium density
res/drawable-hdpi/my_icon.png // bitmap for high density
res/drawable-xhdpi/my_icon.png // bitmap for extra high density
Here is a quick checklist about how you can ensure that your application displays properly on different screens:
- Android groups all actual screen sizes into four generalized sizes: small, normal, large, and extra large.
- Android groups all actual screen densities into four generalized densities: low, medium, high, and extra high.
- A virtual pixel unit that you should use when defining UI layout, to express layout dimensions or position in a density-independent way.
example:
res/layout/my_layout.xml // layout for normal screen size ("default")
res/layout-small/my_layout.xml // layout for small screen size
res/layout-large/my_layout.xml // layout for large screen size
res/layout-xlarge/my_layout.xml // layout for extra large screen size
res/layout-xlarge-land/my_layout.xml // layout for extra large in landscape orientation
Same thing will be happend with your images :
res/drawable-mdpi/my_icon.png // bitmap for medium density
res/drawable-hdpi/my_icon.png // bitmap for high density
res/drawable-xhdpi/my_icon.png // bitmap for extra high density
Here is a quick checklist about how you can ensure that your application displays properly on different screens:
- Use
wrap_content
,fill_parent
, ordp
units when specifying dimensions in an XML layout file - Do not use hard coded pixel values in your application code
- Do not use
AbsoluteLayout
(it's deprecated) - Supply alternative bitmap drawables for different screen densities
Sending Email
We can send email in android with the help of Android Intent with user interface and also without promt to user.
First we will see how can we send email with mail interface:
final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent .setType("plain/text");
emailIntent .putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{"abc@pqr.com"});
emailIntent .putExtra(android.content.Intent.EXTRA_SUBJECT, mySubject);
emailIntent .putExtra(android.content.Intent.EXTRA_TEXT, myBodyText);
emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:/"+ FileName)); // Attachment
context.startActivity(Intent.createChooser(emailIntent, "Send mail...));
Second way:
We can also send mail to user without providing the mail interface;
This can be done by JavaMail API implemented for Andorid . We can also send html content, attachment.
Hope the given demo code will help you :)
Mail sendMail = new Mail("My_User_ID", "PASSWORD"); // Replace user id and password
//according to your credential
String[] toArray = {"1st mail id", "2nd mail id"};
sendMail.setTo(toArray);
sendMail.setFrom("USER EMAIL");
sendMail.setSubject("This is an email sent using Mail JavaMail wrapper from an Android device.");
sendMail.setBody("Email body contents");
try {
sendMail.addAttachment("/sdcard/imagefolder/myImage.png"); // Image path for attachment
if(sendMail.send()) {
Toast.makeText(this, "Email was sent successfully.", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Email was not sent.", Toast.LENGTH_SHORT).show();
}
} catch(Exception e) {
Log.e(TAG, "Could not send email", e);
}
First we will see how can we send email with mail interface:
final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent .setType("plain/text");
emailIntent .putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{"abc@pqr.com"});
emailIntent .putExtra(android.content.Intent.EXTRA_SUBJECT, mySubject);
emailIntent .putExtra(android.content.Intent.EXTRA_TEXT, myBodyText);
emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:/"+ FileName)); // Attachment
context.startActivity(Intent.createChooser(emailIntent, "Send mail...));
Second way:
We can also send mail to user without providing the mail interface;
This can be done by JavaMail API implemented for Andorid . We can also send html content, attachment.
Hope the given demo code will help you :)
Mail sendMail = new Mail("My_User_ID", "PASSWORD"); // Replace user id and password
//according to your credential
String[] toArray = {"1st mail id", "2nd mail id"};
sendMail.setTo(toArray);
sendMail.setFrom("USER EMAIL");
sendMail.setSubject("This is an email sent using Mail JavaMail wrapper from an Android device.");
sendMail.setBody("Email body contents");
try {
sendMail.addAttachment("/sdcard/imagefolder/myImage.png"); // Image path for attachment
if(sendMail.send()) {
Toast.makeText(this, "Email was sent successfully.", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Email was not sent.", Toast.LENGTH_SHORT).show();
}
} catch(Exception e) {
Log.e(TAG, "Could not send email", e);
}
Subscribe to:
Posts (Atom)