I'm building an air extension and the very first method to call on my extention is to check if
GCMRegistrar.checkDevice($context.getActivity());
GCMRegistrar.checkManifest($context.getActivity());
are supported and set, so wrote: CheckGcm.java
package com.doitflash.air.extensions.gcm;
import com.adobe.fre.FREContext;
import com.adobe.fre.FREFunction;
import com.adobe.fre.FREInvalidObjectException;
import com.adobe.fre.FREObject;
import com.adobe.fre.FRETypeMismatchException;
import com.adobe.fre.FREWrongThreadException;
import com.google.android.gcm.GCMConstants;
import com.google.android.gcm.GCMRegistrar;
public class CheckGcm implements FREFunction
{
private String _result;
public FREObject call(FREContext $context, FREObject[] $params)
{
//$context.dispatchStatusEventAsync("variable", "value");
try
{
GCMRegistrar.checkDevice($context.getActivity());
GCMRegistrar.checkManifest($context.getActivity());
_result = "true";
}
catch(Exception err)
{
_result = "false";
}
return as3ConvertValue(_result);
}
private FREObject as3ConvertValue(String $value)
{
try
{
return FREObject.newObject($value);
}
catch (FREWrongThreadException e)
{
return null;
}
}
}
and I setup the android manifest like this:
<manifestAdditions><![CDATA[<manifest android:installLocation="auto">
<permission android:name="air.air.com.doitflash.SampleApp.permission.C2D_MESSAGE" android:protectionLevel="signature" />
<uses-permission android:name="air.air.com.doitflash.SampleApp.permission.C2D_MESSAGE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.VIBRATE" />
<application>
<activity>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:enabled="true"
android:exported="true"
android:name="com.google.android.gcm.GCMBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="air.air.com.doitflash.SampleApp" />
</intent-filter>
</receiver>
<service
android:enabled="true"
android:exported="true"
android:name="com.doitflash.air.extensions.gcm.GCMIntentService" />
</application>
</manifest>]]></manifestAdditions>
I have also setup GCMIntentService:
package com.doitflash.air.extensions.gcm;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gcm.GCMBaseIntentService;
public class GCMIntentService extends GCMBaseIntentService
{
private static final String TAG = "===GCMIntentService===";
public GCMIntentService()
{
super("000000"); // senderID
}
#Override
protected void onRegistered(Context arg0, String registrationId)
{
}
#Override
protected void onUnregistered(Context arg0, String arg1)
{
}
#Override
protected void onMessage(Context arg0, Intent arg1)
{
//Log.i(TAG, "notification title = " + arg1.getStringExtra("title"));
//Log.i(TAG, "notification message = " + arg1.getStringExtra("msg"));
//Log.i(TAG, "notification type = " + arg1.getStringExtra("type"));
//Log.i(TAG, "notification id= " + arg1.getStringExtra("id"));
}
#Override
protected void onError(Context arg0, String errorId)
{
}
#Override
protected boolean onRecoverableError(Context context, String errorId)
{
return super.onRecoverableError(context, errorId);
}
}
everything looks fine in my eyes but when I try tracing the check method in my air project, it returns null! so I know there must be something wrong with:
GCMRegistrar.checkDevice($context.getActivity());
GCMRegistrar.checkManifest($context.getActivity());
because when I remove these two lines, the trace in air returns true. just before starting to build the air extension, I built a sample GCM in java and everything was working perfectly but I don't seem to understand why the air version does not work. any ideas?
UPDATE: I used eclipse logcat to see what is happening on my phone and this may be some hints:
Could not find method com.google.android.gcm.GCMRegistrar.checkDevice, referenced from method com.doitflash.air.extensions.gcm.CheckGcm.call
unable to resolve static method 284: Lcom/google/android/gcm/GCMRegistrar;.checkDevice (Landroid/content/Context;)V
Related
Iam trying to mock switchyard endpoint switchyard://TohpGetAccountReports using the mock endpoint in camel. the mockAccountReportEndpoint defined in junit test is returning null and the test id failing with nullpointer exception.can you please tell me what is wrong with my code?
Camel route :
<route id="accountReportRoute" streamCache="true">
<from uri="direct:accountReport" />
<doTry>
<setProperty propertyName="hpResponse">
<constant>A</constant>
</setProperty>
<to
uri="xslt:xslt/account_reports_manager/create_get_accountreport_request.xslt" />
<log message="GetAccountReports Request : ${body}" logName="esb.hp.InModelProvider.AccountReport"
loggingLevel="TRACE" />
<to
id="AccountReportEndpoint" uri="switchyard://TohpGetAccountReports?operationName=GetAccountReports" />
<log message="GetAccountReports Response : ${body}" logName="esb.hp.InModelProvider.AccountReport"
loggingLevel="TRACE" />
<to
uri="xslt:xslt/account_reports_manager/create_get_accountreport_response.xslt" />
<doCatch>
<exception>java.lang.Exception</exception>
<handled>
<constant>false</constant>
</handled>
<log
message="Exception in hp Model provider accountReportRoute ${exception.stacktrace} "
logName="esb.hp.InModelProvider.AccountReport" loggingLevel="ERROR" />
</doCatch>
</doTry>
<log message="Workaround for handling account report soap fault"
logName="esb.hp.InModelProvider.AccountReport" loggingLevel="DEBUG" />
</route>
junit test class
package com.company.esb.hp.in.modelprovider.test;
import java.util.Map;
import org.apache.camel.CamelContext;
import org.apache.camel.EndpointInject;
import org.apache.camel.Exchange;
import org.apache.camel.Expression;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.AdviceWithRouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.impl.DefaultExchange;
import org.apache.camel.model.ModelCamelContext;
import org.apache.log4j.Logger;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.switchyard.ServiceDomain;
import org.switchyard.component.test.mixins.cdi.CDIMixIn;
import org.switchyard.component.test.mixins.http.HTTPMixIn;
import org.switchyard.test.BeforeDeploy;
import org.switchyard.test.Invoker;
import org.switchyard.test.ServiceOperation;
import org.switchyard.test.SwitchYardRunner;
import org.switchyard.test.SwitchYardTestCaseConfig;
import org.switchyard.test.SwitchYardTestKit;
import org.switchyard.transform.config.model.TransfohpwitchYardScanner;
import com.company.esb.common.test.esbSwitchyardTest;
import com.company.esb.hp.in.modelprovider.test.util.RiskInProviderUtil;
#SwitchYardTestCaseConfig(config = SwitchYardTestCaseConfig.SWITCHYARD_XML, mixins = {
CDIMixIn.class, HTTPMixIn.class }, scanners = { TransfohpwitchYardScanner.class })
#RunWith(SwitchYardRunner.class)
public class hpInModelProviderTest extends esbSwitchyardTest {
private static final Logger LOG = Logger
.getLogger(hpInModelProviderTest.class);
private SwitchYardTestKit testKit;
public static final String getAcctResult = "TohpGetAccountReports";
#EndpointInject(uri = "mock://switchyard:TohpGetAccountReports*")
protected MockEndpoint mockAccountReportEndpoint;
#BeforeDeploy
public void setProperties() {
System.setProperty("esb.hp.inmodelprovider.url", "http://pusslasrws1451.company.biz");
}
#Before
public void installServices() {
simulateesbServices(testKit);
}
#Test
public void testAccountReportDirectRouteSuccess() throws Exception {
String request = readFile("xml/endtoend/success/GetJobsResults/get_job_status-response.xml");
ServiceDomain domain = testKit.getServiceDomain();
//testKit.removeService(getAcctResult);
//testKit.registerInOutService(getAcctResult,
// new GetAccountReportsServiceMockExchangeHandler());
CamelContext ctx = (CamelContext) domain
.getProperty("CamelContextProperty");
Exchange ex = new DefaultExchange(ctx);
ModelCamelContext modelContext = (ModelCamelContext) ctx;
modelContext.getRouteDefinition("accountReportRoute").adviceWith(modelContext, new AdviceWithRouteBuilder() {
#Override
public void configure() throws Exception {
weaveById("AccountReportEndpoint").replace().to(mockAccountReportEndpoint);
}
});
mockAccountReportEndpoint.expectedMessageCount(1);
mockAccountReportEndpoint.returnReplyBody(new Expression() {
#Override
public <T> T evaluate(Exchange exchange, Class<T> type) {
return exchange.getContext().getTypeConverter().convertTo(type, RiskInProviderUtil.readFile("xml/endtoend/success/GetJobsResults/get_account_report_service-response.xml"));
}
});
// MockEndpoint endpoint = getMockEndpoint("mock:switchyard:service");
ex.setProperty("sToken", "f3669d3a-5a2b-4b99-a8df-3aabfd4aae58");
ex.setProperty("sAccId", "196497");
ex.getIn().setBody(request);
ProducerTemplate producer = ctx.createProducerTemplate();
producer.send("direct:accountReport", ex);
System.out.println(ex.getIn().getBody(String.class));
}
#Override
protected void addSetupProperties(Map<String, String> map) {
}
}
..after you have done the adviceWith you must start CamelContext by invoke the start method on the context instance.
http://camel.apache.org/advicewith.html#AdviceWith-UsingisUseAdviceWith()
Try to override the isUseAdviceWith() method (should return true) and start the context after you have done the adviceWith. If it has been already started then try to stop() it and start() it again (cold restart).
I am trying to make my program able to get the user's current longitude and latitude and then place a marker to it. I have used various method in the Internet but none of them seemed to work. From what I have observed I suspect the reason the trouble is that the program fails to get the permission, despite I have already set it in the manifest
Here is the code, I currently only use setMyLocationEnabled to demonstrate the problem
package com.example.user.googlemaptest2;
import android.*;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.io.IOException;
import java.util.List;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private double longitudeDefaultLocation;
private double latitudeDefaultLocation;
private static final int MY_PERMISSION_ACCESS_COARSE_LOCATION = 11;
private static final int MY_PERMISSION_ACCESS_FINE_LOCATION = 12;
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
longitudeDefaultLocation = location.getLongitude();
latitudeDefaultLocation = location.getLatitude();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions( this, new String[] { android.Manifest.permission.ACCESS_COARSE_LOCATION },
MapsActivity.MY_PERMISSION_ACCESS_COARSE_LOCATION );
ActivityCompat.requestPermissions( this, new String[] { Manifest.permission.ACCESS_FINE_LOCATION },
MapsActivity.MY_PERMISSION_ACCESS_FINE_LOCATION );
}
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
mMap.animateCamera(CameraUpdateFactory.zoomTo(14));
}
else
{
Toast.makeText(MapsActivity.this,"FAIL", Toast.LENGTH_LONG).show();
}
}
public void onSearch(View view)
{
EditText location_tf = (EditText)findViewById(R.id.TFaddress);
String location = location_tf.getText().toString();
List<Address> addressList = null;
if (location !=null || location.equals("")) {
Geocoder geocoder = new Geocoder(this);
try {
addressList = geocoder.getFromLocationName(location,1);
} catch (IOException e) {
e.printStackTrace();
}
Address address = addressList.get(0);
LatLng latLng = new LatLng( address.getLatitude(), address.getLongitude());
mMap.addMarker(new MarkerOptions().position(latLng).title("Marker"));
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
}
}
public void changeType (View view)
{
if (mMap.getMapType() == GoogleMap.MAP_TYPE_NORMAL)
{
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
}
else
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
public void onZoom(View view)
{
if (view.getId() == R.id.zoomInButton);
{
mMap.animateCamera(CameraUpdateFactory.zoomIn());
}
if (view.getId() == R.id.zoomOutButton)
{
mMap.animateCamera(CameraUpdateFactory.zoomOut());
}
}
This is the content of my Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.user.googlemaptest2">
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but you must specify either coarse or fine
location permissions for the 'MyLocation' functionality.
-->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.USE_CREDENTIALS" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<!--
The API key for Google Maps-based APIs is defined as a string resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key used to sign the APK.
You need a different API key for each encryption key, including the release key that is used to
sign the APK for publishing.
You can define the keys for the debug and release targets in src/debug/ and src/release/.
-->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="My Key is Here" />
<activity
android:name=".MapsActivity"
android:label="#string/title_activity_maps">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Alas! after a lots of efforts and search I couldn't find my problem. I want to find current location in google map but I am still getting an error(required permissions).
call requires permission which may be rejected by user: code should
explicitly check to see if permission is available (with check
permission) or explicitly handle a potential 'security Exception'
at gMap.setMyLocationEnable(true); Please anybody guide me how can I fix it? My code is given below.
AddMasjid.java
package com.example.saroosh.masjidnow.Tabs;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.saroosh.masjidnow.R;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class AddMasjid extends Fragment implements OnMapReadyCallback{
MapView gMapView;
GoogleMap gMap = null;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v =inflater.inflate(R.layout.add_masjid,container,false);
gMapView = (MapView) v.findViewById(R.id.map);
gMapView.getMapAsync(this);
gMapView.onCreate(savedInstanceState);
gMapView.onResume(); // needed to get the map to display immediately
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
return v;
}
#Override
public void onMapReady(GoogleMap map) {
gMap = map;
gMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
gMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new
LatLng(0, 0), 0));
if (gMap != null) {
gMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
gMap.setMyLocationEnabled();
}
}
#Override
public void onResume() {
super.onResume();
gMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
gMapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
gMapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
gMapView.onLowMemory();
}
}
add_masjid.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#000000">
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/editText1"
android:layout_alignBottom="#+id/editText1"
android:layout_alignParentStart="true"
android:text="#string/xyz"
android:textColor="#FFFFFF"
android:textSize="20sp"
/>
<Button
android:id="#+id/generalId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:background="#drawable/rect1"
android:onClick="geoLocate"
android:text="#string/abc"
android:textColor="#FFFFFF"
android:textSize="20sp" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toEndOf="#+id/textView1"
android:layout_toStartOf="#+id/generalId"
android:ems="10"
android:inputType="text"
android:background="#FFFFFF"
android:labelFor="#+id/editText1"
android:layout_above="#+id/map"
android:layout_alignParentTop="true" />
<com.google.android.gms.maps.MapView
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/generalId">
</com.google.android.gms.maps.MapView>
</RelativeLayout>
I have just solved my problem by adding some permissions in it.
#Override
public void onMapReady(GoogleMap map) {
gMap = map;
gMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
gMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new
LatLng(0, 0), 0));
//add this code...
if (gMap != null) {
gMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
if (ActivityCompat.checkSelfPermission(getActivity().getApplicationContext()
, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity().getApplicationContext()
, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
gMap.setMyLocationEnabled(true);
gMap.getUiSettings().setMyLocationButtonEnabled(true);
}
}
I don't see any thing on google map,lines type some is shown,
my first map view project is running successfully where only map is show and here when i add some more code as the tutorial goes on it is not working ..
here is the
public class MainActivity extends FragmentActivity {
private static final int GPS_ERRORDIALOG_REQUEST = 9001;
GoogleMap mMap;
#SuppressWarnings("unused")
private static final double SEATTLE_LAT = 47.60621,
SEATTLE_LNG = -122.33207, SYDNEY_LAT = -33.867487,
SYDNEY_LNG = 151.20699, NEWYORK_LAT = 40.714353,
NEWYORK_LNG = -74.005973;
private static final float DEFAULTZOOM = 5;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (servicesOK()) {
setContentView(R.layout.activity_main);
if (initMap()) {
Toast.makeText(this, "Ready to map !", Toast.LENGTH_LONG)
.show();
gotoLocation(SEATTLE_LAT, SEATTLE_LNG, DEFAULTZOOM);
} else {
Toast.makeText(this, "Ready to map !", Toast.LENGTH_LONG)
.show();
}
} else {
setContentView(R.layout.activity_map_xml_control);
}
}
private void gotoLocation(double lat, double lng,
float zoom) {
LatLng ll = new LatLng(lat, lng);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(ll, zoom);
mMap.moveCamera(update);
}
public boolean servicesOK() {
int isAvailable = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(this);
if (isAvailable == ConnectionResult.SUCCESS) {
return true;
} else if (GooglePlayServicesUtil.isUserRecoverableError(isAvailable)) {
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(isAvailable,
this, GPS_ERRORDIALOG_REQUEST);
dialog.show();
} else {
Toast.makeText(this, "Can't connect to Google play servieces",
Toast.LENGTH_LONG).show();
}
return false;
}
private boolean initMap() {
if (mMap == null) {
// setContentView(R.layout.activity_main);
SupportMapFragment mapFrag = (SupportMapFragment)
getSupportFragmentManager()
.findFragmentById(R.id.map1);
// gotoLocation(SEATTLE_LAT, SEATTLE_LNG);
mMap = mapFrag.getMap();
}
return (mMap != null);
}
private void gotoLocation(double lat, double lag) {
LatLng ll = new LatLng(lat, lag);
CameraUpdate update = CameraUpdateFactory.newLatLng(ll);
mMap.moveCamera(update);
}
}
manifest file
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission a
ndroid:name="com.google.android.gms.permission.ACTIVITY_RECOGNITION" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="my keyy" />
</application>
Have you retrieved a gray map on your phone? If so, your API_KEY for your map did not set correctly.
Please try to follow this step by step, you will finally get a map on your phone.
For MainAcitivity, sample code:
public class MainActivity extends Activity {
private static LatLng goodLatLng = new LatLng(37, -120);
private GoogleMap googleMap;
private EditText et_address, et_finalAddress;
LatLng addressPos, finalAddressPos;
Marker addressMarker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_address = (EditText) findViewById(R.id.addressEditText);
et_finalAddress = (EditText) findViewById(R.id.finalAddressEditText);
// Initial Map
try {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
}
} catch (Exception e) {
e.printStackTrace();
}
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
// Put a dot on my current location
googleMap.setMyLocationEnabled(true);
googleMap.setIndoorEnabled(true);
googleMap.setTrafficEnabled(true);
// 3D building
googleMap.setBuildingsEnabled(true);
// Get zoom button
googleMap.getUiSettings().setZoomControlsEnabled(true);
Marker marker = googleMap.addMarker(new MarkerOptions()
.position(goodLatLng)
.title("Hello"));
}
For more details, please refer to my github here.
I wish to redirect all errors of type Exception to the result "error". For that, I did this :
<global-exception-mappings>
<exception-mapping result="error" exception="java.lang.Exception"></exception-mapping>
</global-exception-mappings>
But I don't want to handle a particular exception, specifically the org.springframework.security.access.AccessDeniedException which should be allowed to propagate further. How can I achieve that ?
Use instanceof operator and rethrow desired exception from exception handler.
I managed it with an interceptor (here is what I used to try it out):
package com.kenmcwilliams.interceptor;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Rethrower implements Interceptor{
#Override
public void destroy() {
}
#Override
public void init() {
}
#Override
public String intercept(ActionInvocation invocation){
System.out.println("Start rethrower!");
String result = "success";
try {
result = invocation.invoke();
} catch (Exception ex) {
Logger.getLogger(Rethrower.class.getName()).log(Level.SEVERE, null, ex);
}
Object exception = ActionContext.getContext().getValueStack().findValue("exception");
if (exception instanceof RuntimeException){
System.out.println("DOING RETHROW!");
RuntimeException e = (RuntimeException)exception;
throw e;
}
System.out.println("After rethrower!");
return result;
}
}
Here is the struts.xml (to save time looking up struts dtd):
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<constant name="struts.devMode" value="true" />
<constant name="struts.ui.theme" value="simple" />
<package name="kenmcwilliams" namespace="/" extends="struts-default">
<interceptors>
<interceptor name="rethrower" class="com.kenmcwilliams.interceptor.Rethrower"/>
<interceptor-stack name="rethrow-stack">
<interceptor-ref name="rethrower"/>
<interceptor-ref name="defaultStack"/>
</interceptor-stack>
</interceptors>
<global-results>
<result name="error" >/WEB-INF/content/error.jsp</result>
</global-results>
<global-exception-mappings>
<exception-mapping exception="java.lang.Exception" result="error"/>
</global-exception-mappings>
<action name="mybomb" class="com.kenmcwilliams.kensocketchat.action.Bomb">
<interceptor-ref name="rethrow-stack"/>
<result>/WEB-INF/content/bomb.jsp</result>
</action>
</package>
</struts>
Finally the action (it just throws a runtime exception):
package com.kenmcwilliams.kensocketchat.action;
import com.opensymphony.xwork2.ActionSupport;
public class Bomb extends ActionSupport{
#Override
public String execute() throws Exception{
throw new RuntimeException();
}
}