Search This Blog

Showing posts with label Android Basic. Show all posts
Showing posts with label Android Basic. Show all posts

Saturday, 1 June 2013

Android action bar style generator

Action bar becomes popular after it launched in android 3.1 version. Using action with Fragment avoid overhead of maintaining stack of activity. But customizing action bar style is pain. We should thank to Jeff Gilfelt  for his great work. He provide tool of customizing action in unique style.
Just customize action bar style like editing a photo in Photo Editor and it will provide you complete resource with layout, style and draw-able (which include hdpi, ldpi and xhdpi images)

You can use Sherlock Action bar also if you have backward compatibility issue. You can customize its look and feel.

It provide you complete control on customization on android action bar style. you can change action bar Tab bottom line and all other thing related to it

Here Go for Action Bar Style Customization URL

Saturday, 4 May 2013

How to make Android service unstoppable and run it continuously

Android service runs in different mode with help of flag e.g START_CONTINUATION_MASK, START_NOT_STICKY. It enable to control the behavior of Android service life. But service will work until user allow it work. If he/she stops it, it will destroy automatically. More than often, we required it to run unstoppable  If in case user stop, re-instance the old service instance.
For some people, it may malware but sometimes we have to full filled client requirement and that's all our purpose is.

Case when your service can be stopped



  • User stop it forcefully
  • Low Memory situation
  • Device restarted


Handling first two case


When ever we stop service forcefully (or os kill it), it will call onDestory() method. First concept is to use one receiver and send one broadcast whenever service destroy. And restarted service again.

Third case if device is restarted then already we had onBootCompleted action for receiver to catch

Lets go steps by Step to make our Android Service unstoppable

Step 1) Create one Android BroadCastReciever and register it for two action


Manifest

        <service android:name="ServiceTest" >
        </service>

        <receiver android:name="ReceiverCall" >
            <intent-filter>
                <action android:name="com.android.techtrainner" />
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

com.android.techtrainner is the custom action. BroadCastReceiver Class contain code to restart service again

public class ReceiverCall extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i("Service Stops", "Ohhhhhhh");
        context.startService(new Intent(context, ServiceTest.class));;
    }

}


Step 2) Create Android service class , do some task there (I have taken one Timer to print Log) and in onDestory()


    public void onDestroy() {
        try {
            mTimer.cancel();
            timerTask.cancel();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Intent intent = new Intent("com.android.techtrainner");
        intent.putExtra("yourvalue", "torestore");
        sendBroadcast(intent);
    }

Run your application and go to setting, See running service, you will TestService. Try to close it , ohhhhhh it will not close.

DownloadSource Application



Sunday, 3 March 2013

Video Chat API in android provide Group Video Chat, Peer to peer and Mobile to Web

Video chat in android is the hot topic in every mobile either Android or iPhone. While making application based on social networking, including Video chat option can raise your application standard. Even though android does not provide directly anything related to video chat, but there are lots of work around for this.
Challenge while implement Video chat are

  • Video Quality on internet 
  • Video Delay while streaming
  • And implementing between cross platform
So looking for API considering all possibilities is quite difficult before OpenTok comes in to scene.
Before implementing into your project see the pricing which is very crucial to your project nature and scale


OpenTok Pricing

I have been touch with them since last one month, They have launch the early beta version of android version and working hard to launch it completely in April 2013

Current Support for android device

Nexus 4, Nexus 7 and S3

Full Version is expected to launch in next month

How to start implementing 




Tuesday, 9 October 2012

Viewpager Example in android

Viewpager  is  the best way to switching among view. It provide a way to swipe views from left to right and right to left. Viewpager provide strong way to swipe any views but here i have taken ImageView to swipe left and right.

Viewpager is strong widget as well as very simple. So here we go step wise solution  with explanation.

Add the support library while you are creating project because Viewpager does not support in lower android version 


Step 1) After creating a fresh project. change your main.xml to as follow so that it have one Viewpager widget in it.


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <android.support.v4.view.ViewPager
        android:id="@+id/myfivepanelpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>


Step 2) Now our main concern is to bind data inside a Viewpager so that you can easily swipe. PagerAdapter bind the data to Viewpager and create view dynamically when needed. In PagerAdapter we remove the view as soon as its use is over so that we can avoid memory wastage . So create one new class and paste below code inside it.


package com.horizontalscrollviewwithpageindicator;

import android.app.Activity;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;

public class ViewPagerAdapter extends PagerAdapter {

 Activity activity;
 int imageArray[];

 public ViewPagerAdapter(Activity act, int[] imgArra) {
  imageArray = imgArra;
  activity = act;
 }

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

 public Object instantiateItem(View collection, int position) {
  ImageView view = new ImageView(activity);
  view.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
    LayoutParams.FILL_PARENT));
  view.setScaleType(ScaleType.FIT_XY);
  view.setBackgroundResource(imageArray[position]);
  ((ViewPager) collection).addView(view, 0);
  return view;
 }

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

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

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

Step 3) This is the final step and Viewpager complete. As in PagerAdapter , i have created one ImageView to display as child of Viewpager so we need one image array to show image. I have image in my drawable folder. I created one array like this


private int imageArra[] = { R.drawable.antartica1, R.drawable.antartica2,
   R.drawable.antartica3, R.drawable.antartica4,
   R.drawable.antartica5, R.drawable.antartica6,
   R.drawable.antartica7, R.drawable.antartica8 };

Now we just need to attach our PagerAdapter to android Viewpager . So we will change our main activity code to as following ---


package com.horizontalscrollviewwithpageindicator;

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

public class PageIndicatorActivity extends Activity {

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

 private int imageArra[] = { R.drawable.antartica1, R.drawable.antartica2,
   R.drawable.antartica3, R.drawable.antartica4,
   R.drawable.antartica5, R.drawable.antartica6,
   R.drawable.antartica7, R.drawable.antartica8 };

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

}

See the video to get perfect idea about what's the outcome will be. And if you are not able to follow the above procedure than no need to worry. Just download the source code and play with it


                                                         
                                                       

Download Source Code

Wednesday, 1 August 2012

Android sliding drawer example

Consider a case of complex UI where you do not have space on your android application screen but you have to show some extra data on same screen?
There are two way in such a condition --

1) Switching view using LayoutInflater or fragments - but its very costly if as it will need space from visible portion

2) Using menu and action bar - unfortunately we can only show button there to perform action.

Then what should we so ? android provide Sliding drawer for such a requirement. It does not take main screen space. and it open when ever a user want to open. Most importantly , you can show any complex user interface inside a sliding drawer.

Creating sliding drawer is simple. It just need two component--

  •  A button, will visible all the time to open and close sliding drawer. but we do not need to set listener for this.
  • And Layout that will show when you open sliding drawer. I have taken a ListView inside sliding drawer
Sliding Drawer Closed
                             


Sliding drawer
Sliding Drawer Opened

Sliding Drawer
Action On Sliding Drawer Element
                                               

Now you just need to download the sample application and start playing with it. 

Sliding Drawer Source Code


I have browse about sliding drawer and i found a very useful link to create sliding drawer from Left to right or Right to left See Going into depth of Custom Sliding drawer


Thursday, 5 July 2012

Android Expandable ListView simple Example in android.

Android Expandable ListView simple Example in android. We are aware about android most powerful feature ListView. We can handle ListView click event e.g clicking on ListView row, we can start a new activity or what ever we want to do. But it some how strange to many developer, clicking on ListView row it should expand and show more details in spite of opening a new Activity and we can shrink row of ListView after reading details information. This is feature known as ExpandableListView in android. ExpandableListView is pre-define widget in android . and much similar to android ListView.
So here we go for ExpandableListView Simple Example with source code at the end of this article.
ExpandableListView include some steps to create one simple sample Create one fresh project and Extends ExpandableListActivity inspite of Activity public class MainActivity extends ExpandableListActivity

ExpandableListView include two kind of data one for Group Item and One for child of corresponding Group item so lets have a look how prepare data for ExpandableListView 

public void setGroupData() {
  groupItem.add("TechNology");
  groupItem.add("Mobile");
  groupItem.add("Manufacturer");
  groupItem.add("Extras");
         }

     ArrayList<String> groupItem = new ArrayList<String>();
     ArrayList<Object> childItem = new ArrayList<Object>();

     public void setChildGroupData() {
  /**
   * Add Data For TecthNology
   */
  ArrayList<String> child = new ArrayList<String>();
  child.add("Java");
  child.add("Drupal");
  child.add(".Net Framework");
  child.add("PHP");
  childItem.add(child);

  /**
   * Add Data For Mobile
   */
  child = new ArrayList<String>();
  child.add("Android");
  child.add("Window Mobile");
  child.add("iPHone");
  child.add("Blackberry");
  childItem.add(child);
  /**
   * Add Data For Manufacture
   */
  child = new ArrayList<String>();
  child.add("HTC");
  child.add("Apple");
  child.add("Samsung");
  child.add("Nokia");
  childItem.add(child);
  /**
   * Add Data For Extras
   */
  child = new ArrayList<String>();
  child.add("Contact Us");
  child.add("About Us");
  child.add("Location");
  child.add("Root Cause");
  childItem.add(child);
     }

Now Data is ready to showing inside ExpandableListView. Now just like a simple list view we need one adapter to bind data to ExpandableListView. But this time we will use BaseExpandableListAdapter in place of BaseAdapter as it provide a way to create child of a Group when we expand it Finally we need two Layout one to showing Group Row and One two showing Child Row inside ExpandableListView Main Hurdle How to perform Click on child of ExpandableListView? ExpandableListView provide OnChildClickListener but for unknown reason, I am not able to perform child click event using this.
So i created one another way.while creating Child View we will perform click Listener over there in getChildView method of Adapter So now times to introduce with Code step by Step

Step 1) Change your Main Activity code to as following 



package com.multilayerexpandable;

import java.util.ArrayList;

import android.app.ExpandableListActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.Toast;

public class MainActivity extends ExpandableListActivity implements
  OnChildClickListener {

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  ExpandableListView expandbleLis = getExpandableListView();
  expandbleLis.setDividerHeight(2);
  expandbleLis.setGroupIndicator(null);
  expandbleLis.setClickable(true);

  setGroupData();
  setChildGroupData();

  NewAdapter mNewAdapter = new NewAdapter(groupItem, childItem);
  mNewAdapter
    .setInflater(
      (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE),
      this);
  getExpandableListView().setAdapter(mNewAdapter);
  expandbleLis.setOnChildClickListener(this);
 }

 public void setGroupData() {
  groupItem.add("TechNology");
  groupItem.add("Mobile");
  groupItem.add("Manufacturer");
  groupItem.add("Extras");
 }

 ArrayList<String> groupItem = new ArrayList<String>();
 ArrayList<Object> childItem = new ArrayList<Object>();

 public void setChildGroupData() {
  /**
   * Add Data For TecthNology
   */
  ArrayList<String> child = new ArrayList<String>();
  child.add("Java");
  child.add("Drupal");
  child.add(".Net Framework");
  child.add("PHP");
  childItem.add(child);

  /**
   * Add Data For Mobile
   */
  child = new ArrayList<String>();
  child.add("Android");
  child.add("Window Mobile");
  child.add("iPHone");
  child.add("Blackberry");
  childItem.add(child);
  /**
   * Add Data For Manufacture
   */
  child = new ArrayList<String>();
  child.add("HTC");
  child.add("Apple");
  child.add("Samsung");
  child.add("Nokia");
  childItem.add(child);
  /**
   * Add Data For Extras
   */
  child = new ArrayList<String>();
  child.add("Contact Us");
  child.add("About Us");
  child.add("Location");
  child.add("Root Cause");
  childItem.add(child);
 }

 @Override
 public boolean onChildClick(ExpandableListView parent, View v,
   int groupPosition, int childPosition, long id) {
  Toast.makeText(MainActivity.this, "Clicked On Child",
    Toast.LENGTH_SHORT).show();
  return true;
 }
}

 

Step2) Create two XML Layout one for Group row and one for Childe Row of ExpandableListView Group Row XML Layout 

 

<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/textView1" 
android:layout_width="wrap_content" android:layout_height="60dp" android:layout_marginLeft="5dp" android:drawableRight="@drawable/plusminus" android:gravity="center_vertical" android:text="@string/hello_world" android:textColor="#FFFFFF" android:padding="10dp" android:textSelectHandleLeft="@string/hello_world" 
android:textSize="14sp"
 android:textStyle="bold" /> 

Child Row XML Layout 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="40dp"
    android:background="@android:color/black"
    android:clickable="true"
    android:orientation="vertical"
    android:paddingLeft="40dp"
    tools:context=".MainActivity" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="39dp"
        android:gravity="center_vertical" >

        <ImageView
            android:id="@+id/childImage"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:layout_margin="5dp"
            android:background="@drawable/ic_launcher"
            android:contentDescription="@string/hello_world" />

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
            android:text="@string/hello_world"
            android:textColor="#FFFFFF"
            android:textSize="14sp"
            android:textStyle="bold" />
    </LinearLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@android:color/white" />

</LinearLayout>

 

Step 3) Finally Create one New class for binding data inside ExpandableListView 

 


package com.multilayerexpandable;

import java.util.ArrayList;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.CheckedTextView;
import android.widget.TextView;
import android.widget.Toast;

@SuppressWarnings("unchecked")
public class NewAdapter extends BaseExpandableListAdapter {

 public ArrayList<String> groupItem, tempChild;
 public ArrayList<Object> Childtem = new ArrayList<Object>();
 public LayoutInflater minflater;
 public Activity activity;

 public NewAdapter(ArrayList<String> grList, ArrayList<Object> childItem) {
  groupItem = grList;
  this.Childtem = childItem;
 }

 public void setInflater(LayoutInflater mInflater, Activity act) {
  this.minflater = mInflater;
  activity = act;
 }

 @Override
 public Object getChild(int groupPosition, int childPosition) {
  return null;
 }

 @Override
 public long getChildId(int groupPosition, int childPosition) {
  return 0;
 }

 @Override
 public View getChildView(int groupPosition, final int childPosition,
   boolean isLastChild, View convertView, ViewGroup parent) {
  tempChild = (ArrayList<String>) Childtem.get(groupPosition);
  TextView text = null;
  if (convertView == null) {
   convertView = minflater.inflate(R.layout.childrow, null);
  }
  text = (TextView) convertView.findViewById(R.id.textView1);
  text.setText(tempChild.get(childPosition));
  convertView.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {
    Toast.makeText(activity, tempChild.get(childPosition),
      Toast.LENGTH_SHORT).show();
   }
  });
  return convertView;
 }

 @Override
 public int getChildrenCount(int groupPosition) {
  return ((ArrayList<String>) Childtem.get(groupPosition)).size();
 }

 @Override
 public Object getGroup(int groupPosition) {
  return null;
 }

 @Override
 public int getGroupCount() {
  return groupItem.size();
 }

 @Override
 public void onGroupCollapsed(int groupPosition) {
  super.onGroupCollapsed(groupPosition);
 }

 @Override
 public void onGroupExpanded(int groupPosition) {
  super.onGroupExpanded(groupPosition);
 }

 @Override
 public long getGroupId(int groupPosition) {
  return 0;
 }

 @Override
 public View getGroupView(int groupPosition, boolean isExpanded,
   View convertView, ViewGroup parent) {
  if (convertView == null) {
   convertView = minflater.inflate(R.layout.grouprow, null);
  }
  ((CheckedTextView) convertView).setText(groupItem.get(groupPosition));
  ((CheckedTextView) convertView).setChecked(isExpanded);
  return convertView;
 }

 @Override
 public boolean hasStableIds() {
  return false;
 }

 @Override
 public boolean isChildSelectable(int groupPosition, int childPosition) {
  return false;
 }

}


So Screen Shot of Complete Guide will be like




Download Source Code

Saturday, 12 May 2012

Bitmap operations like re sizing, rotating bitmap and other operations

In programming, Image processing is the most difficult work. All though i am not going to discuss image processing in depth but we will discuss about bitmap basic operation like re sizing, rotating bitmap, how to create bitmap from file , input stream and resource.we will discuss it step by step and finally you will get source in which you can enjoy playing with it. img is the ImageView object in my project.
As we are going to discuss bitmap to we need to study how to avoid Memory Over Flow while using big image

Friday, 11 May 2012

Android Database SQLite tutorial : Insert, update, delete, deleting data base and table

All though we know mobile do not have large memory to save data in comparison of Desktop and Laptop
but data base is highly important in android (and other mobile OS also).
In android we use SQlite database. Sq-lite is light wight and design according to support mobile device limited memory.
First i am listing some basic operation and will explain every thing with example
1) Creating data base - In android, we have an API classes to create it that is  SQLiteOpenHelper to create data base. Best way is to create a different class and extends SQLiteOpenHelper

package com.gu;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DataBaseHub extends SQLiteOpenHelper {

    private static final String dbname = "demo.db";
    private static final int version = 2;
    public static String Ename="Ename";
    public static String Eid="Eid";
    public static String Eadd="Eadd";
    public static String Emp="Emp";
    
    public DataBaseHub(Context context) {
        super(context, dbname, null, version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String employee1 = "create table "+Emp+"("+Eid+" integer primary key,"+Ename+" tex                            t,"+Eadd+" text)";
        db.execSQL(employee1);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        if (oldVersion < newVersion) {
            String employee1 = "create table emp("+Eid+" integer,"+Ename+" text,"+Eadd+" t            ext)";
            db.execSQL(employee1);
        }
    }
}

2)Creating a data base Table

String employee1 = "create table "+Emp+"("+Eid+" integer primary key,"+Ename+" text,"+Eadd+" text)";
db.execSQL(employee1);

2)Open Data Base - when we open data base in two way either we want to open data base only for reading or for writing into data base. If we open data base in writing mode then we will get access to reading automatically.

  DataBaseHub dbh=new DataBaseHub(activitycontext);                                       
SqliteDatabase db= dbhgetWritableDatabase();                                                    SqliteDatabase db= dbh.getReadableDatabase();

3) Inserting Values into data base - Now we have created data base and open it for performing operation on it so basic operation is to insert value into data base. I have taken table so i will insert values into this table

DataBaseHub dbh=new DataBaseHub(this);
SQLiteDatabase db=dbh.getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put(DataBaseHub.Eid,101);
cv.put(DataBaseHub.Ename,"Tofeeq");
cv.put(DataBaseHub.Eadd,"142,Ananad Delhi");
long i=db.insert(DataBaseHub.Emp, null, cv);
Log.i("Row ID=",String.valueOf(i));

4) Deleting particular row from data base -  Deleting  particular row in data base is damn simple. We have to specify column name( to identify which row we want to delete)
DataBaseHub dbh=new DataBaseHub(this);
SQLiteDatabase db=dbh.getWritableDatabase();
i=db.delete(DataBaseHub.Emp, DataBaseHub.Eid+"=?",new String[]{"101"});
Log.i("Number of Row=",String.valueOf(i)););

5)Updating a row into data base - Updating row into data base is little bit complicated so i will explain there in code

DataBaseHub dbh=new DataBaseHub(this);
SQLiteDatabase db=dbh.getWritableDatabase();
// Create content values that contains the name of the column you want to update and the value you want to assign to it 
ContentValues cv = new ContentValues();
cv.put("my_column", "5");
String where = DataBaseHub.Eid+"=?"; // The where clause to identify which columns to update.
String[] value = { "2" }; // The value for the where clause.
// Update the database (all columns in TABLE_NAME where my_column has a value of 2 will be changed to 5)
db.update(DataBaseHub.Emp, cv, where, value);

6) Reading record from data base - you can read all record by querying a table it will store table records into Cursor. Use cursor method's cusor.movetoNext() cursor.movetToprevious()

DataBaseHub dbh=new DataBaseHub(this);
SQLiteDatabase db = dbh.getReadableDatabase();
Cursor cursor = db.query("Table_name",null,null,null,null,
           null, null, null, null, null);
    if (cursor != null)
    cursor.moveToFirst();
//Now you can read record from cursor easily

7) Deleting Table from data base - Deleting table in android data base is very important. E.g if you are making Music Player. Then you need to create dynamic table while you creating play list

DataBaseHub dbh=new DataBaseHub(this);
SQLiteDatabase db=dbh.getWritableDatabase();
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);

8) Deleting complete data base - all though we do not need this operation generally but in case if you need to delete your data base you can delete easily by using activity context.


context.deleteDatabase(DATABASE_NAME);

Sunday, 29 April 2012

Service example in android

Service is one of core component of android application. Every one knows service is very important part. we use it but sometimes we do not know exact power and depth of service, today i am going to discuss it in details.
After this article we will also let you know difference between Thread and Service, and how to perform real time task in service


In the end you will also get source code.

Service -A Service is an application component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use.

Difference between a Thread , service and asynchronous task

1)  Service is like an Activity but has no interface. Probably if you want to fetch the weather for example you won't create a blank activity for it, for this you will use a Service.

2)  A Thread is a Thread, probably you already know it from other part. You need to know that you cannot update UI from a Thread. You need to use a Handler for this, but read further.

3)  An AsyncTask is an intelligent Thread that is advised to be used. Intelligent as it can help with it's methods, and there are two methods that run on UI thread, which is good to update UI components

Other one difference between service and thread is that thread is not intelligent enough to recognize that is it already running or not? Every time you create a new object of thread and start again it will create a new instance and a new thread start running.
But if service is already running and you start again it will not created again.So that is very important difference

Saturday, 28 April 2012

Utility Function Call, Email, Send SMS in android Using Intent

Generally while we making an android application then sometimes we need small piece of code like how to call a number on button click, how to send an email, how to send a sms. But problem is that it does not available at one place. So i am giving all possible Utility code here

1) How to call a number in android application

 Intent callIntent = new Intent(Intent.ACTION_CALL);  
 callIntent.setData(Uri.parse("tel:123456789"));  
 startActivity(callIntent);  


2) How to send an email in android application

 Intent(android.content.Intent.ACTION_SENDTO);
emailIntent.setType("text/html");
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "testing email send.");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, Html.fromHtml("<b>this is html text in email body.</b>"));
startActivity(Intent.createChooser(emailIntent, "Email to Friend")); 

How to pick an Email from contact in android

Picking email, Phone number, and other detail from android in built contact is very easy if you use ACTION_PICK.Action Pick activity syntax will be like


Intent intent1=new Intent(Intent.ACTION_PICK,ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent1,100);


Note : it need permission .so do not forget to mention it in manifest

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

It will start a default activity that will list all contact. On item select that activity will finish automatically and it will return result in OnActivityResult. default activity return complete Intent with all available information with particular select contact.

Monday, 16 April 2012

Creating HorizontalScrollView in Android

Today i am going to describing a powerful tool of android, Horizontal Listview with complete source in the end.
Horizontal ListView sometimes is very useful and it save our day. HorizontalScrollView is nothing but a widget, If you add more element than its visible area then it start scrolling horizontally. Bit main disadvantage is that you can not perform click on the base of position quite easily

If you need some explanation then read complete step else download code with link in the end and play with it

Step 1) Create one new Project name HorizontalListviewDemo

Step 2) Change your main activity to as follow class

 package com.ahmad;  
 import android.app.Activity;  
 import android.os.Bundle;  
 import android.view.View;  
 import android.view.View.OnClickListener;  
 import android.widget.Button;  
 import android.widget.LinearLayout;  
 import android.widget.Toast;  
 public class SecondActivity extends Activity implements OnClickListener {  
  Button btn1, btn2, btn3, btn4;  
  public LinearLayout middle;  
  @Override  
  public void onCreate(Bundle savedInstanceState) {  
  super.onCreate(savedInstanceState);  
     setContentView(R.layout.main);  
  btn1 = (Button) findViewById(R.id.btn1);  
  btn1.setOnClickListener(this);  
  btn2 = (Button) findViewById(R.id.btn2);  
  btn2.setOnClickListener(this);  
  btn3 = (Button) findViewById(R.id.btn3);  
  btn3.setOnClickListener(this);  
  try {  
   btn4 = (Button) findViewById(R.id.btn4);  
   btn4.setOnClickListener(this);  
  } catch (Exception e) {  
   e.getMessage();  
  }  
  }  
  @Override  
  public void onClick(View v) {  
  if (v.getId() == R.id.btn1) {  
   Toast.makeText(this, "Second Act Btn1 Clicked", Toast.LENGTH_LONG)  
    .show();  
  } else if (v.getId() == R.id.btn2) {  
   Toast.makeText(this, "Second Act Btn 2 Clicked", Toast.LENGTH_LONG)  
    .show();  
  } else if (v.getId() == R.id.btn3) {  
   Toast.makeText(this, "Second Act Btn 3 Clicked", Toast.LENGTH_LONG)  
    .show();  
  } else if (v.getId() == R.id.btn4) {  
   Toast.makeText(this, "Second Act Btn 4 Clicked", Toast.LENGTH_LONG)  
    .show();  
  }  
  }  
 }  
Step 3)Make one Layout and add HorizontalListview and some content inside

  
Now enjoy after running it.complete source link is below.See more article on ListView in blog tag Android ListView
                                                          Download Complete Project


Article You may Like

Android Listactivity with header

Sunday, 15 April 2012

Asynchronous task, Updating UI from background in android

As all we know in android there are two ways to perform background task such as downloading image and other task that include long operation
  • Using Thread 
  • Asynchronous Task                          
Using Thread, there is one dis-advantage that we can not update user interface other wise we will get Looper.loop() exception

So its efficient to use Asynchronous task.
An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called ParamsProgress and Result, and 4 steps, called onPreExecutedoInBackgroundonProgressUpdate and onPostExecute.

Saturday, 14 April 2012

Zipping File and Folder in android

While we are attaching any folder/file to mail or other attachment so we really need to attach folder with more than one sub folder. So we need to compress it so called zipping . It necessary in Mobile OS as in Windows. So for this android provide ZipOutPutStream and ZipEntry. ZipOutPutStream read complete folder and then ZipEntry zip all the file inside folder to a new compress folder. Zipping File is very easy.If you want dynamically select which file/folder to zipped then see this

import android.util.Log; 
import java.io.BufferedInputStream; 
import java.io.BufferedOutputStream; 
import java.io.FileInputStream; 
import java.io.FileOutputStream; 
import java.util.zip.ZipEntry; 
import java.util.zip.ZipOutputStream; 
 
 
public class Compress { 
  private static final int BUFFER = 2048; 
 
  private String[] _files; 
  private String _zipFile; 
 
  public Compress(String[] files, String zipFile) { 
    _files = files; 
    _zipFile = zipFile; 
  } 
 
  public void zip() { 
    try  { 
      BufferedInputStream origin = null; 
      FileOutputStream dest = new FileOutputStream(_zipFile); 
 
      ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest)); 
 
      byte data[] = new byte[BUFFER]; 
 
      for(int i=0; i < _files.length; i++) { 
        Log.v("Compress", "Adding: " + _files[i]); 
        FileInputStream fi = new FileInputStream(_files[i]); 
        origin = new BufferedInputStream(fi, BUFFER); 
        ZipEntry entry = new ZipEntry(_files[i].substring(_files[i].lastIndexOf("/") + 1)); 
        out.putNextEntry(entry); 
        int count; 
        while ((count = origin.read(data, 0, BUFFER)) != -1) { 
          out.write(data, 0, count); 
        } 
        origin.close(); 
      } 
 
      out.close(); 
    } catch(Exception e) { 
      e.printStackTrace(); 
    } 
 
  } 
} 

In constructor we have two string parameter.first pass array of file inside a folder .Then file path to which zipped folder will save if it is not present then this code will create new zip folder.

Friday, 13 April 2012

Android File explorer example i.e pick image, video, Audio from android sdcards

In android we know sdcard is main drive to store information. Sometimes we need to read/write file from sdcard. In this case we can give static path and easily can read/write using FileInputStream and FileOutputStream. But in most case we need to select it  dynamically on user demand.After selecting it we can modify it, we can share or we can send it to anywhere

So today I am going to make a simple application like File-explorer. It will help in my next Article Ziping and Unziping Folder in android.


Step1) Create one project File-Explorer 


Step 2) Change your activity to following code

package com.AndroidExplorer;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class AndroidExplorer extends ListActivity {
 private List<String> item = null;
 private List<String> path = null;
 private String root = "/sdcard";
 private TextView myPath;

 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.explorer);
  myPath = (TextView) findViewById(R.id.path);
  getDir(root);
 }
 private void getDir(String dirPath) {
  myPath.setText("Location: " + dirPath);
  item = new ArrayList<String>();
  path = new ArrayList<String>();
  File f = new File(dirPath);
  File[] files = f.listFiles();
  if (!dirPath.equals(root)) {
   item.add(root);
   path.add(root);
   item.add("../");
   path.add(f.getParent());
  }
  for (int i = 0; i < files.length; i++) {
   File file = files[i];
   path.add(file.getPath());
   if (file.isDirectory())
    item.add(file.getName() + "/");
   else
    item.add(file.getName());
  }
  ArrayAdapter<String> fileList = new ArrayAdapter<String>(this,
    R.layout.explorer_row, item);
  setListAdapter(fileList);
         }
       File file;
       @Override
 protected void onListItemClick(ListView l, View v, int position, long id) {
 file = new File(path.get(position));
  if (file.isDirectory()) {
    if (file.canRead())
    getDir(path.get(position));
   else {
    new AlertDialog.Builder(this)
    .setIcon(R.drawable.icon)
    .setTitle("[" + file.getName()+ "] folder can't be read!")
    .setPositiveButton("OK",new DialogInterface.OnClickListener() {
       @Override public void onClick(DialogInterface dialog,int which) {
     }}).show();
   }
  } else {
      new AlertDialog.Builder(this)
     .setIcon(R.drawable.icon)
     .setTitle("Select")
     setMessage("Select " + file.getName() + "to server ?")
    .setPositiveButton("Select",new DialogInterface.OnClickListener() {
         @Override public void onClick(DialogInterface dialog,int which) {
  Toast.makeText(
                     AndroidExplorer.this,"" + file.getAbsolutePath()+ " iss selected ",300)
           .show();
     }
 })
 .setNegativeButton("No",new DialogInterface.OnClickListener() {
  @Override
          public void onClick(DialogInterface dialog,int which) {
         dialog.dismiss();
      }
   }).show();
  }
     }
      } 


Step 3)Now our coding part has been done.

We will create two xml. As i have take one List-Activtiy   so it need two layout one main.xml and another one to inflating into ListView row.Click me for advance ListView

  • explorer.xml inside res/layout folder
<?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:id="@+id/path"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    />
<ListView
 android:id="@android:id/list"
 android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:cacheColorHint="#B26B00"
    android:fadingEdge="none"
 />
<TextView
 android:id="@android:id/empty"
 android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="No Data"
 />
</LinearLayout>
  • explorer_row in same folder
<?xml version="1.0" encoding="utf-8"?>
<TextView 
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/rowtext" android:padding="10dp"
  android:background="#C0C0C0" android:textColor="#000"
  android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:textSize="23sp" />

Now enjoy you can download this complete project from this link.

                                      Download this Project


These are the screen shot of that project




Android News and source code