Tuesday, 31 July 2012

Custom List View

CustomList.java



import java.util.List;
import java.util.Vector;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class CustomList extends Activity
{
private LayoutInflater mInflater;
private Vector<RowData> data;
ListView list;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    list=(ListView)findViewById(R.id.list);
    mInflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
    data = new Vector<RowData>();
    RowData rd = new RowData("android ice cream sandwich", "Version 4.0    ");
    data.add(rd);
    rd = new RowData("android jelly bean", "Version 4.1    ");
    data.add(rd);
    final Builder builder = new AlertDialog.Builder(this);
    //Settings adapter to fill the RowData
    CustomAdapter adapter = new CustomAdapter(this, R.layout.custom_row,R.id.call, data);
    list.setAdapter(adapter);  
    //ListItem click
    list.setOnItemClickListener(new AdapterView.OnItemClickListener()
    {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3)
        {
            CustomAdapter adapter = (CustomAdapter) arg0.getAdapter();
                RowData row = adapter.getItem(arg2);   
            builder.setTitle(row.mItem);
            builder.setMessage(row.mDescription + " -> " + arg2 );
            builder.setPositiveButton("ok", null);
            builder.show();       
        }//onItemClick
    });
   
}//onCreate



/**
 * Data type used for custom adapter. Single item of the adapter.     
 */
private class RowData
{
    protected String mItem;
    protected String mDescription;

        RowData(String item, String description)
        {
        mItem = item;
        mDescription = description;            
        }

        @Override
        public String toString()
        {
                return mItem + " " +  mDescription;
        }
}//RowData

private class CustomAdapter extends ArrayAdapter<RowData>
{

        public CustomAdapter(Context context, int resource,int textViewResourceId, List<RowData> objects)
        {
                super(context, resource, textViewResourceId, objects);
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent)
        {
                ViewHolder holder = null;
                //widgets displayed by each item in your list
                TextView item = null;
                TextView description = null;
                ImageView image=null;
                //data from your adapter
                RowData rowData= getItem(position);
               //we want to reuse already constructed row views...
                if(null == convertView)
                {
                        convertView = mInflater.inflate(R.layout.custom_row, null);
                        holder = new ViewHolder(convertView);
                        convertView.setTag(holder);
                }               
                holder = (ViewHolder) convertView.getTag();
               
                item = holder.getItem();
                item.setText(rowData.mItem);

                description = holder.getDescription();         
                description.setText(rowData.mDescription);
               
                image=holder.getImage();
                image.setOnClickListener(new View.OnClickListener() {
                   
                    @Override
                    public void onClick(View v) {
               
                        Toast.makeText(getBaseContext(), "Click on the image", Toast.LENGTH_SHORT).show();
                       
                    }
                });

                return convertView;
        }//getView
}//CustomAdapter

/**
 * Wrapper for row data.
 *
 */
    private class ViewHolder
    {     
        private View mRow;
        private TextView description = null;
        private TextView item = null;
        ImageView image=null;

            public ViewHolder(View row)
                {
                mRow = row;
                }

            public TextView getDescription()
                {
                    if(null == description)
                        {
                            description = (TextView) mRow.findViewById(R.id.call);
                        }
                    return description;
                }
            public TextView getItem()
                {
                    if(null == item)
                        {
                        item = (TextView) mRow.findViewById(R.id.callnumber);
                        }
                    return item;
                }         
            public ImageView getImage()
            {
                if(null == image)
                {
                image = (ImageView) mRow.findViewById(R.id.starimage);
                }
                return image;
            }      
}//Activity
}




main.xml



<?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:background="@android:color/white">
    <ListView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/list"/>
</LinearLayout>



custom_row.xml




<?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">   
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
   
  <TextView android:id="@+id/call" android:text="call"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
         />
  <TextView android:id="@+id/date_time" android:layout_below="@+id/call" android:text="Web ,Jul 31 1:40 PM"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
    <TextView android:id="@+id/callnumber"  android:layout_toRightOf="@+id/call"
        android:layout_width="wrap_content" android:text="callnumber"
        android:layout_height="wrap_content"
        />
    <ImageView android:id="@+id/starimage" android:src="@drawable/star" android:layout_marginTop="5dip" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_alignParentRight="true"/>
    </RelativeLayout>
   
</LinearLayout>



start image




Screen:


Tuesday, 3 January 2012

Running Background Service in android

This is example how to running the Service in the Background.

ServicesActivity.java


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class ServicesActivity extends Activity implements OnClickListener {
  private static final String TAG = "ServicesActivity";
  Button buttonStart, buttonStop;

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

    buttonStart = (Button) findViewById(R.id.start);
    buttonStop = (Button) findViewById(R.id.stop);

    buttonStart.setOnClickListener(this);
    buttonStop.setOnClickListener(this);
  }

  public void onClick(View src) {
    switch (src.getId()) {
    case R.id.buttonStart:
       startService(new Intent(this, service.class));
      break;
    case R.id.buttonStop:
      stopService(new Intent(this, service.class));
      break;
    }
  }
}


service.java



import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class service extends Service {
    private static final String TAG = "service";
    MediaPlayer player;
   
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
   
    @Override
    public void onCreate() {
           
        player = MediaPlayer.create(this, R.raw.sound);
        player.setLooping(false);
    }

    @Override
    public void onDestroy() {
       
        player.stop();
    }
   
    @Override
    public void onStart(Intent intent, int start) {
       
        player.start();
    }
}

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"
    android:gravity="center">
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" android:text="Service"/>
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" 
android:id="@+id/start" android:text="Start"></Button>
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" 
android:id="@+id/stop" android:text="Stop"></Button>
</LinearLayout>




AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.name" android:versionCode="1" android:versionName="1.0">
  <application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity android:name=".ServicesActivity" android:label="@string/app_name">
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
    </activity>
    <service android:enabled="true" android:name=".service" />
  </application>
</manifest>

Different type of layout example


main.xml  in the layout
this layout is for the Normal Screen

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

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >
       <TextView
            android:id="@+id/textview"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Subject" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="   :   " />
        <EditText
            android:id="@+id/Edittext"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/linearLayout2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:background="@android:color/darker_gray" >
         
            <TableLayout
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"> 
          
                    <TableRow android:layout_margin="5dip" android:gravity="center">
      
                    <Button
                         android:id="@+id/button2"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="submit" />
                    <TextView
                        android:text="           "
                            android:gravity="center"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"/>
                    <Button
                        android:id="@+id/button3"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="cancel" />
      
                </TableRow>
            </TableLayout>           

       </LinearLayout>
    <LinearLayout android:id="@+id/linearLayout4"
        android:layout_width="fill_parent"
         android:layout_height="300dip"
        android:layout_below="@+id/linearLayout3"
        android:layout_marginTop="60dp">
  
        <ListView
            android:id="@+id/ListView01"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"/>
    </LinearLayout>
  
</RelativeLayout>



This main.xml is not properly work in the small Screen Resolution.

Small Screen

For that make new folder in the res/layout-small
make main.xml

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

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >
       <TextView
            android:id="@+id/textview"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Subject" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="   :   " />
        <EditText
            android:id="@+id/Edittext"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/linearLayout2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:background="@android:color/darker_gray" >
         
            <TableLayout
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"> 
          
                    <TableRow android:layout_margin="5dip" android:gravity="center">
      
                    <Button
                         android:id="@+id/button2"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="submit" />
                    <TextView
                        android:text="           "
                            android:gravity="center"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"/>
                    <Button
                        android:id="@+id/button3"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="cancel" />
      
                </TableRow>
            </TableLayout>           

       </LinearLayout>
    <LinearLayout android:id="@+id/linearLayout4"
        android:layout_width="fill_parent"
         android:layout_height="250dip"
        android:layout_below="@+id/linearLayout3"
        android:layout_marginTop="60dp">
  
        <ListView
            android:id="@+id/ListView01"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"/>
    </LinearLayout>
  
</RelativeLayout>






we have Activity Layout

LayoutActivity.java

import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class LayoutActivity extends Activity {
    private ListView lv;
    private String arr[]={"Android","iPhone","BlackBerry",};
    @Override
    public void onCreate(Bundle icicle)
    {
    super.onCreate(icicle);
    setContentView(R.layout.main);
    lv=(ListView)findViewById(R.id.ListView01);
   
    lv.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , arr));
    }
}

How to install android plugin

First you’ll need to download the Android SDK source files:
( http://code.google.com/android/download.html )

Currently the following operating systems are supported:
  • Windows XP or Vista
  • Mac OS X 10.4.8 or later (x86 only)
  • Linux (tested on Linux Ubuntu Dapper Drake)
You will also need to install a suitable development environment such as:

 

Installing The Android SDK

 

First you will need to download the Android SDK pack .zip archive, once downloaded find a suitable installation location on your machine and extract the zipped files.
Please note: This installation location will be referred to as $SDK_ROOT from now on through this tutorial
Alternatively you can add /tools to your root path which will prevent the need to specify the full path to the tools directory along with enabling you to run Android Debug Bridge (adb) along with other command line tools.
To add /tools:

 

Linux

  1. Edit the ~/.bash_profile or ~/.bashrc files looking for a line that sets the PATH variable.
  2. Add the full path location to your $SDK_ROOT/tools location for the PATH variable.
  3. If no PATH line exists you can add the line by typing the following:
  4. export PATH=${PATH}:<path to your $SDK_ROOT/tools>

 

Mac OS X

  1. In the home directory locate the .bash_profile and locating the PATH variable add the location to your $SDK_ROOT/tools folder.

 

Windows XP / Vista

  1. Right click on the My Computer icon and select the properties tab.
  2. Select the Advanced tab and click the Environment Variables button.
  3. In the new dialog box dowble-click on Path (located under System Variables) and type in the full path location to the tools directory.
The Android SDK also requires a suitable development environment to work in, here’s the installation guides for each of the supported environments.

 

Android Eclipse Plugin (ADT)

 

If you choose to use the Eclipse IDE as your Android development environment you will have the opportunity to install and run a plug-in called Android Development Tools. ADT comes with a variety of powerful tools and extensions that will make creating, running and debugging your Android applications much easier and faster.
In order to download and install ADT you will first need to configure an Eclipse remote update, this can achieved via the following steps:
  1. Start Eclipse, then select Help > Software Updates > Find and Install….
  2. In the dialog that appears, select Search for new features to install and press Next.
  3. Press New Remote Site.
  4. In the resulting dialog box, enter a name for the remote site (e.g. Android Plugin) and enter this as its URL: https://dl-ssl.google.com/android/eclipse/.
  5. Press OK.
  6. You should now see the new site added to the search list (and checked).
  7. Press Finish.
  8. In the subsequent Search Results dialog box, select the checkbox for Android Plugin > Eclipse Integration > Android Development Tools and press Next.
  9. Read the license agreement and then select Accept terms of the license agreement, if appropriate.
  10. Press Next.
  11. Press Finish.
  12. The ADT plugin is not signed; you can accept the installation anyway by pressing Install All.
  13. Restart Eclipse.
  14. After restart, update your Eclipse preferences to point to the SDK root directory ($SDK_ROOT):
    Select Window > Preferences… to open the Preferences panel. (Mac OS X: Eclipse > Preferences)
    Select Android from the left panel.
    For the SDK Location in the main panel, press Browse... and find the SDK root directory.
  15. Press Apply, then OK. 

     

     

    Updating the ADT Plugin

     

    To update the ADT plugin to the latest version, follow these steps:
    1. Select Help > Software Updates > Find and Install….
    2. Select Search for updates of the currently installed features and press Finish.
    3. If any update for ADT is available, select and install.
    Alternatively:
    1. Select Help > Software Updates > Manage Configuration.
    2. Navigate down the tree and select Android Development Tools <version>
    3. Select Scan for Updates under Available Tasks.

    Wednesday, 23 November 2011

    ListView Multiple Choice

    main.xml



    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout android:id="@+id/Layout1"
    android:layout_width="fill_parent" android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <ListView android:id="@+id/ListView1" android:layout_height="wrap_content"
    android:layout_width="fill_parent"></ListView>
    </LinearLayout>


    ListViewMultipleChoice.java


     public class ListViewMultipleChoice extends Activity {
    private ListView list;
    private String lv_items[] = { "Android", "iPhone", "BlackBerry"};

    @Override
    public void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    setContentView(R.layout.main);

    list = (ListView) findViewById(R.id.ListView1);

    list.setAdapter(new ArrayAdapter<String>(this,
    android.R.layout.simple_list_item_multiple_choice, lv_items));
    list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
    }
    }







    Tuesday, 22 November 2011

    Progress Dialog


    import android.app.Activity;
    import android.app.ProgressDialog;
    import android.content.pm.ActivityInfo;
    import android.os.Bundle;

    public class ProgressDialogActivity extends Activity {
        /** Called when the activity is first created. */
        ProgressDialog pro;
        @Override
        public void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER);
            setContentView(R.layout.main);
             pro=new ProgressDialog(this);
             pro.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
             pro.setMax(300);
             pro.setCancelable(true);
             pro.setMessage("Loading data..");
             pro.show();
             Threadex t=new Threadex();
             t.start(); //start thread
       // t.stomth();
        }//This is Oncreate method
        class Threadex extends Thread
        {
            public void stomth()
            {
                pro.dismiss();
            }
            public void run()
            {
                for(int i=10;i<=pro.getMax();i=i+10)
                {
                    pro.incrementProgressBy(10);
                    try
                    {
                    sleep(1000); //sleep for 1 seconds
                    }
                    catch(Exception e)
                    {
                    e.printStackTrace();
                    }
               
                } //this is for loop ends
               
                pro.dismiss();
               
               
            } //this is end of Run
        }//This is End of Threadex
    } //This is End of Activity

    Here Update the 10 distance continues Upto 300 distance because we have set 300 distance as max .



    This is after the Dismiss the ProgressDialog




    This is for ProgressDialog.STYLE_HORIZONTAL.
    we can set Another Style ProgressDialog.STYLE_SPINNER but view is different

    Monday, 14 November 2011

    Getting SMS in your Activity

    import android.app.Activity;
    import android.database.Cursor;
    import android.net.Uri;
    import android.os.Bundle;
    import android.widget.TextView;

    public class SMSActivity extends Activity
    {
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    TextView textview = new TextView(this);
    Uri url = Uri.parse("content://sms/inbox");
    Cursor cursor = getContentResolver().query(url, null, null, null,null);
    String smsdisplay = "";
    while (cursor.moveToNext()) {
    smsdisplay += "From :" + cursor.getString(2) + " : " + cursor.getString(11)+"\n";
    }
    textview.setText(smsdisplay);
    setContentView(textview);
    }
    }

    in the AndroidManifest.xml

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

    Gives this Permission for Reading SMS in your activity.