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