Thursday 19 July 2012

adroid mapview display multiple locations and on tap change activity

package com.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
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 NearMapSearch extends MapActivity {
private MapView mapView;
private MapController mc;
String latJson = "", lngJson = "";
String SelectedItem = "";
String path = "";
Spinner selCategary;
String selectedcategary="";
private LocationManager locationManager;
private String provider;
Location location;
double lat,lng;
GeoPoint point;
public ArrayList<HashMap<String, String>> mylist;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.near);
mapView = (MapView) findViewById(R.id.near_mapview);
selCategary=(Spinner) findViewById(R.id.near_selcategary_categary);
mc = mapView.getController();
mapView.setBuiltInZoomControls(true);
ArrayAdapter<CharSequence> selcategaryadapter = ArrayAdapter.createFromResource(this, R.array.sel_categary, android.R.layout.simple_spinner_item);
selcategaryadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
selCategary.setAdapter(selcategaryadapter);
selCategary.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if(selCategary.getSelectedItemPosition()!=0)
{
selectedcategary=selCategary.getSelectedItem().toString();
mylist = new ArrayList<HashMap<String, String>>();

path = "ajax.googleapis.com/ajax/services/search/local?v=1.0&q="+ selectedcategary+ "&sll=31.418083,73.077575&rsz=large&start=0";

//** service start and data store in mylist ***
JSONObject json = JSONFunction.getJSONCategaryRes(path);
if (json != null) {
JSONObject Jindex = null;
try { JSONObject responseData = json.getJSONObject("responseData");
JSONArray results = responseData.getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
HashMap<String, String> data = new HashMap<String, String>();
Jindex = results.getJSONObject(i);
data.put("latJson", Jindex.getString("lat").toString());
data.put("lngJson", Jindex.getString("lng").toString());
data.put("city", Jindex.getString("city").toString());
data.put("title", Jindex.getString("title").toString());
data.put("url", Jindex.getString("staticMapUrl").toString());
data.put("streetAddress", Jindex.getString("streetAddress").toString());
mylist.add(data);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//** service end ***
Drawable makerDefault = NearMapSearch.this.getResources().getDrawable(
R.drawable.red_dot);
MirItemizedOverlay itemizedOverlay = new MirItemizedOverlay(makerDefault);
point =new GeoPoint((int) ( (31.418083) * 1E6),(int) ((73.077575) * 1E6));
OverlayItem overlayItem = new OverlayItem(point, "fsd", null);
for(int i=0;i<mylist.size();i++)
Double lng=0.0;
Double lat=0.0;
HashMap<String, String> data1=(HashMap<String, String>) mylist.get(i);
lat=Double.parseDouble(data1.get("latJson") );
lng=Double.parseDouble(data1.get("lngJson"));
int lat1=(int)((lat) * 1E6);
int lng1=(int)((lng) * 1E6);
itemizedOverlay.addOverlayItem(lat1,lng1,"abc");
}
mapView.getOverlays().add(itemizedOverlay);
MapController mc = mapView.getController();
mc.setCenter(new GeoPoint((int)(31.418083 * 1E6), (int)(73.077575 * 1E6)));
mc.zoomToSpan(itemizedOverlay.getLatSpanE6(),
itemizedOverlay.getLonSpanE6());
}
else
{
AlertDialog alertDialog = new AlertDialog.Builder(NearMapSearch.this).create();
alertDialog.setTitle("");
alertDialog.setMessage("Result not found.");
alertDialog.setButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
return;
}
});
alertDialog.show();
}
}
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
criteria.setPowerRequirement(Criteria.POWER_LOW);
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
provider = locationManager.getBestProvider(criteria, true);
location = locationManager.getLastKnownLocation(provider);
 
if (location != null)
{
lat = (double) (location.getLatitude());
lng = (double) (location.getLongitude());
}
mapView.setBuiltInZoomControls(true);
point = new GeoPoint( (int) ( (31.418083) * 1E6),(int) ((73.077575) * 1E6));
OverlayItem overlayitem = new OverlayItem(point, "Hello!", "I am here");
final List<Overlay> mapOverlays = mapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.circle);
MItemizedOverlay itemizedoverlay = new MItemizedOverlay(drawable, this);
itemizedoverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedoverlay);
NearMapSearch.this.runOnUiThread(new Runnable() {
public void run() {
mapView.getController().animateTo(point);
}
});
 
}
@Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
private class MirItemizedOverlay extends ItemizedOverlay<OverlayItem> {
private List<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
public MirItemizedOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
// TODO Auto-generated constructor stub
}
@Override
protected OverlayItem createItem(int i) {
return mOverlays.get(i);
}
@Override
public int size() {
return mOverlays.size();
}
public void addOverlayItem(OverlayItem overlayItem) {
mOverlays.add(overlayItem);
populate();
}
public void addOverlayItem(int lat, int lon, String title) {
GeoPoint point = new GeoPoint(lat, lon);
OverlayItem overlayItem = new OverlayItem(point, title, null);
addOverlayItem(overlayItem);
}
protected boolean onTap(int index) {
OverlayItem item = mOverlays.get(index);
System.out.println("item index::" + index);
HashMap<String, String> data1=(HashMap<String, String>) mylist.get(index);;
Intent i=new Intent(NearMapSearch.this,BusinessDetail.class);
Bundle b=new Bundle();
b.putString("title", data1.get("title"));
b.putString("city", data1.get("city"));
b.putString("url", data1.get("url"));
b.putString("streetAddress", data1.get("streetAddress"));
i.putExtras(b);
startActivity(i);
return true;
}
}
}

<manifest>
<
uses-permission android:name="android.permission.INTERNET" />uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
</manifest>




<
<
umer;

Using GPS How to get current location Android

public getLocation()
{
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setPowerRequirement(Criteria.POWER_LOW);
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
String bestprovider = locationManager.getBestProvider(criteria,false);
Location lastknownlocation = locationManager.getLastKnownLocation(bestprovider);
Geocoder geocoder = new Geocoder(SignUp.this, Locale.getDefault());
try{

if(lastknownlocation!=null)
{
List<Address> addresses = geocoder.getFromLocation(lastknownlocation.getLatitude(),lastknownlocation.getLongitude(),100);
showToast(addresses.get(0).getAddressLine(0)+", "+addresses.get(0).getAddressLine(1)+", "+addresses.get(0).getCountryName());
}
else{
Toast.makeText(this, "location is not available", 3000).show();
}
}
catch (IOException e)
{
e.printStackTrace();
}

}


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

Wednesday 11 July 2012

SharedPreferences in android

SharedPreferences prefs;

public static Context context;

context =getApplicationContext();
prefs = PreferenceManager.getDefaultSharedPreferences(context);
//put data in sharedpreference
Editor editor = prefs.edit();
editor.putString(USERNAME_MEM", username11 );
editor.commit();
//get data from sharedpreference
String username= prefs.getString("username", null);
{
// do ur work
}

SplashScreen in android


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;
public class SplashScreen extends Activity
 {
     private Thread mSplashThread;   
     public void onCreate(Bundle savedInstanceState)
      {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.splash);       
          final SplashScreen sPlashScreen = this;  
          mSplashThread =  new Thread()
           {       
               public void run()
                {
                    try
                     {
                      synchronized(this)
                       {
                        wait(1000);                    
                       }
                     }
                    catch(InterruptedException ex)
                     {                   
                     }
                    finish();
                    Intent intent = new Intent();
                    intent.setClass(sPlashScreen, OurWishingWellActivity.class);
                    startActivity(intent);                   
                }
           };       
           mSplashThread.start();       
      }       
     public boolean onTouchEvent(MotionEvent evt)
      {
          if(evt.getAction() == MotionEvent.ACTION_DOWN)
           {
               synchronized(mSplashThread)
                {
                    mSplashThread.notifyAll();
                }
           }
          return true;
      }   
 }

scrolling whole screen including ListView in android


Add this class in ur project
//**** class Utility start****
package com.umer;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;
public class Utility
{
public static void setListViewHeightBasedOnChildren(ListView listView)
{
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null)
{
return;
}
int totalHeight = 0;
int desiredWidth = MeasureSpec.makeMeasureSpec(listView.getWidth(), MeasureSpec.AT_MOST);
for (int i = 0; i < listAdapter.getCount(); i++)
{
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(desiredWidth, MeasureSpec.UNSPECIFIED);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1))+40;
listView.setLayoutParams(params);
listView.requestLayout();
}
}
//**** class Utility end****
//Add this code where you are using ur adapter
try{
ImageAdapter imageAdapter=new ImageAdapter(MyReg1.this, R.layout.my_reg_list, mylist);
bar.setVisibility(View.INVISIBLE);
list.setAdapter(imageAdapter);
list.setScrollingCacheEnabled(false);
Utility.setListViewHeightBasedOnChildren(list);
}
 
catch(Exception exp){
Log.d("Image Adapter Exception",exp.toString());
}

ScrollView scrolls if soft keyboard is visible .. android

//add this in java classthis.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

//add this in your menifest in activity
android:windowSoftInputMode=
"stateVisible|adjustResize|adjustPan"