Wednesday 6 July 2011

Simple ListView with ListActivity in Android


Android and Lists

Here is the tutorial for how to make ListView using ListView Activity in android.
Let's Discuss About what we can achieve using ListView Activity in android.
      You can directly use the "ListView" in your layout as any other UI component. In case your Activity is primary showing a list you can extend the activity "ListActivity" which simplifies the handling of a "ListView". "ListActivity" extends "Activity" and provides simplified handling of lists. For example you have a predefine method if someone clicks on a list element.

"ListActivity" contains a "ListAdapter" which is responsible for managing the data. This adapter must be set in the onCreate() method of your Activity via the method setListAdapter().
If the user select in the list a list entry the method onListItemClick() will be called. This method allows to access the selected element.
Android provides already some default layouts which you can use in your Adapter, e.g. "android.R.layout.simple_list_item1". In case you don't want to use one of the pre-defined layouts your own layout must have an element with the id "@android:id/list" which is the ListView. You can also use a view with the id "@android:id/empty". This view is displayed if the list is empty. For example you could display here an error message.

ListViews and performance:
Showing a big dataset must be with efficiency implemented on a mobile device. Therefore the ListView solitary creates views (widget) if needed and attach them to the view hierarchy. The default Adapter implementation for a ListView will recycle views, e.g. if a row is not displayed anymore it will be recycled and only its content will change. If you implement your own adapter for a view you also should do this to avoid performance problems.

Let's Begin
For the simple ListView we don't require to put <ListView/> in activity so here is the code for main Activity.


public class SimpleListActivityActivity extends ListActivity {

/** Called when the activity is first created. */
/** When we are using ListActivity we don't need to find the ListView in xml by Id*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);
this.setListAdapter(new ArrayAdapter<String>(SimpleListActivityActivity.this, android.R.layout.simple_list_item_1, COUNTRIES));
}
String[] COUNTRIES = new String[] {
"Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra",
"Angola", "Anguilla", "Antarctica", "Antigua and Barbuda", "Argentina",
"Armenia", "Aruba", "Australia", "Austria", "Azerbaijan",
"Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium",
"Belize", "Benin", "Bermuda", "Bhutan", "Bolivia",
"Bosnia and Herzegovina", "Botswana", "Bouvet Island", "Brazil", "British Indian Ocean Territory",
"British Virgin Islands", "Brunei", "Bulgaria", "Burkina Faso", "Burundi",
"Cote d'Ivoire", "Cambodia", "Cameroon", "Canada", "Cape Verde",
"Cayman Islands", "Central African Republic", "Chad", "Chile", "China",
"Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo",
"Cook Islands", "Costa Rica", "Croatia", "Cuba", "Cyprus", "Czech Republic",
"Democratic Republic of the Congo", "Denmark", "Djibouti", "Dominica", "Dominican Republic",
"East Timor", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea",
"Estonia", "Ethiopia", "Faeroe Islands", "Falkland Islands", "Fiji", "Finland",
"Former Yugoslav Republic of Macedonia", "France", "French Guiana", "French Polynesia",
"French Southern Territories", "Gabon", "Georgia", "Germany", "Ghana", "Gibraltar",
"Greece", "Greenland", "Grenada", "Guadeloupe", "Guam", "Guatemala", "Guinea", "Guinea-Bissau",
"Guyana", "Haiti", "Heard Island and McDonald Islands", "Honduras", "Hong Kong", "Hungary",
"Iceland", "India", "Indonesia", "Iran", "Iraq", "Ireland", "Israel", "Italy", "Jamaica",
"Japan", "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Kuwait", "Kyrgyzstan", "Laos",
"Latvia", "Lebanon", "Lesotho", "Liberia", "Libya", "Liechtenstein", "Lithuania", "Luxembourg",
"Macau", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands",
"Martinique", "Mauritania", "Mauritius", "Mayotte", "Mexico", "Micronesia", "Moldova",
"Monaco", "Mongolia", "Montserrat", "Morocco", "Mozambique", "Myanmar", "Namibia",
"Nauru", "Nepal", "Netherlands", "Netherlands Antilles", "New Caledonia", "New Zealand",
"Nicaragua", "Niger", "Nigeria", "Niue", "Norfolk Island", "North Korea", "Northern Marianas",
"Norway", "Oman", "Pakistan", "Palau", "Panama", "Papua New Guinea", "Paraguay", "Peru",
"Philippines", "Pitcairn Islands", "Poland", "Portugal", "Puerto Rico", "Qatar",
"Reunion", "Romania", "Russia", "Rwanda", "Sqo Tome and Principe", "Saint Helena",
"Saint Kitts and Nevis", "Saint Lucia", "Saint Pierre and Miquelon",
"Saint Vincent and the Grenadines", "Samoa", "San Marino", "Saudi Arabia", "Senegal",
"Seychelles", "Sierra Leone", "Singapore", "Slovakia", "Slovenia", "Solomon Islands",
"Somalia", "South Africa", "South Georgia and the South Sandwich Islands", "South Korea",
"Spain", "Sri Lanka", "Sudan", "Suriname", "Svalbard and Jan Mayen", "Swaziland", "Sweden",
"Switzerland", "Syria", "Taiwan", "Tajikistan", "Tanzania", "Thailand", "The Bahamas",
"The Gambia", "Togo", "Tokelau", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey",
"Turkmenistan", "Turks and Caicos Islands", "Tuvalu", "Virgin Islands", "Uganda",
"Ukraine", "United Arab Emirates", "United Kingdom",
"United States", "United States Minor Outlying Islands", "Uruguay", "Uzbekistan",
"Vanuatu", "Vatican City", "Venezuela", "Vietnam", "Wallis and Futuna", "Western Sahara",
"Yemen", "Yugoslavia", "Zambia", "Zimbabwe"
};

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
    Object o=this.getListAdapter().getItem(position);
    String name=o.toString();
    Toast.makeText(SimpleListActivityActivity.this, name, 2000).show();
  }
}

here is the screen which you will get from Android AVD:




For any thing missing and if you use eclipse than press ctrl+shift+O it will automatic import require java classes from android.

Tuesday 5 July 2011

How to Get Your Eclipse-Integrated NDK On Here are the few steps


Sooner or future in your Android game development attempt you may find the need to have some code that runs faster. It turns out that Android code written in C runs 10-100 times as fast as its Java counterpart. I can verify this, as I've already moved a few major components in my newest 3D game engine into native land. That's quite a boost but let's face it - C is a pain in the ass and while Eclipse is great for Java, it's not for C, right? Wrong. 

Here's how to set up a super speedy NDK development environment.
First of all, Eclipse can do way more than just Java. Java is what it's great at and what it was designed for but the architecture makes it so that it can handle any language effectively, including C. There is a component called CDT that allows for C/C++ Development in Eclipse. I'm getting ahead of myself, though. Here's what you need:





If you're in Windows, you'll need Cygwin with the develop packages installed (Especially GCC and Make)


Here's what you need to do:
Install all 3 of those things. I like to install my NDK to c:\Android_NDK. I'll refer to that dir for the rest of this article.
Get acquainted with the NDK. You need to configure each project as an "app" in the c:\Android_NDK\apps dir. Just take a look at the examples. They work and are thorough.
How to test your NDK:
Run cygwin
cd /cygdrive/c/Android_NDK
make APP=hello-jni


It should roll up without errors. If you are lacking GCC or Make or any other develop packages, you will want to run your Cygwin setup again and check to make sure that all of the development packages are installed. If you have strange errors, I suggest reporting them in the NDK user's group.
Once your NDK is running, you can add an app for your project and set up the basic native framework for your project. Please refer to the examples for this part. You will need a specific build file that tells the compiler what sources to compile. JNI code is usually located in your Android project's jni folder. A file called Android.mk will need to be in there which instructs the compiler on what to compile.
After you get the basic configuration done, you will want to start writing some C. NDK uses Java's standard JNI bindings to work. All of the existing documentation on JNI should apply from this point forward. What to code is beyond the scope of this article.


Now for the good part :
If you've done any NDK work, you're probably used to using a text editor or vim or some other editor to edit your C/CPP then running make APP=myapp every time to build, then clicking refresh on your project in Eclipse and then hoping that the shared object library file that gets deployed is current. What a pain in the ass! There's a much, much better way.
Now that you have CDT installed, you can edit all of your C/C++ right from Eclipse. If you right click on a C/CPP source file, just pick Open With--C/C++ Editor and it will use the CDT editor. Much nicer! It won't be able to figure out what the code is doing because it's not compiling it, but it will make editing nice and all in one spot.
Building is a snap as well. Ever used builders in Eclipse? They are configurable triggers that will execute what you configure and refresh resources for you. Make sure you know if you're on the old r3 NDK (upgrade if you are - you should be on r4) and if so, I put different instructions in this list for the different versions. Here's how I set mine up:



Right click on your project, pick properties.
Select "builders" from the left-hand list.
Click "New..." on the right side.
Select "Program" as the configuration type.
I name mine "Native Builder"
Location - c:\cygwin\bin\bash.exe
Working Directory - c:\cygwin\bin
Arguments -
(for NDK r3):
--login -c "cd /cygdrive/c/Android_NDK && make APP=myapp"
(for NDK r4):
--login -c "cd /cygdrive/c/<myapp_project_dir> && /cygdrive/c/Android_NDK/ndk-build"
Make sure you have the two hyphens before login and the quotes after the hyphen-c
Now go to the refresh tab
Check "Refresh resources upon completion"
Select "Specific resources"
Click on the "Specify resources" button and select your project's lib directory.
Check "Recursively include sub-folders"
Now go to the build options tab
Check "Allocate Console"
Check "Launch in background"
Check "Run the builder After a Clean"
Check "Run the builder During manual builds"
Check "Run the builder During auto builds"
Check "Specify working set of relevant resources"
Click on "Specify Resources"
Select your project's JNI directory and all files within.
Now click OK on the bottom.
The assumption here is that cygwin is installed to c:\cygwin, NDK is in c:\Android_NDK and your project is called "myapp". Change where appropriate.
What did you just do?! You made it so that any time you edit any files within your JNI directory and you save them, Eclipse will run the NDK Builder for you via CygwinADT to compile a new APK for you and YOU ARE GOOD TO GO!
This gravely fasted me up while working on my current project. I hope you can all benefit from it!

Simple Android Animation Application

Here is the example for simple android animation using <animation-list/> in  Drawable Folder in android.

Here is the java code for Simple Animation
<!----------------------------    --------------------------------------------->

public class AnimationSimpleActivity extends Activity {
    ImageView mImageView;
    
    private AnimationDrawable introDrawable;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mImageView=(ImageView)findViewById(R.id.animation);
        mImageView.setBackgroundResource(R.drawable.myanimation);
        introDrawable=(AnimationDrawable)mImageView.getBackground();
        mImageView.post(new Animator());
    }
    private long starttime,endtime;
    private class Animator implements Runnable {

    public void run() {
starttime=System.currentTimeMillis();
introDrawable.start();
Timer mTimer=new Timer();
mTimer.schedule(new ActivityChanger(), 3000);
}
}
    
    public class ActivityChanger extends TimerTask{


@Override
public void run() {
endtime = System.currentTimeMillis();
if(endtime-starttime >=1800){
AnimationSimpleActivity.this.finish();
Intent mIntent=new Intent(AnimationSimpleActivity.this, Activity2.class);
startActivity(mIntent);
}
}
   
    }

}

Below is the xml file for animation-list res/drawable/myanimation.xml


<?xml version="1.0" encoding="utf-8"?>
<animation-list
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:oneshot="true">
 <item  android:drawable="@drawable/f1" android:duration="200"/>
 <item  android:drawable="@drawable/f2" android:duration="200"/>
 <item  android:drawable="@drawable/f3" android:duration="200"/>
 <item  android:drawable="@drawable/f4" android:duration="200"/>
 <item  android:drawable="@drawable/f5" android:duration="200"/>
 <item  android:drawable="@drawable/f6" android:duration="200"/>
 <item  android:drawable="@drawable/f7" android:duration="200"/>
 <item  android:drawable="@drawable/f8" android:duration="200"/>
 <item  android:drawable="@drawable/f9" android:duration="200"/>  
   
</animation-list>

Here is the output:





Friday 24 June 2011

How to get Resource Name In Android By Resource Id

Here i update my Custom GridView and i also add the ItemClickListen In It,And Here you can also find the how to get Resources Name By Passing It ID in android.

For that you have to First Refer My Last Post Of Custom GridView at here http://android-vogue.blogspot.com/2011/06/custom-gridview-in-android-with.html so now let see what i update in that is here below


First add the this line in OnCreate Method

mGridViewl.setOnItemClickListener(MyClickListener);

and after that add the


private OnItemClickListener MyClickListener=new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long lg) {

myarray.add(COUNTRIES[position]);
resourcename=getResourceNameByID(R.drawable.class,mThumbIds[position]);
Toast.makeText(Gridview.this, "Image Name is "+ resourcename, 34).show();
//Toast.makeText(Gridview.this, "Mood Has been selected ", Toast.LENGTH_SHORT).show();

//Log.v("log_tag", "the string is "  +  temp);

}
};

add above function in GridView Class

Now the most Important Part For Getting Resource Name Of Image By Passing ID of that Image we add following method in GridView Class


public String getResourceNameByID(Class<?> aClass,int ResourceID) throws IllegalArgumentException{

Field[]drawableFields =aClass.getFields();
for(Field f:drawableFields){
try{
if(ResourceID==f.getInt(null)){
return f.getName();
}
}
catch(Exception e){
e.printStackTrace();
}
}


throw new IllegalArgumentException();

}

Now you are ready to get Resource Name By Id of Resource.





Monday 13 June 2011

Custom GridView In Android With ImageView and TextView

Every one want to do some thing with android ListView and GridView and Much More.
Here is the Example of Custom GridView in Which we have used ImageView and TextView below it.
Now One more thing that is this custom gridview can also done by the using View ,But i done it as shown in my code using Class Like what you want to put in grid just put it in gridview xml file and also make class ViewHolder as done by me in this tutorials .

Here below is my class for the GridView

public class Gridview extends Activity {
    GridView mGridViewl;
    //Context mContext = Gridview.this;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mGridViewl = (GridView) findViewById(R.id.gridview);
        mGridViewl.setAdapter(new EfficientAdapter(this));

    }
   
    private static class EfficientAdapter extends BaseAdapter{
        private LayoutInflater mLayoutInflater;
        public EfficientAdapter(Context context){
            mLayoutInflater=LayoutInflater.from(context);
        }
       
        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return mThumbIds.length;
        }

        @Override
        public Object getItem(int arg0) {
            // TODO Auto-generated method stub
            return arg0;
        }

        @Override
        public long getItemId(int arg0) {
            // TODO Auto-generated method stub
            return arg0;
        }

        @Override
        public View getView(int position, View converView, ViewGroup parent) {
            ViewHolder mVHolder;
            if(converView == null){
                converView=mLayoutInflater.inflate(R.layout.customgrid, parent, false);
                mVHolder=new ViewHolder();
                mVHolder.mImageView=(ImageView)converView.findViewById(R.id.imgview);
                mVHolder.mTextView=(TextView)converView.findViewById(R.id.text);
                mVHolder.mImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                mVHolder.mImageView.setPadding(8,8,8,8);
                converView.setTag(mVHolder);
            }else{
                mVHolder=(ViewHolder)converView.getTag();
            }
            mVHolder.mImageView.setImageResource(mThumbIds[position]);
            mVHolder.mTextView.setText(COUNTRIES[position]);
           
            return converView;
        }
       
    }
   
    static class ViewHolder{
        ImageView mImageView;
        TextView mTextView;
    }

    static final String[] COUNTRIES = new String[] { "Afghanistan", "Albania",
            "Algeria", "American Samoa", "Andorra", "Angola", "Anguilla",
            "Antarctica", "Antigua and Barbuda", "Argentina" };

   

    private static  Integer[] mThumbIds = { R.drawable.android,
            R.drawable.android1, R.drawable.android2,
            R.drawable.android3, R.drawable.android4,
            R.drawable.android5, R.drawable.android6, R.drawable.android7,
            R.drawable.android8, R.drawable.android9 };
}

and here is my main.xml  file for setcontentView(); in my activity

<?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">
    <GridView    android:id="@+id/gridview"
                android:stretchMode="columnWidth"
                 android:cacheColorHint="#00000000"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:numColumns="3"
                android:clipChildren="true"
                android:horizontalSpacing="5dip"
                android:verticalSpacing="5dip">
    </GridView>
</LinearLayout>


here is the another file of customgrid.xml  for use in gridview

<?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"
  >
      <ImageView
      android:src="@drawable/android"
      android:scaleType="center"
      android:cropToPadding="true"
      android:adjustViewBounds="true"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/imgview"
      android:layout_gravity="center"/>
     
      <TextView
      android:text="@string/hello"
     android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/text"
      android:layout_gravity="center_horizontal"
      />
 
</LinearLayout>

Here is the Out Put Image of my Device



Saturday 11 June 2011

How to get Latitude and Longitude of current location in android mobile?

Here is the First Activity class for getting Current Location Latitude and Longitude.
Here is the my java file class

public class LocationGet extends Activity implements LocationListener{
    private TextView latituteField;
    private TextView longitudeField;
    private LocationManager locationManager;
    private String provider;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        latituteField = (TextView) findViewById(R.id.latitude);
        longitudeField = (TextView) findViewById(R.id.longitude);
        // Get the location manager
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        // Define the criteria how to select the locatioin provider -> use
        // default
        Criteria criteria = new Criteria();
        provider = locationManager.getBestProvider(criteria, false);
        Location location = locationManager.getLastKnownLocation(provider);
        // Initialize the location fields
        if (location != null) {
            System.out.println("Provider " + provider + " has been selected.");
            int lat = (int) (location.getLatitude());
            int lng = (int) (location.getLongitude());
            latituteField.setText(String.valueOf(lat));
            longitudeField.setText(String.valueOf(lng));
        } else {
            latituteField.setText("Provider not available");
            longitudeField.setText("Provider not available");
        }

    }

    @Override
    public void onLocationChanged(Location location) {
        int lat = (int) (location.getLatitude());
        int lng = (int) (location.getLongitude());
        latituteField.setText(String.valueOf(lat));
        longitudeField.setText(String.valueOf(lng));
        }

    @Override
    public void onProviderDisabled(String provider) {
        Toast.makeText(this, "Disenabled provider " + provider,
                Toast.LENGTH_SHORT).show();

       
    }

    @Override
    public void onProviderEnabled(String provider) {
        Toast.makeText(this, "Enabled new provider " + provider,
                Toast.LENGTH_SHORT).show();

       
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub
       
    }

    @Override
    protected void onResume() {
        locationManager.requestLocationUpdates(provider, 500, 1, this);
        super.onResume();
    }
   
    /* Remove the locationlistener updates when Activity is paused */
    @Override
    protected void onPause() {
        super.onPause();
        locationManager.removeUpdates(this);
    }

}


here is the xml file to display two textview for lat and lng

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <TextView 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/latitude"
    android:id="@+id/latitude"
    /><TextView 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/longitude"
    android:id="@+id/longitude"
    />
</LinearLayout>

Friday 3 June 2011

How to read local xml file from my asset folder or in res/raw folder?

Here is my main file of java to read xml and parse it.

public class Readxml extends ListActivity {
    ArrayList<String> items=new ArrayList<String>();
    TextView selection;
    String myvalues;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        selection=(TextView)findViewById(R.id.selection);
        Button btn=(Button)findViewById(R.id.btnget);
       
       
       try
       {
           InputStream is=getResources().openRawResource(R.raw.my_xml_sample);
          //here is i specified my xml file name
           DocumentBuilder builder=DocumentBuilderFactory.newInstance().newDocumentBuilder();
           Document doc=builder.parse(is, null);
           NodeList words=doc.getElementsByTagName("Data");
           //NodeList words=doc.getElementsByTagNameNS(arg0, arg1);
          // NodeList mywords=doc.getElementsByTagNameNS("Data" , "Data" );
         
           for(int i=0;i<words.getLength();i++){
              items.add(((Element)words.item(i)).getTextContent());
            // myvalues=((Element)words.item(i)).getNodeValue();
              Log.v("log_tag", "my values is"+ myvalues);
           }
           is.close();
       }
       catch(Throwable t){
          
           Toast.makeText(this, "Exception :"+ t.toString(), 2000).show();
          
          
       }
      
       setListAdapter(new ArrayAdapter<String>(this,
               android.R.layout.simple_list_item_1,
               items));
       btn.setOnClickListener(new OnClickListener() {
       
        @Override
        public void onClick(View arg0) {
            String[] mylist =new String[items.size()];
            for(int i=0,j=0;i<items.size();i=i+18,j++){
                Log.v("log_tag", "the values of item is"+items.get(i));
                mylist[j]=items.get(i);
           
                Log.v("log_tag", "her is my column"+mylist[j]);
           
            }
           
        }
    });
      
       
    }
   
    public void onListItemClick(ListView parent, View v, int position,
            long id) {
            selection.setText(items.get(position).toString());
            }
}