Wednesday 23 November 2011

Resources

Android some Animation code examples

http://android-er.blogspot.com/2011/10/bitmap-processing-createscaledbitmap.html

Loading page with progress tutorial

http://www.41post.com/4650/programming/android-coding-a-loading-screen-part-3

Bypass Activation for samsung verizon device

http://theunlockr.com/2010/09/20/how-to-bypass-the-activation-screen-on-the-samsung-fascinate/  

Solution for Must override a superclass method Error 
http://androidcodemonkey.blogspot.in/2011/10/how-to-solve-must-override-superclass.html


some best samples:


http://android-coding.blogspot.in/2011/07/androidwebkitwebview.html
Intent flogs
http://blog.akquinet.de/2010/04/15/android-activites-and-tasks-series-intent-flags/ 

Guide for designing the 9-patch image

http://radleymarx.com/blog/simple-guide-to-9-patch/


http://www.androidpeople.com/android-listview-searchbox-sort-items


Convert URI to real path format



http://android-er.blogspot.in/2011/04/convert-uri-to-real-path-format.html


Create Your Own Custom Keyboard for Android Devices

http://tutorials-android.blogspot.in/2011/06/create-your-own-custom-keyboard-for.html

Connecting kindle fire to ubuntu
 http://sentinelweb.co.uk/connecting-kindle-fire-to-adb-on-ubuntu/

Updating 51 rules in ubuntu system to connect android device

http://code.google.com/p/51-android/


HowTo: ListView, Adapter, getView and different list items’ layouts in one ListView


http://android.amberfog.com/?p=296


Getting current date/time without depend on device

http://json-time.appspot.com/




android adb path in ubuntu system

export PATH=$PATH{}:/home/raghu/anddev/anddev_updated/Android_studio_sdk/android-sdk-linux/platform-tools


Tuesday 22 November 2011

Reading Json and creating Json object in android

Here i am taking a code to reading the json which is noting but parsing the twitter account time line
here is my java code which is having the twitter timeline json array
ParseJSON .java


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class ParseJSON extends Activity {

/** Called when the activity is first created. */

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String readTwitterFeed = readTwitterFeed();
try {
JSONArray jsonArray = new JSONArray(readTwitterFeed);
Log.i(ParseJSON.class.getName(),
"Number of entries " + jsonArray.length());
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Log.i(ParseJSON.class.getName(), jsonObject.getString("text"));
}
} catch (Exception e) {
e.printStackTrace();
}
}

public String readTwitterFeed() {
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(
"http://twitter.com/statuses/user_timeline/vogella.json");
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} else {
Log.e(ParseJSON.class.toString(), "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return builder.toString();
}
}

To create Json objcet from the android code use the following method


public void writeJSON() {
JSONObject object = new JSONObject();
try {
object.put("name", "Jack Hack");
object.put("score", new Integer(200));
object.put("current", new Double(152.32));
object.put("nickname", "Hacker");
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println(object);
}

Here we must take the internet permission in manifest file




Friday 18 November 2011

Android location based services to show current location of the device with pin point

Hi here i am providing the code snippet for showing the current location of the android mobile. Here in my java code i used the Location manager class to get the location lat, lan values. Using location listener class we can get locations with good performance.
Here i used Location listener as GPS_PROVIDE but better to use both GPS_PROVIDER and NETWORK_PROVIDER also why because some times mobile can not get the location points using GPS.
Here i registered location listener in onResume() method and released the listener in onPause() method.
I displayed the location values as a text view and displayed the map for the respected location with pointed image. To show the point image i used  MapItemOverlay class object which is the sub class for the ItemizedOverlay. I passed the geopoint and address for the MapItemOverlay class object. Then it will display the location pointed by the drawable image.

Here is my java code:

LocationActivity.java




import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

public class LocationActivity extends MapActivity implements LocationListener {

private static final String TAG = "LocationActivity";

LocationManager locationManager;
Geocoder geocoder;
GeoPoint p ;
TextView locationText;
MapView map;
MapController mapController;
String addr;
int rlat,rlng;
List<Overlay> listOfOverlays;
Drawable drawable;
 List<GeoPoint> pointsList ;
 List<String> addressarray;
 MapItemOverlay itemizedoverlay ;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        pointsList=new ArrayList<GeoPoint>();
        addressarray=new ArrayList<String>();
        locationText = (TextView)this.findViewById(R.id.lblLocationInfo);
        map = (MapView)this.findViewById(R.id.mapview);
        map.setBuiltInZoomControls(true);
        mapController = map.getController();
        mapController.setZoom(16);
        locationManager = (LocationManager)this.getSystemService(LOCATION_SERVICE);
        geocoder = new Geocoder(this);
        Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if (location != null) {
        Log.v(TAG, location.toString());
final int lat = (int) (location.getLatitude() * 1E6);
final int lng = (int) (location.getLongitude() * 1E6);
this.onLocationChanged(location);        
        }
    }

    @Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
locationManager.removeUpdates(this);
}

@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 10, this);
}
   
@Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}

@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
Log.d(TAG, "onLocationChanged with location " + location.toString());
// Displays lat, long, altitude and bearing
String text = String.format("Lat:\t %f\nLong:\t %f\nAlt:\t %f\nBearing:\t %f", location.getLatitude(), location.getLongitude(), location.getAltitude(), location.getBearing());
this.locationText.setText(text);

try {
// This gets a list of addresses
List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 10);
for (Address address : addresses) {
this.locationText.append("\n" + address.getAddressLine(0));
addr+=address.getAddressLine(0);
}

rlat = (int)(location.getLatitude() * 1000000);
rlng = (int)(location.getLongitude() * 1000000);
addressarray.add(addr);


GeoPoint point = new GeoPoint(rlat,rlng);
pointsList.add(point);
mapController.animateTo(point);
 int minLat = Integer.MAX_VALUE;
int minLong = Integer.MAX_VALUE;
int maxLat = Integer.MIN_VALUE;
int maxLong = Integer.MIN_VALUE;
for (int i=0;i<pointsList.size();i++) {
/*maxLat=maxLat+point.getLatitudeE6();
maxLong=maxLong+point.getLongitudeE6();*/
minLat = Math.min(pointsList.get(i).getLatitudeE6(), minLat);
minLong = Math.min(pointsList.get(i).getLongitudeE6(), minLong);
maxLat = Math.max(pointsList.get(i).getLatitudeE6(), maxLat);
maxLong = Math.max(pointsList.get(i).getLongitudeE6(), maxLong);
}
maxLat = maxLat + (int)((maxLat-minLat)*0.1);
minLat = minLat - (int)((maxLat-minLat)*0.1);
maxLong = maxLong + (int)((maxLong-minLong)*0.2);
minLong = minLong - (int)((maxLong-minLong)*0.2);
mapController.zoomToSpan(Math.abs(minLat - maxLat), Math.abs(minLong - maxLong));
mapController.animateTo(new GeoPoint((maxLat + minLat) / 2,(maxLong + minLong) / 2));
listOfOverlays = map.getOverlays();
listOfOverlays.clear();
drawable = this.getResources().getDrawable(R.drawable.icon);
itemizedoverlay = new MapItemOverlay(drawable,this);
for(int i=0;i<pointsList.size();i++){
        p=pointsList.get(i);
    OverlayItem overlayitem = new OverlayItem(p, "location",addressarray.get(i));
        itemizedoverlay.addOverlay(overlayitem);
       }
       itemizedoverlay.nowPopulate();
       listOfOverlays.add(itemizedoverlay);

} catch (IOException e) {
Log.e("LocateMe", "Could not get Geocoder data", e);
}
}

@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub

}

@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub

}

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

}
public class MapItemOverlay extends ItemizedOverlay {
    private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
    Context mContext;
    String id1;
    Float mLat = null ;
    Float mLong = null ;
    Location myLocation = null ;
    LocationManager lm = null ;
    //String[] id,title,spotlight,addr,distance,addr2,phone,url,graphic,city,statecode,zipcode,myLat,myLong,partHead;
    public MapItemOverlay(Drawable defaultMarker,Context context) {
    super(boundCenterBottom(defaultMarker));
    mContext = context;
    // TODO Auto-generated constructor stub
    }
    public void addOverlay(OverlayItem overlay) {
    mOverlays.add(overlay);
   
    }
    public void nowPopulate(){
    populate();
    }
    @Override
    protected OverlayItem createItem(int i) {
    // TODO Auto-generated method stub
    return mOverlays.get(i);

    }
    @Override
    public int size() {
    // TODO Auto-generated method stub
    return mOverlays.size();
    }
    @Override
    protected boolean onTap(final int index) {
    final OverlayItem item = mOverlays.get(index);
    return true;
    }
}
}

Please include package for the above code.
code for
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="Waiting for location..."
    android:id="@+id/lblLocationInfo"
/>
<com.google.android.maps.MapView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mapview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:clickable="true"
    android:apiKey="0D8OQwybgC6JZo8d3VmMRNL40NgE8-aghGarxeQ"
/>
</LinearLayout>
You must generate your own map api key to replace the andoid:apiKey="XXXX" values. then only you can see the map in your emulator/ device

And you must add these permissions into your manifest.xml file


    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
the above tags are add outside the <application> tag and the below tag must add inside the <application> tag
<uses-library android:name="com.google.android.maps" />


The output may like this screenshot




Thank you.



Tuesday 11 October 2011

Android populating music files from sdcard as a listview

Android populating music files from sdcard as a listview:

Hi

Here i am giving a example code to populating a list of songs from sdcard.
This code will works in devises and emulator which is created with sdcard.
At first we are using a Content Resolver class to get the sdcard songs. Here we passed the default android audio path as uri for the content resolver. and used a listview to populate the songs. If there is no sdcard it will show the status for the users.

Here we no need to declare any special permissions in the manifest file.

Here is my user interface file
named it as  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:layout_height="wrap_content"
android:layout_width="fill_parent"
android:id="@+id/PhoneMusicList"></ListView>
</LinearLayout>

and my java file is named as AudioList.java


package org.std;
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class AudioList extends Activity {
      ListView musiclist;
      Cursor musiccursor;
      String au[];
      /** Called when the activity is first created. */
      @Override
      public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            init_phone_music_grid();
      }

      private void init_phone_music_grid() {
       System.gc();
   
          try{
          ContentResolver contentResolver = getContentResolver();
           Uri uri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
           musiccursor = contentResolver.query(uri, null, null, null, null);
           au=new String[musiccursor.getCount()];
           if (musiccursor == null) {
               // query failed, handle error.
           } else if (!musiccursor.moveToFirst()) {
               // no media on the device
            Toast.makeText(this, "No sdcard presents", Toast.LENGTH_SHORT).show();
           } else {
               int titleColumn = musiccursor.getColumnIndex(android.provider.MediaStore.Audio.Media.DISPLAY_NAME);
               int idColumn = musiccursor.getColumnIndex(android.provider.MediaStore.Audio.Media._ID);
               for(int i=0;i<musiccursor.getCount();i++)
               {
                String thisTitle = musiccursor.getString(titleColumn);
                    System.out.println("raghu  "+thisTitle);
                    au[i]=thisTitle;
                    musiccursor.moveToNext();
               }
            musiclist = (ListView) findViewById(R.id.PhoneMusicList);
         musiclist.setAdapter(new MusicAdapter(getApplicationContext()));
         musiclist.setOnItemClickListener(musicgridlistener);
           }
          }
          catch(Exception e){
          System.out.println("No sdcard presents");
          }

      }

      private OnItemClickListener musicgridlistener = new OnItemClickListener() {
            public void onItemClick(AdapterView parent, View v, int position,long id) {
                  System.gc();
            Toast.makeText(AudioList.this, "Clicked item is: "+au[position], Toast.LENGTH_SHORT).show();
            }
      };

      public class MusicAdapter extends BaseAdapter {
            private Context mContext;

            public MusicAdapter(Context c) {
                  mContext = c;
            }

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

            public Object getItem(int position) {
                  return position;
            }

            public long getItemId(int position) {
                  return position;
            }

            public View getView(int position, View convertView, ViewGroup parent) {
                  System.gc();
                  TextView tv = new TextView(mContext.getApplicationContext());
                  if (convertView == null) {
                        tv.setText(au[position]);
                  } else
                        tv = (TextView) convertView;
                  return tv;
            }
      }
}

the output may like this: