Wednesday, 19 December 2012
Little Green Robot Developer: Share data between two Android applications by usi...
Little Green Robot Developer: Share data between two Android applications by usi...: APP1 package com.example.app1; import android.app.Activity; import android.content.ComponentName; import android.content.Context; i...
Share data between two Android applications by using SharedPreferences
APP1
package com.example.app1;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
Button b1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b1=(Button) findViewById(R.id.button1);
b1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent();
dataWriter();
i.setClassName("com.example.app2", "com.example.app2.MainActivity");
Intent intentDeviceTest = new Intent("android.intent.action.MAIN");
intentDeviceTest.setComponent(new ComponentName("com.example.app1",
"com.example.app2.MainActivity"));
startActivity(i);
}
});
public void dataWriter(){
String strShareValue = "Hello! this is shared data";
SharedPreferences prefs = getSharedPreferences("demopref",Context.MODE_WORLD_READABLE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("demostring", strShareValue);
editor.commit();
}
APP2
package com.example.app2;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
String dataShared;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dataRead();
TextView tv = (TextView)findViewById(R.id.textView1);
tv.setText(dataShared);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void dataRead(){
Context con;
try {
con = createPackageContext("com.example.app1", 0);
SharedPreferences pref = con.getSharedPreferences("demopref", Context.MODE_PRIVATE);
dataShared = pref.getString("demostring", "No Value");
}
catch (NameNotFoundException e) {
Log.e("Not data shared", e.toString());
}
}
}
package com.example.app1;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
Button b1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b1=(Button) findViewById(R.id.button1);
b1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent();
dataWriter();
i.setClassName("com.example.app2", "com.example.app2.MainActivity");
Intent intentDeviceTest = new Intent("android.intent.action.MAIN");
intentDeviceTest.setComponent(new ComponentName("com.example.app1",
"com.example.app2.MainActivity"));
startActivity(i);
}
});
public void dataWriter(){
String strShareValue = "Hello! this is shared data";
SharedPreferences prefs = getSharedPreferences("demopref",Context.MODE_WORLD_READABLE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("demostring", strShareValue);
editor.commit();
}
APP2
package com.example.app2;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
String dataShared;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dataRead();
TextView tv = (TextView)findViewById(R.id.textView1);
tv.setText(dataShared);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void dataRead(){
Context con;
try {
con = createPackageContext("com.example.app1", 0);
SharedPreferences pref = con.getSharedPreferences("demopref", Context.MODE_PRIVATE);
dataShared = pref.getString("demostring", "No Value");
}
catch (NameNotFoundException e) {
Log.e("Not data shared", e.toString());
}
}
}
Thursday, 22 November 2012
Call Other application Activity inside Your Application via Intent in Android
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent();
i.setClassName("PackageNameOfOtherApp", "ClassNameWithPackageOfOtherApp");
Bundle b = new Bundle();
b.putString("name", "umer");
b.putString("num", "1234");
i.putExtras(b);
startActivity(i);
}
});
**************Menifiest**************
</activity>
<activity android:name="ClassNameWithPackageOfOtherApp" >
</activity>
latitude and longitude from GPS and network android
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1, (float) 0, this);
Criteria criteria = new Criteria();
criteria.setPowerRequirement(Criteria.POWER_HIGH);
criteria.setAccuracy(Criteria.ACCURACY_MEDIUM);
String bestprovider = locationManager.getBestProvider(criteria, false);
Location lastknownlocation = locationManager.getLastKnownLocation("gps");
//Toast.makeText(this, GlobalInfo.Latitude+"test", Toast.LENGTH_SHORT).show();
if(lastknownlocation!=null)
{
lat=lastknownlocation.getLatitude();
lng=lastknownlocation.getLongitude();
Toast.makeText(this, lat+".. from gps .."+ lng, Toast.LENGTH_LONG).show();
}else{
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1, (float) 0, this);
lastknownlocation = locationManager.getLastKnownLocation("netwotk");
if(lastknownlocation!=null)
{
lat=lastknownlocation.getLatitude();
lng=lastknownlocation.getLongitude();
Toast.makeText(this, lat+".. from sim .."+ lng, Toast.LENGTH_LONG).show();
}
}
}
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
lat=location.getLatitude();
lng=location.getLongitude();
Log.d("GPS", "onLocationChanged");
Toast.makeText(this,"lat::" +lat+"::long::"+lng, Toast.LENGTH_SHORT).show();
tv.setText("Latitude:: "+ lat + ":: longitude:: "+ lng);
}
@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
}
Tuesday, 11 September 2012
Sim info android source code
package com.umer.cellid;
import java.util.Locale;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.CellLocation;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.telephony.gsm.GsmCellLocation;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class OpencellidActivity extends Activity {
String latitude;
String longitude;
public class OpenCellID {
String mcc; //Mobile Country Code
String mnc; //mobile network code
String cellid; //Cell ID
String lac; //Location Area Code
Boolean error;
String strURLSent;
String GetOpenCellID_fullresult;
public Boolean isError(){
return error;
}
public void setMcc(String value){
mcc = value;
}
public void setMnc(String value){
mnc = value;
}
public void setCallID(int value){
cellid = String.valueOf(value);
}
public void setCallLac(int value){
lac = String.valueOf(value);
}
public String getLocation(){
return("latitude: "+latitude + " longitude: " + longitude);
}
public void groupURLSent(){
strURLSent =
"http://www.opencellid.org/cell/get?mcc=" + mcc
+"&mnc=" + mnc
+"&cellid=" + cellid
+"&lac=" + lac
+"&fmt=txt";
}
public String getstrURLSent(){
return strURLSent;
}
public String getGetOpenCellID_fullresult(){
return GetOpenCellID_fullresult;
}
public void GetOpenCellID() throws Exception {
groupURLSent();
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(strURLSent);
HttpResponse response = client.execute(request);
GetOpenCellID_fullresult = EntityUtils.toString(response.getEntity());
spliteResult();
}
private void spliteResult(){
if(GetOpenCellID_fullresult.equalsIgnoreCase("err")){
error = true;
}else{
error = false;
String[] tResult = GetOpenCellID_fullresult.split(",");
latitude = tResult[0];
longitude = tResult[1];
}
}
}
int myLatitude, myLongitude;
OpenCellID openCellID;
TextView textSignal,batteryLevel;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SignalStrengthListener signalStrengthListener;
TextView textGsmCellLocation = (TextView)findViewById(R.id.gsmcelllocation);
TextView textMCC = (TextView)findViewById(R.id.mcc);
TextView textMNC = (TextView)findViewById(R.id.mnc);
TextView textCID = (TextView)findViewById(R.id.cid);
TextView textLAC = (TextView)findViewById(R.id.lac);
TextView textGeo = (TextView)findViewById(R.id.geo);
TextView textRemark = (TextView)findViewById(R.id.remark);
TextView textImei = (TextView)findViewById(R.id.imei);
TextView textImsi = (TextView)findViewById(R.id.imsi);
TextView textGps = (TextView)findViewById(R.id.gps_langlat);
textSignal = (TextView)findViewById(R.id.signal);
batteryLevel=(TextView) findViewById(R.id.betry);
Button mapButton=(Button) findViewById(R.id.button1);
//retrieve a reference to an instance of TelephonyManager
TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
GsmCellLocation cellLocation = (GsmCellLocation)telephonyManager.getCellLocation();
String networkOperator = telephonyManager.getNetworkOperator();
String mcc = networkOperator.substring(0, 3);
String mnc = networkOperator.substring(3);
textMCC.setText("mcc: " + mcc);
textMNC.setText("mnc: " + mnc);
textImei.setText("Imei: " + getimeinum().toString());
textImsi.setText("imsi: " + getimsinum().toString());
int cid = cellLocation.getCid();
int lac = cellLocation.getLac();
textGsmCellLocation.setText(cellLocation.toString());
textCID.setText("gsm cell id: " + String.valueOf(cid));
textLAC.setText("gsm location area code: " + String.valueOf(lac));
signalStrengthListener = new SignalStrengthListener();
((TelephonyManager)getSystemService(TELEPHONY_SERVICE)).listen(signalStrengthListener,SignalStrengthListener.LISTEN_SIGNAL_STRENGTHS);
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);
if(lastknownlocation!=null)
{
textGps.setText("GPSLocation: Latitude: " + lastknownlocation.getLatitude()+", Longitude: "+ lastknownlocation.getLongitude());
}
textGeo.setText("APN: " + getapn().toString());
this.registerReceiver(this.myBatteryReceiver,
new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
openCellID = new OpenCellID();
openCellID.setMcc(mcc);
openCellID.setMnc(mnc);
openCellID.setCallID(cid);
openCellID.setCallLac(lac);
try {
openCellID.GetOpenCellID();
if(!openCellID.isError()){
// textGeo.setText(openCellID.getLocation());
textRemark.setText( "\n\n"
+ "URL sent: \n" + openCellID.getstrURLSent() + "\n\n"
+ "response: \n" + openCellID.getLocation()+ "\n\n");
}else{
textGeo.setText("Error");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
textGeo.setText("Exception: " + e.toString());
}
mapButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent in=new Intent(OpencellidActivity.this, Map.class);
Bundle b=new Bundle();
b.putString("latitude", latitude);
b.putString("longitude", longitude);
in.putExtras(b);
startActivity(in);
}
});
}
private BroadcastReceiver myBatteryReceiver
= new BroadcastReceiver(){
@Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
if (arg1.getAction().equals(Intent.ACTION_BATTERY_CHANGED)){
batteryLevel.setText("Battery Level: "
+ String.valueOf(arg1.getIntExtra("level", 0)) + "%");
}
}
};
public String getimeinum() {
String deviceID = null;
String serviceName = Context.TELEPHONY_SERVICE;
TelephonyManager m_telephonyManager = (TelephonyManager) getSystemService(serviceName);
CellLocation re= m_telephonyManager.getCellLocation();
GsmCellLocation loc = (GsmCellLocation)m_telephonyManager.getCellLocation();
String Cell_ID = String.format("%08x ", loc.getCid());
int deviceType = m_telephonyManager.getPhoneType();
switch (deviceType) {
case (TelephonyManager.PHONE_TYPE_GSM):
break;
case (TelephonyManager.PHONE_TYPE_CDMA):
break;
case (TelephonyManager.PHONE_TYPE_NONE):
break;
default:
break;
}
// String imsi = m_telephonyManager.getSubscriberId();
deviceID = m_telephonyManager.getDeviceId();
return deviceID ;
}
public String getimsinum()
{
String serviceName = Context.TELEPHONY_SERVICE;
TelephonyManager m_telephonyManager = (TelephonyManager) getSystemService(serviceName);
String imsi = m_telephonyManager.getSubscriberId();
return imsi;
}
private class SignalStrengthListener extends PhoneStateListener
{
@Override
public void onSignalStrengthsChanged(android.telephony.SignalStrength signalStrength) {
// get the signal strength (a value between 0 and 31)
int strengthAmplitude = signalStrength.getGsmSignalStrength();
//do something with it (in this case we update a text view)
textSignal.setText(" signal strength: "+String.valueOf(strengthAmplitude));
// signal=String.valueOf(strengthAmplitude);
super.onSignalStrengthsChanged(signalStrength);
}
}
public String getLocation()
{
String name = null;
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(OpencellidActivity.this, Locale.getDefault());
if(lastknownlocation!=null)
{
lastknownlocation.getLatitude();
lastknownlocation.getLongitude();
}
return name;
}
public String getapn()
{
final Uri APN_TABLE_URI = Uri.parse("content://telephony/carriers");
final Uri PREFERRED_APN_URI = Uri.parse("content://telephony/carriers/preferapn");
//receiving cursor to preffered APN table
Cursor c = getContentResolver().query(PREFERRED_APN_URI, null, null, null, null);
//moving the cursor to beggining of the table
c.moveToFirst();
//now the cursor points to the first preffered APN and we can get some
//information about it
//for example first preffered APN id
int index = c.getColumnIndex("_id"); //getting index of required column
Short id = c.getShort(index); //getting APN's id from
//we can get APN name by the same way
index = c.getColumnIndex("name");
String name = c.getString(index);
return name;
}
}
Manifest
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
Monday, 3 September 2012
how to extract code of apk file.
step 1:Download dex2jar here. Create a new java project and paste (dex2jar-0.0.7.11-SNAPSHOT/lib ) jar files .Copy apk file into newly created java projectRun it and after refresh the project ,you get jar file .Using java decompiler you can view all java class files
step 2: Download java decompiler here
One more way
- Download Dex2Jar zip from this link :http://code.google.com/p/dex2jar/
- Unzip the downloaded zip file.
- Open command prompt & write the following command on reaching to directry where dex2jar exe is there and also copy the apk in same directory.dex2jar targetapp.apk file(./dex2jar app.apk on terminal)
- http://java.decompiler.free.fr/?q=jdgui download decompiler from this link.
- Open ‘targetapp.apk.dex2jar.jar’ with jd-gui File > Save All Sources to sava the class files in jar to java files.
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"/>
<
<
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>
{
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;
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"
//add this in your menifest in activity
android:windowSoftInputMode="stateVisible|adjustResize|adjustPan"
Saturday, 30 June 2012
Go homeActivity with FLAG_ACTIVITY_CLEAR_TOP in android
It sets the FLAG_ACTIVITY_CLEAR_TOP flag on the Intent along with the HomeActivity. This flag launches a new instance of the activity if it isn’t currently running, and closes all the activities on top of it.
public static void goHome( Context ctx ) { if ( ! ( ctx instanceof HomeActivity ) ) { Intent intent = new Intent( ctx, HomeActivity.class ); intent.setFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP ); ctx.startActivity( intent ); } }
Get DeviceType, Android API Level , OS Version and Application Version in Android
int osv=Build.VERSION.SDK_INT;
String osv2=Build.VERSION.RELEASE;
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
if(dm.widthPixels<600)
{
DeviceType="Android SmartPhone";
}
else
{
DeviceType="Android Tablet";
}
String model2=android.os.Build.BRAND;
System.out.println("BRAND is "+model2+" "+DeviceType);
String brandname = model2.substring(0,1).toUpperCase() + model2.substring(1);
DeviceType=brandname+" "+DeviceType;
try
{
app_ver =Integer.toString( this.getPackageManager().getPackageInfo(this.getPackageName(), 0).versionCode);
}
catch (NameNotFoundException e1)
{
e1.printStackTrace();
}
androidinfo.setText(" DeviceType: "+ DeviceType+" \n "+"Android: API Level "+osv+" OS Version "+osv2+"\n Application Version: "+app_ver);
String osv2=Build.VERSION.RELEASE;
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
if(dm.widthPixels<600)
{
DeviceType="Android SmartPhone";
}
else
{
DeviceType="Android Tablet";
}
String model2=android.os.Build.BRAND;
System.out.println("BRAND is "+model2+" "+DeviceType);
String brandname = model2.substring(0,1).toUpperCase() + model2.substring(1);
DeviceType=brandname+" "+DeviceType;
try
{
app_ver =Integer.toString( this.getPackageManager().getPackageInfo(this.getPackageName(), 0).versionCode);
}
catch (NameNotFoundException e1)
{
e1.printStackTrace();
}
androidinfo.setText(" DeviceType: "+ DeviceType+" \n "+"Android: API Level "+osv+" OS Version "+osv2+"\n Application Version: "+app_ver);
Get Current time zone TimeZone.getDefault() Android
TextView textTimeZone = (TextView)findViewById(R.id.timezone);
TimeZone timezone = TimeZone.getDefault();
String TimeZoneName = timezone.getDisplayName();
int TimeZoneOffset = timezone.getRawOffset()/(60 * 60 * 1000);
textTimeZone.setText("My Time Zone\n" +
TimeZoneName + " : " +String.valueOf(TimeZoneOffset));
Update UI using RunOnUiThread in Android
package
com.umer.runOnUiThreadExmp;
import
android.app.Activity;
import
android.os.Bundle;
import
android.widget.TextView;
public
class
RunOnUiThreadExample
extends
Activity {
/** Called when the activity is first created. */
TextView txtview;
@Override
public
void
onCreate(Bundle savedInstanceState) {
super
.onCreate(savedInstanceState);
setContentView(R.layout.main);
txtview=(TextView)findViewById(R.id.txtview);
myThread();
}
public
void
myThread(){
Thread th=
new
Thread(){
@Override
public
void
run(){
try
{
while
(
true
)
{
Thread.sleep(
100
);
RunOnUiThreadExample.
this
.runOnUiThread(
new
Runnable() {
@Override
public
void
run() {
// TODO Auto-generated method stub
// do ur UI work
txtview.setText("my name is umer and i am android developer");
}
});
}
}
catch
(InterruptedException e) {
// TODO: handle exception
}
}
};
th.start();
}
}
Sort listview by title Android
Collections.sort(mylistArray, new Comparator<Object>(){
public int compare(Object o1, Object o2) {
HashMap<?, ?> map1=(HashMap<?, ?>)o1;
HashMap<?, ?> map2=(HashMap<?, ?>)o2;
String s1=(String)map1.get("title");
String s2=(String)map2.get("title");
return s1.compareToIgnoreCase(s2);
}
});
mylistArray have sorted by title. now use sorted array in ur ListView adapter.
Wednesday, 6 June 2012
Checking for the presence of an Internet connection on an Android device
final boolean isInternetOn() {CONNECTIVITY_SERVICE);// ARE WE CONNECTED TO THE NET
if ( connec.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED ||CONNECTING ||CONNECTING ||CONNECTED ) {// MESSAGE TO SCREEN FOR TESTING (IF REQ)
//Toast.makeText(this, connectionType + ” connected”, Toast.LENGTH_SHORT).show();
return true;else if ( connec.getNetworkInfo(0).getState() == NetworkInfo.State.DISCONNECTED || connec.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED ) {//System.out.println(“Not Connected”);
return
false ;
return
false;
connec.getNetworkInfo(0).getState() == NetworkInfo.State.
connec.getNetworkInfo(1).getState() == NetworkInfo.State.
connec.getNetworkInfo(1).getState() == NetworkInfo.State.
}
false ;
}
false;
}
ConnectivityManager connec = (ConnectivityManager)getSystemService(Context.
Upload a Image in server in Android by JSON webservices
package com.wishingWell.JSONFuntions;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONfunctionImage {
private static final String TAG = "UPLOADER";
private static String Tag = "UPLOADER";
private static String urlString="........";
static HttpURLConnection conn;
public static JSONObject getJSONImage(String filepath){
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "-------------------------acebdf13572468";
String line=null;
StringBuilder sb = new StringBuilder();
JSONObject res=null;
try {
// ------------------ CLIENT REQUEST
FileInputStream fileInputStream = new FileInputStream(new File(
filepath));
// open a URL connection to the Servlet
URL url = new URL(urlString);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a cached copy.
conn.setUseCaches(false);
// Use a post method.
conn.setRequestMethod("POST");
//conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary="+boundary);
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(lineEnd + twoHyphens + boundary + lineEnd); //" + pathToOurFile +"
dos.writeBytes("Content-Disposition: form-data; name=\"userimage\";filename=\".png\"" + lineEnd);
dos.writeBytes("Content-Type: image/png" + lineEnd + lineEnd);
Log.e(Tag, "Headers are written");
// create a buffer of maximum size
int bytesAvailable = fileInputStream.available();
int maxBufferSize = 10000;
// int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[] buffer = new byte[bytesAvailable];
// read file and write it into form...
int bytesRead = fileInputStream.read(buffer, 0, bytesAvailable);
while (bytesRead > 0) {
dos.write(buffer, 0, bytesAvailable);
bytesAvailable = fileInputStream.available();
bytesAvailable = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bytesAvailable);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// close streams
Log.e(Tag, "File is written");
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
Log.e(Tag, "error: " + ex.getMessage(), ex);
}
catch (IOException ioe) {
Log.e(Tag, "error: " + ioe.getMessage(), ioe);
}
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(conn
.getInputStream()));
try {
while ((line = rd.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
rd.close();
} catch (IOException ioex) {
Log.e("MediaPlayer", "error: " + ioex.getMessage(), ioex);
}
// System.out.println(" returnr sb ::"+ sb.toString());
try{
res = new JSONObject(sb.toString());
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return res;
}
}
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONfunctionImage {
private static final String TAG = "UPLOADER";
private static String Tag = "UPLOADER";
private static String urlString="........";
static HttpURLConnection conn;
public static JSONObject getJSONImage(String filepath){
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "-------------------------acebdf13572468";
String line=null;
StringBuilder sb = new StringBuilder();
JSONObject res=null;
try {
// ------------------ CLIENT REQUEST
FileInputStream fileInputStream = new FileInputStream(new File(
filepath));
// open a URL connection to the Servlet
URL url = new URL(urlString);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a cached copy.
conn.setUseCaches(false);
// Use a post method.
conn.setRequestMethod("POST");
//conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary="+boundary);
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(lineEnd + twoHyphens + boundary + lineEnd); //" + pathToOurFile +"
dos.writeBytes("Content-Disposition: form-data; name=\"userimage\";filename=\".png\"" + lineEnd);
dos.writeBytes("Content-Type: image/png" + lineEnd + lineEnd);
Log.e(Tag, "Headers are written");
// create a buffer of maximum size
int bytesAvailable = fileInputStream.available();
int maxBufferSize = 10000;
// int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[] buffer = new byte[bytesAvailable];
// read file and write it into form...
int bytesRead = fileInputStream.read(buffer, 0, bytesAvailable);
while (bytesRead > 0) {
dos.write(buffer, 0, bytesAvailable);
bytesAvailable = fileInputStream.available();
bytesAvailable = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bytesAvailable);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// close streams
Log.e(Tag, "File is written");
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
Log.e(Tag, "error: " + ex.getMessage(), ex);
}
catch (IOException ioe) {
Log.e(Tag, "error: " + ioe.getMessage(), ioe);
}
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(conn
.getInputStream()));
try {
while ((line = rd.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
rd.close();
} catch (IOException ioex) {
Log.e("MediaPlayer", "error: " + ioex.getMessage(), ioex);
}
// System.out.println(" returnr sb ::"+ sb.toString());
try{
res = new JSONObject(sb.toString());
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return res;
}
}
Subscribe to:
Posts (Atom)