logcat have error about ArrayList - java

program not error but logcat error about index array list so picture I can't solve . please help me.
public class MainActivity extends MapActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MapView mv = (MapView) findViewById(R.id.mapview);
mv.setBuiltInZoomControls(true);
MapController mc = mv.getController();
ArrayList all_geo_points = getDirections(16.821219, 100.260457, 13.913698, 100.510954);
GeoPoint moveTo = (GeoPoint) all_geo_points.get(0);
mc.animateTo(moveTo);
mc.setZoom(12);
mv.getOverlays().add(new MyOverlay(all_geo_points));
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
public static ArrayList getDirections(double lat1, double lon1, double lat2, double lon2) {
String url = "http://maps.googleapis.com/maps/api/directions/xml?origin=" +lat1 + "," + lon1 + "&destination=" + lat2 + "," + lon2 + "&sensor=false&units=metric";
String tag[] = { "lat", "lng" };
ArrayList list_of_geopoints = new ArrayList();
HttpResponse response = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
response = httpClient.execute(httpPost, localContext);
InputStream in = response.getEntity().getContent();
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(in);
if (doc != null) {
NodeList nl1, nl2;
nl1 = doc.getElementsByTagName(tag[0]);
nl2 = doc.getElementsByTagName(tag[1]);
if (nl1.getLength() > 0) {
list_of_geopoints = new ArrayList();
for (int i = 0; i < nl1.getLength(); i++) {
Node node1 = nl1.item(i);
Node node2 = nl2.item(i);
double lat = Double.parseDouble(node1.getTextContent());
double lng = Double.parseDouble(node2.getTextContent());
list_of_geopoints.add(new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6)));
}
} else {
// No points found
}
}
} catch (Exception e) {
e.printStackTrace();
}
return list_of_geopoints;
}
public class MyOverlay extends Overlay {
private ArrayList all_geo_points;
public MyOverlay(ArrayList allGeoPoints) {
super();
this.all_geo_points = allGeoPoints;
}
#Override
public boolean draw(Canvas canvas, MapView mv, boolean shadow, long when) {
super.draw(canvas, mv, shadow);
drawPath(mv, canvas);
return true;
}
public void drawPath(MapView mv, Canvas canvas) {
int xPrev = -1, yPrev = -1, xNow = -1, yNow = -1;
Paint paint = new Paint();
paint.setColor(Color.BLUE);
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setStrokeWidth(4);
paint.setAlpha(100);
if (all_geo_points != null)
for (int i = 0; i < all_geo_points.size() - 4; i++) {
GeoPoint gp = (GeoPoint) all_geo_points.get(i);
Point point = new Point();
mv.getProjection().toPixels(gp, point);
xNow = point.x;
yNow = point.y;
if (xPrev != -1) {
canvas.drawLine(xPrev, yPrev, xNow, yNow, paint);
}
xPrev = xNow;
yPrev = yNow;
}
}
}
}
This is code About google maps is line drive so input point latitude and longtitude two point for way line to driver and input is array . In code don't error but code have warning about array 8 wraning it all warning about array. run program have error logcat about array index.
01-18 00:37:29.720: E/AndroidRuntime(667): FATAL EXCEPTION: main
01-18 00:37:29.720: E/AndroidRuntime(667): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.getgoogledirection/com.example.getgoogledirection.MainActivity}: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
01-18 00:37:29.720: E/AndroidRuntime(667): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
01-18 00:37:29.720: E/AndroidRuntime(667): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
01-18 00:37:29.720: E/AndroidRuntime(667): at android.app.ActivityThread.access$600(ActivityThread.java:130)
01-18 00:37:29.720: E/AndroidRuntime(667): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
01-18 00:37:29.720: E/AndroidRuntime(667): at android.os.Handler.dispatchMessage(Handler.java:99)
01-18 00:37:29.720: E/AndroidRuntime(667): at android.os.Looper.loop(Looper.java:137)
01-18 00:37:29.720: E/AndroidRuntime(667): at android.app.ActivityThread.main(ActivityThread.java:4745)
01-18 00:37:29.720: E/AndroidRuntime(667): at java.lang.reflect.Method.invokeNative(Native Method)
01-18 00:37:29.720: E/AndroidRuntime(667): at java.lang.reflect.Method.invoke(Method.java:511)
01-18 00:37:29.720: E/AndroidRuntime(667): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
01-18 00:37:29.720: E/AndroidRuntime(667): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
01-18 00:37:29.720: E/AndroidRuntime(667): at dalvik.system.NativeStart.main(Native Method)
01-18 00:37:29.720: E/AndroidRuntime(667): Caused by: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
01-18 00:37:29.720: E/AndroidRuntime(667): at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)
01-18 00:37:29.720: E/AndroidRuntime(667): at java.util.ArrayList.get(ArrayList.java:304)
01-18 00:37:29.720: E/AndroidRuntime(667): at com.example.getgoogledirection.MainActivity.onCreate(MainActivity.java:45)
01-18 00:37:29.720: E/AndroidRuntime(667): at android.app.Activity.performCreate(Activity.java:5008)
01-18 00:37:29.720: E/AndroidRuntime(667): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
01-18 00:37:29.720: E/AndroidRuntime(667): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)

It would be much easier to help you, if you put the output of logcat here.
As you mention, the error probably comes from the method getDirections.

Related

convert array by split to integer

I get error :
FATAL EXCEPTION: main at java.lang.Integer.invalidInt
for this block :
int f = Integer.parseInt(c[1]);
limitter.setProgress(f);
limit.setText(f + " A");
MAIN CODE:
byte[] encodedBytes = new byte[readBufferPosition];
System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
final String data = new String(encodedBytes, "US-ASCII");
readBufferPosition = 0;
handler.post(new Runnable()
{
public void run()
{
String[] c = data.split("limit");
int x = c.length;
if(x>1){
int f = Integer.parseInt(c[1]);
limitter.setProgress(f);
limit.setText(f + " A");
}
What is wrong?
Here is the stack trace:
FATAL EXCEPTION: main
at java.lang.Integer.invalidInt(Integer.java:138)
at java.lang.Integer.parse(Integer.java:375)
at java.lang.Integer.parseInt(Integer.java:366)
at java.lang.Integer.parseInt(Integer.java:332)
at com.tos.hidro.Terminal$2$1.run(Terminal.java:207)
at android.os.Handler.handleCallback(Handler.java:608)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:4987)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)

Code worked before once and no longer works anymore

So this code ran before with flying colors once. Then I closed my computer, and went to sleep when i got up however and tried to run the code I now get an error in logcat and the app crashes. I have not changed the code at all? How could this even happen?
public class DrawingView extends View{
public DrawingView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
RectF rectf = new RectF(0, 0, 200, 0);
private static final int w = 100;
public static int lastColor = Color.BLACK;
private final Random random = new Random();
private final Paint paint = new Paint();
private final int radius = 230;
private final Handler handler = new Handler();
public static int redColor = Color.RED;
public static int greenColor = Color.GREEN;
int randomWidth = 0;
int randomHeight = 0;
public static int addPoints = 0;
private final Runnable updateCircle = new Runnable() {
#Override
public void run() {
lastColor = random.nextInt(2) == 1 ? redColor : greenColor;
paint.setColor(lastColor);
invalidate();
handler.postDelayed(this, 1000);
}
};
#Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
handler.post(updateCircle);
}
#Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
handler.removeCallbacks(updateCircle);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// your other stuff here
if(random == null){
randomWidth =(int) (random.nextInt(Math.abs(getWidth()-radius/2)) + radius/2f);
randomHeight = (random.nextInt((int)Math.abs((getHeight()-radius/2 + radius/2f))));
}else {
randomWidth =(int) (random.nextInt(Math.abs(getWidth()-radius/2)) + radius/2f);
randomHeight = (random.nextInt((int)Math.abs((getHeight()-radius/2 + radius/2f))));
}
canvas.drawCircle(randomWidth, randomHeight, radius, paint);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN){
int x = (int) event.getX();
int y = (int) event.getY();
if(isInsideCircle(x, y) == true){
//Do your things here
if(redColor == lastColor){
Intent i = new Intent(this.getContext(), YouFailed.class);
this.getContext().startActivity(i);
} else {
addPoints++;
}
}else {
}
}
return true;
}
public boolean isInsideCircle(int x, int y){
if ((((x - randomWidth)*(x - randomWidth)) + ((y - randomHeight)*(y - randomHeight))) < ((radius)*(radius))){
return true;
}
return false;
}
}
And here is the errors in logCat. It says that it has something to do with View? and the getParent() method. I think it might have something to do with using this instead of the context, but I'm not sure at all java gets very confusing to me at times.
04-21 11:48:58.287: E/AndroidRuntime(2502): FATAL EXCEPTION: main
04-21 11:48:58.287: E/AndroidRuntime(2502): Process: com.Tripps.thesimplegame, PID: 2502
04-21 11:48:58.287: E/AndroidRuntime(2502): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.Tripps.thesimplegame/com.Tripps.thesimplegame.Main}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.ViewParent android.view.View.getParent()' on a null object reference
04-21 11:48:58.287: E/AndroidRuntime(2502): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
04-21 11:48:58.287: E/AndroidRuntime(2502): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
04-21 11:48:58.287: E/AndroidRuntime(2502): at android.app.ActivityThread.access$800(ActivityThread.java:144)
04-21 11:48:58.287: E/AndroidRuntime(2502): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
04-21 11:48:58.287: E/AndroidRuntime(2502): at android.os.Handler.dispatchMessage(Handler.java:102)
04-21 11:48:58.287: E/AndroidRuntime(2502): at android.os.Looper.loop(Looper.java:135)
04-21 11:48:58.287: E/AndroidRuntime(2502): at android.app.ActivityThread.main(ActivityThread.java:5221)
04-21 11:48:58.287: E/AndroidRuntime(2502): at java.lang.reflect.Method.invoke(Native Method)
04-21 11:48:58.287: E/AndroidRuntime(2502): at java.lang.reflect.Method.invoke(Method.java:372)
04-21 11:48:58.287: E/AndroidRuntime(2502): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
04-21 11:48:58.287: E/AndroidRuntime(2502): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
04-21 11:48:58.287: E/AndroidRuntime(2502): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.ViewParent android.view.View.getParent()' on a null object reference
04-21 11:48:58.287: E/AndroidRuntime(2502): at android.view.ViewGroup.addViewInner(ViewGroup.java:3879)
04-21 11:48:58.287: E/AndroidRuntime(2502): at android.view.ViewGroup.addView(ViewGroup.java:3733)
04-21 11:48:58.287: E/AndroidRuntime(2502): at android.view.ViewGroup.addView(ViewGroup.java:3709)
04-21 11:48:58.287: E/AndroidRuntime(2502): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:406)
04-21 11:48:58.287: E/AndroidRuntime(2502): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:387)
04-21 11:48:58.287: E/AndroidRuntime(2502): at android.app.Activity.setContentView(Activity.java:2164)
04-21 11:48:58.287: E/AndroidRuntime(2502): at com.Tripps.thesimplegame.Main.onCreate(Main.java:48)
04-21 11:48:58.287: E/AndroidRuntime(2502): at android.app.Activity.performCreate(Activity.java:5933)
04-21 11:48:58.287: E/AndroidRuntime(2502): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
04-21 11:48:58.287: E/AndroidRuntime(2502): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
04-21 11:48:58.287: E/AndroidRuntime(2502): ... 10 more
very sorry everyone. thank you for pointing out line 48 because i did not create the object for the contentent view
public class Main extends Activity {
DrawingView v;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
//LinearLayout layout1 = new LinearLayout (this);
//FrameLayout game = new FrameLayout(this);
DrawingView v = new DrawingView (this);
//TextView myText = new TextView(this);
//Button redCircle = new Button(this);
//redCircle.setWidth(300);
//redCircle.setText(DrawingView.addPoints);
//layout1.addView(myText);
//layout1.addView(redCircle);
//redCircle.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
//game.addView(myText);
//game.addView(v);
//game.addView(layout1);
setContentView(v);
//redCircle.setOnClickListener((OnClickListener) this);
}
public void onClick(View v) {
Intent intent = new Intent(this, Main.class);
startActivity(intent);
// re-starts this activity from game-view. add this.finish(); to remove from stack
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

The program is showing null pointer exception....converting double to int

My program causes a null pointer exception... I think the problem is in converting lat3 and lon3 from double to int... Is there some other way of parsing the location in double to int to give it to GeoPoint?
Code:
public class mapLoc extends com.google.android.maps.MapActivity implements LocationListener
{
TextView t ;
int lat2,lon2,lat3,lon3;
Double presentlon,presentlat;
Drawable d;
MapView mv;
MapController mc;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
t = (TextView)findViewById(R.id.maptxt);
Intent intent = getIntent();
Bundle extra = intent.getExtras();
String latitude = extra.getString("latitude");
String longitude = extra.getString("longitude");
t.append(latitude+"\t");
t.append(longitude);
Float lat1 = Float.parseFloat(latitude);
Float lon1 = Float.parseFloat(longitude);
lat2 = (int) (lat1*1E6);
lon2 = (int) (lon1*1E6);
mv = (MapView)findViewById(R.id.maps);
mc = mv.getController();
mc.setZoom(14);
mv.setBuiltInZoomControls(true);
mv.displayZoomControls(true);
mv.setClickable(true);
List<Overlay> mapOverlays = mv.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.marker);
overlay itemizedoverlay = new overlay(drawable, this);
lat3 = (int)(presentlat * 1E6);
lon3 = (int)(presentlon * 1E6);
GeoPoint point = new GeoPoint(lat3, lon3);
OverlayItem overlayitem = new OverlayItem(point, "Hello, user", "This is your present location");
mc.animateTo(point);
itemizedoverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedoverlay);
GeoPoint point2 = new GeoPoint(lat2, lon2);
OverlayItem overlayitem2 = new OverlayItem(point2, "This is your","saved location");
itemizedoverlay.addOverlay(overlayitem2);
mapOverlays.add(itemizedoverlay);
}
#Override
public void onLocationChanged(Location location)
{
presentlat = location.getLatitude();
presentlon = location.getLongitude();
}
#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
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
};
}
Logcat errors:
05-25 10:21:52.444: W/dalvikvm(342): threadid=3: thread exiting with uncaught exception (group=0x4001b188)
05-25 10:21:52.444: E/AndroidRuntime(342): Uncaught handler: thread main exiting due to uncaught exception
05-25 10:21:52.454: E/AndroidRuntime(342): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.loc/com.loc.mapLoc}: java.lang.NullPointerException
05-25 10:21:52.454: E/AndroidRuntime(342): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2496)
05-25 10:21:52.454: E/AndroidRuntime(342): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
05-25 10:21:52.454: E/AndroidRuntime(342): at android.app.ActivityThread.access$2200(ActivityThread.java:119)
05-25 10:21:52.454: E/AndroidRuntime(342): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)
05-25 10:21:52.454: E/AndroidRuntime(342): at android.os.Handler.dispatchMessage(Handler.java:99)
05-25 10:21:52.454: E/AndroidRuntime(342): at android.os.Looper.loop(Looper.java:123)
05-25 10:21:52.454: E/AndroidRuntime(342): at android.app.ActivityThread.main(ActivityThread.java:4363)
05-25 10:21:52.454: E/AndroidRuntime(342): at java.lang.reflect.Method.invokeNative(Native Method)
05-25 10:21:52.454: E/AndroidRuntime(342): at java.lang.reflect.Method.invoke(Method.java:521)
05-25 10:21:52.454: E/AndroidRuntime(342): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
05-25 10:21:52.454: E/AndroidRuntime(342): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
05-25 10:21:52.454: E/AndroidRuntime(342): at dalvik.system.NativeStart.main(Native Method)
05-25 10:21:52.454: E/AndroidRuntime(342): Caused by: java.lang.NullPointerException
05-25 10:21:52.454: E/AndroidRuntime(342): at com.loc.mapLoc.onCreate(mapLoc.java:71)
05-25 10:21:52.454: E/AndroidRuntime(342): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
05-25 10:21:52.454: E/AndroidRuntime(342): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2459)
In code snippet I dont think these presentlat and presentlon are getting initialized and hence throwing NPE.
lat3 = (int)(presentlat * 1E6); // NPE
lon3 = (int)(presentlon * 1E6);
Either initialize them before use or have a null check.
Keep in mind that Double (capital D) is not a primitive type, but a reference type that happens to be able to hold only boxed double (note the difference) values - or null. The Java language doesn't treat unboxing differently than other object accesses through a reference. If the reference is null (which obviously is the case here), it'll throw a NPE. The real difference with unboxing is that such access happens implicitly through something like ref.doubleValue() when you use the reference in arithmetic expressions.
You are right, your app is blowing up because presentlat and presentlon are private variables that have not been initialised. You should move that code into your onLocationChanged function.

Use My location Latitude Longitude and DB Latitude Longitude Calculation Distance

Use My location Latitude Longitude and DB Latitude Longitude Calculation Distance.but always error "The application AndroidGoogleMaps(process com.androidhive.googlemaps)has stopped unexpectedly.Please try again."
public class AndroidGoogleMapsActivity extends MapActivity {
public int mm[][]= new int[100][100];
double[][] rtdist= new double[50][2];
double[][] okdist= new double[50][2];
public GeoPoint[] endpp = new GeoPoint[100];
private static String KEY_SUCCESS = "success";
private MyLocationOverlay mylayer;
private MapController mapController;
private MapView mapView;
protected GeoPoint geoPoint;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViews();
setupMap();
}
private void findViews() {
mapView = (MapView) findViewById(R.id.mapView);
mapController = mapView.getController();
mapView.setBuiltInZoomControls(true);
}
private void setupMap() {
List<Overlay> overlays = mapView.getOverlays();
mylayer = new MyLocationOverlay(this, mapView);
mylayer.runOnFirstFix(new Runnable() {
public void run() {
// Zoom in to current location
mapView.setTraffic(true);
mapController.setZoom(17);
mapController.animateTo(mylayer.getMyLocation());
}
});
overlays.add(mylayer);
GeoPoint startpp = mylayer.getMyLocation();
String b="SELECT lat,lng FROM markers";
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.execqlcmd(b);
try {
if (json.getString(KEY_SUCCESS) != null)
{
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1)
{
for(int i=0 ; i<100 ; i++) {
JSONObject json_row = json.getJSONObject("r"+i);
mm[i][0]=(int)(Double.parseDouble(json_row.getString("c0")) * 1E6) ;
mm[i][1]=(int)(Double.parseDouble(json_row.getString("c1")) * 1E6) ;
endpp[i] =new GeoPoint(mm[i][0], mm[i][1] );
MapController mc = mapView.getController();
DistanceCalculator caldist= new DistanceCalculator(6371);
for(int j = 0; j < 2; j++)
{
rtdist[j][0]=1;
rtdist[j][1]=caldist.CalculationByDistance(startpp, endpp[j]);
//startpp The location of the phone is
//endpp DB's lat lng
//To judge the results of this array is in line with the distance required by the user
if(rtdist[j][1]<=50)
{
okdist[j][0]=rtdist[j][0]; //The amount of store
okdist[j][0]=rtdist[j][1]; //Store the distance
}
}
mc.animateTo(geoPoint);
mc.setZoom(15);
mapView.invalidate();
List<Overlay> mapOverlays = mapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.mark_red);
AddItemizedOverlay itemizedOverlay =
new AddItemizedOverlay(drawable, this);
OverlayItem overlayitem = new OverlayItem(geoPoint, "Hello", "Sample Overlay item");
itemizedOverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedOverlay);
}}}}
catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
mylayer.enableMyLocation();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
mylayer.disableMyLocation();
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
public class DistanceCalculator {
private double Radius;
// R = earth's radius (mean radius = 6,371km)
// Constructor
DistanceCalculator(double R) {
Radius = R;
}
public double CalculationByDistance(GeoPoint startpp, GeoPoint endpp) {
double lat1 = startpp.getLatitudeE6()/1E6;
double lat2 = endpp.getLatitudeE6()/1E6;
double lon1 = startpp.getLongitudeE6()/1E6;
double lon2 = endpp.getLongitudeE6()/1E6;
double dLat = Math.toRadians(lat2-lat1);
double dLon = Math.toRadians(lon2-lon1);
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
Math.sin(dLon/2) * Math.sin(dLon/2);
double c = 2 * Math.asin(Math.sqrt(a));
return Radius * c;
}
}
}
LogCat :
05-13 14:49:44.703: D/dalvikvm(303): GC_FOR_MALLOC freed 4358 objects / 275032 bytes in 316ms
05-13 14:49:44.903: D/dalvikvm(303): GC_FOR_MALLOC freed 10567 objects / 641664 bytes in 58ms
05-13 14:49:45.063: D/dalvikvm(303): GC_FOR_MALLOC freed 4727 objects / 310440 bytes in 45ms
05-13 14:49:45.243: D/dalvikvm(303): GC_FOR_MALLOC freed 6480 objects / 394584 bytes in 48ms
05-13 14:49:45.443: D/dalvikvm(303): GC_FOR_MALLOC freed 7949 objects / 616640 bytes in 51ms
05-13 14:49:45.623: D/dalvikvm(303): GC_FOR_MALLOC freed 6072 objects / 370040 bytes in 51ms
05-13 14:49:45.813: D/dalvikvm(303): GC_FOR_MALLOC freed 4449 objects / 354128 bytes in 62ms
05-13 14:49:45.823: I/dalvikvm-heap(303): Grow heap (frag case) to 3.048MB for 87396-byte allocation
05-13 14:49:45.884: D/dalvikvm(303): GC_FOR_MALLOC freed 45 objects / 2392 bytes in 66ms
05-13 14:49:45.953: D/dalvikvm(303): GC_FOR_MALLOC freed 2 objects / 80 bytes in 67ms
05-13 14:49:45.953: I/dalvikvm-heap(303): Grow heap (frag case) to 3.129MB for 87396-byte allocation
05-13 14:49:46.013: D/dalvikvm(303): GC_FOR_MALLOC freed 0 objects / 0 bytes in 58ms
05-13 14:49:46.273: E/JSON(303): {"tag":"exesqlcmd","success":1,"error":0,"rownum":2,"colnum":2,"r0":{"c0":"23.973728","c1":"121.583641"},"r1":{"c0":"23.973827","c1":"121.585625"}}
05-13 14:49:46.293: D/AndroidRuntime(303): Shutting down VM
05-13 14:49:46.293: W/dalvikvm(303): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
05-13 14:49:46.313: E/AndroidRuntime(303): FATAL EXCEPTION: main
05-13 14:49:46.313: E/AndroidRuntime(303): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.androidhive.googlemaps/com.androidhive.googlemaps.AndroidGoogleMapsActivity}: java.lang.NullPointerException
05-13 14:49:46.313: E/AndroidRuntime(303): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
05-13 14:49:46.313: E/AndroidRuntime(303): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
05-13 14:49:46.313: E/AndroidRuntime(303): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
05-13 14:49:46.313: E/AndroidRuntime(303): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
05-13 14:49:46.313: E/AndroidRuntime(303): at android.os.Handler.dispatchMessage(Handler.java:99)
05-13 14:49:46.313: E/AndroidRuntime(303): at android.os.Looper.loop(Looper.java:123)
05-13 14:49:46.313: E/AndroidRuntime(303): at android.app.ActivityThread.main(ActivityThread.java:4627)
05-13 14:49:46.313: E/AndroidRuntime(303): at java.lang.reflect.Method.invokeNative(Native Method)
05-13 14:49:46.313: E/AndroidRuntime(303): at java.lang.reflect.Method.invoke(Method.java:521)
05-13 14:49:46.313: E/AndroidRuntime(303): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
05-13 14:49:46.313: E/AndroidRuntime(303): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
05-13 14:49:46.313: E/AndroidRuntime(303): at dalvik.system.NativeStart.main(Native Method)
05-13 14:49:46.313: E/AndroidRuntime(303): Caused by: java.lang.NullPointerException
05-13 14:49:46.313: E/AndroidRuntime(303): at com.androidhive.googlemaps.AndroidGoogleMapsActivity$DistanceCalculator.CalculationByDistance(AndroidGoogleMapsActivity.java:178)
05-13 14:49:46.313: E/AndroidRuntime(303): at com.androidhive.googlemaps.AndroidGoogleMapsActivity.setupMap(AndroidGoogleMapsActivity.java:106)
05-13 14:49:46.313: E/AndroidRuntime(303): at com.androidhive.googlemaps.AndroidGoogleMapsActivity.onCreate(AndroidGoogleMapsActivity.java:41)
05-13 14:49:46.313: E/AndroidRuntime(303): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
05-13 14:49:46.313: E/AndroidRuntime(303): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
05-13 14:49:46.313: E/AndroidRuntime(303): ... 11 more
if you want to calculate distance between two geographic point you have to see those two methods in the Location Class
Location Class
you can use it like this:
Location locationA = new Location("point A");
locationA.setLatitude(latA);
locationA.setLongitude(lngA);
Location locationB = new Location("point B");
locationB.setLatitude(latB);
LocationB.setLongitude(lngB);
distance = locationA.distanceTo(locationB);

Not able to get Text-to-Speech work from an non-activity class

I tried to use Text-to-Speech but getting an nullpointerexception.I have many textviews with text init.what i tried to do is that when user clicks on this textviews than text-to-speech speaks up the text which is on that particular textview.Following is the code of 2 of my classes which handles text-to-speech.I have also marked down the lines where i'm getting the nullpointerexception.Please tell me what am i doing wrong?! Thank you.
My TextSpeaker class:
public class TextSpeaker implements OnInitListener{
TextToSpeech tts;
public TextSpeaker(Context c,OnInitListener listener){
tts = new TextToSpeech(c,listener); //Getting NullPointerException here
}
#Override
public void onInit(int status) {
if(status != TextToSpeech.ERROR){
tts.setLanguage(Locale.US);
}
}
}
My TextViewClick class:
public class TextViewClick implements OnClickListener{
public String textHolder;
Context c;
TextToSpeech.OnInitListener listener;
TextSpeaker tts1 = new TextSpeaker(c,listener); //Getting NullPointerException here
#Override
public void onClick(View v) {
TextView tv=(TextView) v;
tv.setTextColor(R.color.red);
textHolder = (String) tv.getText();
System.out.println(textHolder);
tts1.tts.speak(textHolder, TextToSpeech.QUEUE_FLUSH, null);
}
}
My logcat messages:
01-18 13:59:20.017: E/AndroidRuntime(323): FATAL EXCEPTION: main
01-18 13:59:20.017: E/AndroidRuntime(323): java.lang.NullPointerException
01-18 13:59:20.017: E/AndroidRuntime(323): at android.speech.tts.TextToSpeech.<init>(TextToSpeech.java:407)
01-18 13:59:20.017: E/AndroidRuntime(323): at blah.blah.com.TextSpeaker.<init>(TextSpeaker.java:13)
01-18 13:59:20.017: E/AndroidRuntime(323): at independent.vervecoders.com.TextViewClick.<init>(TextViewClick.java:13)
01-18 13:59:20.017: E/AndroidRuntime(323): at independent.vervecoders.com.Independent.onClick(Independent.java:86)
01-18 13:59:20.017: E/AndroidRuntime(323): at android.view.View.performClick(View.java:2408)
01-18 13:59:20.017: E/AndroidRuntime(323): at android.view.View$PerformClick.run(View.java:8816)
01-18 13:59:20.017: E/AndroidRuntime(323): at android.os.Handler.handleCallback(Handler.java:587)
01-18 13:59:20.017: E/AndroidRuntime(323): at android.os.Handler.dispatchMessage(Handler.java:92)
01-18 13:59:20.017: E/AndroidRuntime(323): at android.os.Looper.loop(Looper.java:123)
01-18 13:59:20.017: E/AndroidRuntime(323): at android.app.ActivityThread.main(ActivityThread.java:4627)
01-18 13:59:20.017: E/AndroidRuntime(323): at java.lang.reflect.Method.invokeNative(Native Method)
01-18 13:59:20.017: E/AndroidRuntime(323): at java.lang.reflect.Method.invoke(Method.java:521)
01-18 13:59:20.017: E/AndroidRuntime(323): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
01-18 13:59:20.017: E/AndroidRuntime(323): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
01-18 13:59:20.017: E/AndroidRuntime(323): at dalvik.system.NativeStart.main(Native Method)
It appears that your Context is never initialized. Make sure that you initialize the context before you call the constructor for TextSpeaker.
You also don't need to pass an onInitListener, your TextSpeaker is already an OnInitListener. You can try this in your TextViewClick:
public class TextViewClick implements OnClickListener
{
public String textHolder;
public TextViewClick(Context c)
{
TextSpeaker tts1 = new TextSpeaker(c);
}
#Override
public void onClick(View v)
{
TextView tv=(TextView) v;
tv.setTextColor(R.color.red);
textHolder = (String) tv.getText();
System.out.println(textHolder);
tts1.tts.speak(textHolder, TextToSpeech.QUEUE_FLUSH, null);
}
}
And your TextSpeaker would change as well:
public class TextSpeaker implements OnInitListener
{
TextToSpeech tts;
public TextSpeaker(Context c)
{
tts = new TextToSpeech(c, this);
}
#Override
public void onInit(int status) {
if(status != TextToSpeech.ERROR){
tts.setLanguage(Locale.US);
}
}
}
In addition, make sure you have enabled TTS in your device settings.

Categories

Resources