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());
            }
}

Tuesday, 17 May 2011

How to Blink Text View in Every 1 second in Android


package com.android.textviewblink;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

public class TextViewBlink extends Activity {
Handler handler;
TextView txtvw;
boolean blinkOn = true;
        @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txtvw = (TextView) findViewById(R.id.txtview);
Thread myThread = null;
Runnable runnable = new CountDownRunner();
myThread = new Thread(runnable);
myThread.start();

}

public void update(){
runOnUiThread(new Runnable() {

@Override
public void run() {
// TODO Auto-generated method stub
if (blinkOn) {
 txtvw.setVisibility(View.VISIBLE);
//txtvw.setText("Himanshu");
Log.v("log_tag", "true is gone");
} else {
txtvw.setVisibility(View.INVISIBLE);
//txtvw.setText("Mistri");
Log.v("log_tag", "false is gone");
}
blinkOn = !blinkOn;
}
});
}
class CountDownRunner implements Runnable {

// @Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
                                      Thread.sleep(1000); //here you can change the time of blink
update();
Log.v("log_tag", "here the thread come for every 1 second ");

} catch (InterruptedException e) {
// Thread.currentThread().interrupt();
Log.e("log_tag", "Error s " + e.toString());
} catch (Exception e) {
Log.e("log_tag", "Error is " + e.toString());
}
}
}
}
}

Monday, 16 May 2011

Android Button Design and selector

For first The xml file for may main layout in android activity is following

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">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="@string/hello" />
<LinearLayout android:orientation="horizontal"
android:layout_width="wrap_content" android:layout_height="wrap_content">
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Done" android:id="@+id/donebtn"
android:padding="5dip" android:background="@drawable/button_view" />
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="back" android:id="@+id/backbtn"
android:padding="5dip" android:background="@drawable/button_view" />
</LinearLayout>
<LinearLayout android:orientation="horizontal"
android:layout_width="wrap_content" android:layout_height="wrap_content">
<Button android:text="button_selector" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:background="@drawable/selector" />
</LinearLayout>
</LinearLayout>
-------------------------------------------------------------------------------------------------------------

After declare main xml file we will make 


<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#453657" />
<stroke android:width="1dp" android:height="1dp"  android:color="#FFD40F"  />
<corners android:bottomLeftRadius="8dip"
android:topRightRadius="8dip" android:topLeftRadius="8dip"
android:bottomRightRadius="8dip" />
</shape>

this xml file in drawable folder of your project .
<solid/> this tag is for background color of shape
<stroke/> this tag is used for boarder of shape
<corners/> this tag is used for make the corner round at given value.

and now for changing on button clicked changes we define again new xml file like this below.

Selector.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/spinner_dropdown_background_down"
android:state_pressed="true" />
 
<item android:drawable="@drawable/spinner_dropdown_background_down" 
android:state_focused="true" />
<item android:drawable="@drawable/spinner_dropdown_background_up" />
</selector>




Wednesday, 11 May 2011

Custom ListView In android

Here is the android tutorial for how to make android custom list view with TextView ,Image View ,Check Box

Below is the java file for it.

package android.tutorial.customlist;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class CustomListView extends Activity {
    ListView mListview;
/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mListview=(ListView)findViewById(R.id.listview);
        mListview.setAdapter(new mCustomList(this));
      
    }
    public class mCustomList extends BaseAdapter{
     private Context mContext;

     public mCustomList(Context c){
     mContext = c;
     }
     @Override
public int getCount() {
// TODO Auto-generated method stub
return COUNTRIES.length;
}

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

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

@Override
public View getView(int position, View converView, ViewGroup parent) {
View List;
if(converView==null){
List=new View(mContext);
LayoutInflater mLayoutinflater=getLayoutInflater();
List=mLayoutinflater.inflate(R.layout.mylist, parent, false);
}
else{
List = (View)converView;
}
ImageView imageView = (ImageView)List.findViewById(R.id.imgview);
TextView textView = (TextView)List.findViewById(R.id.text);
CheckBox chkbox=(CheckBox)List.findViewById(R.id.chkbox);
textView.setText(COUNTRIES[position]);

// TODO Auto-generated method stub
return List;
}
    
    }
  
    static final 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"
      };
}


The Xml File for Main activity is here:

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"
    >
<ListView
android:id="@+id/listview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:scrollbars="none"
></ListView>
</LinearLayout>


for making custom list view here is the custom xml file you can modified file as require listview .


<?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="wrap_content"
android:background="@drawable/list_back">
<TextView android:id="@+id/text" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:textColor="#099900" />
<ImageView android:layout_width="wrap_content"
android:layout_height="wrap_content" android:scaleType="center"
android:id="@+id/imgview" android:src="@drawable/icon" android:layout_centerInParent="true" />
<CheckBox android:id="@+id/chkbox" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:checked="true" android:layout_alignParentRight="true" android:layout_marginRight="10dip" />
</RelativeLayout>




Thursday, 28 April 2011

Why to choice android not iPhone or Other Phone Here the 10 Reasons


10 Things Android Does Better Than iPhone OS

When Android first debuted on the HTC Dream (also known as the G1) back in October of 2008, it was deemed an "iPhone Killer." While it didn't quite slay Apple's handset, it was the first step in a revolution against the tyrannous iPhone. The initial Android platform bested the iPhone OS on several levels, but lacked some key functionalities that the iPhone could provide. Since then, Android has grown - not only meeting all of the functionalities of the iPhone, but besting it in nearly all aspects from an extensive list of devices to a growing Android Marketplace. Here is our list of the top 10 things Android does better than the iPhone.

1: Android can Run Multiple Apps at the Same Time


Starting with version 1.0, Android has been able to run multiple applications at the same time regardless of whether they are system apps or apps from the Android Marketplace. The current version of iPhone OS does offer limited multitasking, but only allows native applications such as Mail, iPod and Phone to run in the background. Android users benefit greatly from this discrepancy, as they can receive notifications, listen to music, or even record GPS data without keeping the application open. Apple will try to level the playing field with iPhone OS 4, granting developers access to a small and limiting list of APIs that can run certain services in the background, but it's a long way from the true multitasking that Android has.

2:  Android Keeps Information Visible on Your Home Screen


One of the key features Android has is a customizable home screen keeps active widgets right at your fingertips, always accesible and always visible - without having to launch an application first. There are widgets for just about every app in the Android Marketplace from playing music to checking the weather and keeping up to date on Facebook. Meanwhile iPhone users are force to flip through their app list to locate and launch each app. If you wanted to check the forecast, for example, you would have to find the app, launch it, and then wait for it to load. With Android, all of that information can be displayed directly on your home screen, never more than a finger swipe away.


3: Android Has a Better App Market


It's true that Apple's App Store has over 180,000 applications, while the Android Marketplace has only just broken the 50,000 mark but Android's rapid growth and adoption give it the potential to catch up to the iPhone App Store. Android also has another advantage: a completely open market. Apple receives around 10,000 app submissions per week, yet many apps are overlooked because they appear too simple or denied because a similar app already exists. The Android Marketplace is driven entirely by its consumers, so the best app is the one that succeeds - not the first one to reach the market. In addition, the Android Marketplace doesn't censor its apps, so the possibilities are truly endless.

4: Android Gives You Better Notifications 


The iPhone has some trouble with notifications. Because it's restricted to pop-up notifications, it can only handle one at a time and because it lacks multitasking, applications must be open in order for them to make notifications. Android, on the other hand, has a convenient notification bar which displays an icon for every notification you have waiting. The notification bar can also be pulled downward to reveal more detail about each notification. Android also allows app developers to make notification details viewable from the lock screen, something the iPhone can only do with native applications.

5: Android Lets You Choose Your Hardware 


Apple users are encouraged to "Think Different" but when it comes to the actual hardware, they don't get much choice. You can pick the color, either black or white, and you get to choose between the 16GB or the pricier 32GB version. Other than that, you're stuck with the 3.5-inch, 320x480 pixel display, 256MB of RAM, and 600MHz processor. Because Android is an open platform, manufacturers have the freedom to pair it with any hardware they want, like the Nexus One (with 3.7-inch, 480x800 pixel display, 512MB of RAM, and 1GHz Snapdragon processor) or the Motorola Droid which has a physical keypad. Obviously, available selections will vary by carrier - speaking of which....

6: Android Lets You Choose Your Carrier

AT&T truly is the iPhone's weakest link. The iPhone's success turned the country's fastest 3G network into a staggering mess of dropped calls and dodgy data connections. If you lust after an iPhone and live in an area with poor AT&T coverage, you're stuck struggling with low signal quality, slow data speeds, and missed calls. Android devices are available on every major cellular carrier (although AT&T only offers a single, somewhat underpowered, Android phone). Verizon has the Motorola Droid, Droid Eris, and Droid Incredible to start. T-Mobile has the Nexus One, MyTouch 3G, Behold II, and will soon carry the MyTouch Slide. And Sprint has the Hero, Moment, and plans for the very promising Evo 4G. No matter where you live, Android lets you pick the carrier that's best for you.

7: Android Lets You Install Custom ROMs

The iPhone can be Jailbroken for some additional functionality, like installing apps that aren't available in the App Store, but the overall experience is the same. You're still stuck with the same exact interface. Similar to the Jailbreaking movement, Android has a small community dedicated to building custom ROMs for Android devices. Not only do Custom ROMs bring the same functionality Jailbreaking does, but they also bring an additional level of customization to your phone. There are ROMs that port custom UIs from one device to another. Other ROMs strip down bulky features and optimize for speed. With Android, nothing is out of reach.

8: Android Lets You Change Your Settings Faster

Smartphones have been gaining more and more functionality over the past few years: Wi-Fi, GPS, 4G, Bluetooth, etc. While these are all great and necessary additions, they have very adverse affects on battery life. In attempts to counter poor battery life, users have taken to toggling system settings like turning on Wi-Fi or 3G on only when they are needed. iPhone users are stuck digging around in the system settings every time they want to use the internet or a Bluetooth device. Android lets you use widgets to manage your settings directly from your home screen - and for those lesser-used settings that might not have dedicated widgets, you can also create shortcuts on your home screen to take you directly to the setting you want to change.

9: Android Does Google and Social Integration

With Smartphones giving us constant connectivity, it's not surprising that the majority of our computerized lives are moving online. We have email for our messages, Flickr for our photos, Google Docs for our documents, and Facebook and Twitter for our social lives. Android offers the ability to integrate all of this natively. Your Gmail account can be automatically synchronized with your phone. Photos taken with your phone can be automatically uploaded to Flickr. Your phone can even be linked to your Facebook account and can sync your phone contacts with your Facebook friends - complete with profile images, email addresses, and phone numbers. The iPhone can do this only through use of third party apps, and is nowhere near as seamless to use as the Android alternative.

10: Android Gives You More Options to Fit Your Budget 

If you've ever thought about buying an iPhone, you have probably noticed the price tag. The older iPhone 3G costs $99 with a two-year commitment and performs sluggishly with the latest OS updates when compared to the 3GS (which will run you a whopping $199 with two-year agreement). Because Android is an open source platform, it is very cost effective to implement which means savings for the end user. Every major cellular carrier (except for AT&T) has at least one Android phone available free with two-year agreement. Of course these are lower end Android devices, but they are still comparable in performance to the iPhone 3GS. The most expensive Android phones (which significantly outperform the iPhone 3GS) are  $199 with two-year contract.








Wednesday, 27 April 2011

How to Start Multiple Thread in Android

here is the code of java where define two thread for android application main class


package com.practice.secondhand;

import java.util.Date;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;

public class SecondHand extends Activity {
// private Handler mHandler = new Handler();
protected static final String TAG = SecondHand.class.getName();
private ImageView img;
Handler mHandler;

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Thread myThread = null;
Runnable runnable = new CountDownRunner();
myThread = new Thread(runnable);
myThread.start();

}

private void doPlay(){
new Thread(new Runnable() {

@Override
public void run() {
// TODO Auto-generated method stub

Log.v("log_tag", "this is seocond thread");

}
}).start();
}
public void doRotate() {

runOnUiThread(new Runnable() {
public void run() {
try {

Date dt = new Date();
int hours = dt.getHours();
int minutes = dt.getMinutes();
int seconds = dt.getSeconds();
String curTime = hours + ":" + minutes + "::" + seconds;
Log.v("log_tag", "Log is here Time is now" + curTime);
img = (ImageView) findViewById(R.id.imgsecond);
RotateAnimation rotateAnimation = new RotateAnimation((seconds - 1) * 6, seconds * 6,
Animation.RELATIVE_TO_SELF, 0.5f,Animation.RELATIVE_TO_SELF, 0.5f);

rotateAnimation.setInterpolator(new LinearInterpolator());
rotateAnimation.setFillAfter(true);

img.startAnimation(rotateAnimation);
} catch (Exception e) {
Log.e("log_tag", "Error msg is " + e.toString());

}
}
});
}

class CountDownRunner implements Runnable {
// @Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
// Log.v("log_tag", "Roate is going");
doRotate();
Thread.sleep(1000);
doPlay();
} catch (InterruptedException e)
{
// Thread.currentThread().interrupt();
} catch (Exception e) {
Log.e("log_tag", "Error is " + e.toString());
}
}
}
}

}


in this class doRotate(); function is for the updating ui thread in my class it is for the analog clock second hand for updating second hand .and doPlay() is thread for doing any other thing at every one second.