I want to get route between two locations,for that i have found esri sample service i.e :http://route.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World.
But if i use this service i am getting error as Unauthorized access to a secure.
I am unable to use this service,Please tell me if any free service for getting route on arcgis map
Thanks.
my code:
public void getRouteFromSource(Geometry current_location,Geometry destination_point,boolean isCurrentLocation){
routeLayer = new GraphicsLayer();
mMapView.addLayer(routeLayer);
// Initialize the RouteTask
try {
String routeTaskURL = "http://route.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World";
mRouteTask = RouteTask.createOnlineRouteTask(routeTaskURL, null);
} catch (Exception e1) {
e1.printStackTrace();
}
// Add the hidden segments layer (for highlighting route segments)
hiddenSegmentsLayer = new GraphicsLayer();
mMapView.addLayer(hiddenSegmentsLayer);
QueryDirections(current_location, destination_point,isCurrentLocation);
}
private void QueryDirections(final Geometry sourceGeometry, final Geometry destinationGeometry,boolean isCurrentLocation) {
// Show that the route is calculating
if(isCurrentLocation==false){
dialog = ProgressDialog.show(mContext, PollingStationLocatorContant.plase_wait,
"Calculating route...", true);
}
// Log.e("mLocation", "mLocation "+sourceGeometry);
// Log.e("POINTTT", "POINTTT"+p);
// Spawn the request off in a new thread to keep UI responsive
Thread t = new Thread() {
private RouteResult mResults;
#Override
public void run() {
try {
// Start building up routing parameters
/*Point startPoint = new Point(78.4867, 17.3850);
Point stopPoint = new Point(79.5941, 17.9689);*/
// Log.e("mLocation.getX()",""+ p.getX()+"---"+ p.getY());
// Log.e("mLocation.getY()",""+ mLocation.getX() +"----"+ mLocation.getY());
//Point startPoint = new Point(mLocation.getX(), mLocation.getY());
//Point stopPoint = new Point(p.getX(), p.getY());
StopGraphic point1 = new StopGraphic(sourceGeometry);
StopGraphic point2 = new StopGraphic(destinationGeometry);
Log.e("point1", ""+point1);
Log.e("point2", ""+point2);
NAFeaturesAsFeature rfaf = new NAFeaturesAsFeature();
// Convert point to EGS (decimal degrees)
// Create the stop points (start at our location, go
// to pressed location)
rfaf.setFeatures(new Graphic[] { point1, point2 });
rfaf.setCompressedRequest(true);
// RouteParameters r = new RouteParameters();
RouteParameters rp = mRouteTask.retrieveDefaultRouteTaskParameters();
//rp.setImpedanceAttributeName("Length");
rp.setReturnDirections(false);
// Assign the first cost attribute as the impedance
rp.setStops(rfaf);
// Set the routing service output SR to our map
// service's SR
rp.setOutSpatialReference(mMapView.getSpatialReference());
//rp.setImpedanceAttributeName("");
// Solve the route and use the results to update UI
// when received
mResults = mRouteTask.solve(rp);
List<Route> routes = mResults.getRoutes();
Route mRoute = routes.get(0);
Geometry routeGeom = mRoute.getRouteGraphic().getGeometry();
Graphic symbolGraphic = new Graphic(routeGeom, new SimpleLineSymbol(Color.BLUE,5));
//SimpleMarkerSymbol sls = new SimpleMarkerSymbol(Color.RED, 10,STYLE.CIRCLE);
PictureMarkerSymbol pls=new PictureMarkerSymbol(mContext.getResources().getDrawable(R.drawable.animation_image));
mMapView.setExtent(routeGeom, 20);
Graphic destinatonGraphic = new Graphic(sourceGeometry, pls);
mGraphicsLayer.addGraphic(symbolGraphic);
mDestinationGraphicLayer.addGraphic(destinatonGraphic);
mMapView.addLayer(mGraphicsLayer);
mMapView.addLayer(mDestinationGraphicLayer);
mHandler.post(mUpdateResults);
} catch (Exception e) {
mDestinationGraphicLayer.removeAll();
noRouteFound=true;
e.printStackTrace();
mHandler.post(mUpdateResults);
}
}
};
// Start the operation
t.start();
}
void updateUI() {
if(dialog!=null && dialog.isShowing()){
dialog.dismiss();
if(noRouteFound){
Toast.makeText(mContext, "Unable to find route.Please select with in State", Toast.LENGTH_LONG).show();
}
}
}
Disregarding geocoding services (which may be called for free if data is not stored) routing services do require a token.
As stated in the documentation:
Required parameters: token
Use this parameter to specify a token that provides the identity of a
user that has the permissions to access the service. Accessing
services provided by Esri provides more information on how such an
access token can be obtained.
What you can do is to go here and register a free developer account. You will receive a free token and its related amount of free credits that you can use to query the routing API.
However, the documentation linked above shows samples of response for all possible situations (error, route ok, route not found).
After creating a free developer account follow these steps.
Inside your getRouteFromSource function replace the existing code with this.
TOKEN = "The token you receive after you sign up";
CLIENT_ID = "The client_id you receive after you sign up";
try {
UserCredentials authenticate= new UserCredentials();
authenticate.setUserAccount("your username", "your password");
authenticate.setUserToken(TOKEN, CLIENT_ID);
mRouteTask = RouteTask
.createOnlineRouteTask(
"http://route.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World",
authenticate);
} catch (Exception e1) {
e1.printStackTrace();
}
This should solve your problem.
Related
I've been trying very hard to create a route between two points(startPoint, endPoint). But i am getting the following error:
Location "Location 1" in "Stops" is unlocated. Location "Location 2" in "Stops" is unlocated. Need at least 2 valid stops. "Stops" does not contain valid input for any route.
I've posted this question on gis.stackexchange.com and geonet.esri.com and didn't get a reply except one which was not helpful.
My Code:
private final String routeTaskURL = "http://sampleserver3.arcgisonline.com/ArcGIS/rest/services/Network/USA/NAServer/Route";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMapView = (MapView) findViewById(R.id.map);
mMapView.enableWrapAround(true);
new Thread(new Runnable() {
#Override
public void run() {
try {
UserCredentials userCredentials = new UserCredentials();
userCredentials.setUserToken(token, clientID);
RouteTask routeTask = RouteTask.createOnlineRouteTask(routeTaskURL, userCredentials);
RouteParameters routeParameters = routeTask.retrieveDefaultRouteTaskParameters();
NAFeaturesAsFeature naFeatures = new NAFeaturesAsFeature();
Point startPoint = new Point(36.793653, -119.866896);
Point stopPoint = new Point(36.795488, -119.853345);
StopGraphic startPnt = new StopGraphic(startPoint);
StopGraphic stopPnt = new StopGraphic(stopPoint);
naFeatures.setFeatures(new Graphic[] {startPnt, stopPnt});
routeParameters.setStops(naFeatures);
RouteResult mResults = routeTask.solve(routeParameters);
List<Route> routes = mResults.getRoutes();
System.out.println(mResults.getRoutes());
Route mRoute = routes.get(0);
Geometry geometry = mRoute.getRouteGraphic().getGeometry();
Graphic symbolGraphic = new Graphic(geometry, new SimpleLineSymbol(Color.BLUE, 3));
mGraphicsLayer.addGraphic(symbolGraphic);
System.out.println(mResults.getStops());
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
I've searched the internet. Many developers were/are facing this problem. I've tried all the solutions but none of them worked. I got routeTaskURL from the ArcGIS Routing Sample app. The link which is given in the documentation of ArcGIS maps gives me the 403 error if i open it in the browser.
Note: "token" and "clientID" is declared in the first step and they both are taken from the ArcGIS developers console where i registered my application.
Any Suggestions?
Your X and Y values are switched. Change to this:
Point startPoint = new Point(-119.866896, 36.793653);
Point stopPoint = new Point(-119.853345, 36.795488);
See the Point class documentation to learn that the constructor parameters are (x, y), not (y, x). The route service you're using has a default spatial reference of 4326, which is unprojected longitude and latitude. -119.866896 and -119.853345 are not valid latitude (y) values, but they are valid longitude (x) values.
So in my app I am making use of google map apis and I'm using Geocoding to determine the Address based on the user's current location. I was using the Geocoder Android Class but I've found that it truly works terribly. It's just not reliable. So I used a post I saw here at SO to create my own Geocoder. Problem is, I now don't know if I'm using server side or client side geocoding. This is kind of important because one has a limit and the other really doesn't. All of my code is in Android though.
Here's some code, this is within my "MyGeocoder" Class:
public List<Address> getFromLocation(double latitude, double longitude,
int maxResults) throws IOException, LimitExceededException {
if (latitude < -90.0 || latitude > 90.0) {
throw new IllegalArgumentException("latitude == " + latitude);
}
if (longitude < -180.0 || longitude > 180.0) {
throw new IllegalArgumentException("longitude == " + longitude);
}
if (isLimitExceeded(context)) {
throw new LimitExceededException();
}
final List<Address> results = new ArrayList<Address>();
final StringBuilder url = new StringBuilder(
"http://maps.googleapis.com/maps/api/geocode/json?sensor=true&latlng=");
url.append(latitude);
url.append(',');
url.append(longitude);
url.append("&language=");
url.append(Locale.getDefault().getLanguage());
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url.toString());
try {
HttpResponse response = httpclient.execute(httppost);
String jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
Gson gson = new Gson();
MyGeocodeResponse geocodeResponse = gson.fromJson(jsonResult, MyGeocodeResponse.class);
final Address current = new Address(Locale.getDefault());
if(geocodeResponse.getStatus().equals(STATUS_OK)) {
MyGeocode locGeocode= geocodeResponse.getResults().get(0);
String streetAddress = "";
for(MyAddressComponent component : locGeocode.getAddress_components()) {
for(String type : component.getTypes()) {
if(type.equals("locality")) {
current.setLocality(component.getLong_name());
}
if(type.equals("administrative_area_level_1")) {
current.setAdminArea(component.getLong_name());
}
if(type.equals("street_number")) {
if(streetAddress.length() != 0) {
current.setAddressLine(0, component.getLong_name() + " " + streetAddress);
} else {
streetAddress = component.getLong_name();
}
}
if(type.equals("route")) {
if(streetAddress.length() != 0) {
current.setAddressLine(0, streetAddress + " " + component.getShort_name());
} else {
streetAddress = component.getShort_name();
}
}
}
}
current.setLatitude(latitude);
current.setLongitude(longitude);
results.add(current);
}
Log.i("TEST", "Got it");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return results;
}
Edit:
And I guess a further questions is, if this is server-side Geocoding, then can this code only be run 2,500 times per day period, or can it be run 2,500 times daily per user of the app? If it's the first option I'm still ok, but if it's the 2nd option I don't see how any app that wants to have a half-way big user base can use server-side geocoding without hitting that limit.
I now don't know if I'm using server side or client side geocoding
after looking to your code you wrote http://maps.googleapis.com/maps/api/geocode/json?sensor=true&latlng=,so it is server side reverse geocoding as you are calling geocoding api by making an extra External http call.
if this is server-side Geocoding, then can this code only be run 2,500 times per day period, or can it be run 2,500 times daily per user of the app?
2,500 request limit is per IP address(basically it is mentioning 2500 request per day),yah this code only be run 2,500 times per day for all of your user.One thing you should keep in mind you are making http call to geocoder api so it doesn't matter from where you are making this call from server or from client.
you should have a look on this google link where they have mention "When to Use Client-Side Geocoding" and "When to Use Server-Side Geocoding".
I am following a tutorial here https://code.google.com/p/osmbonuspack/wiki/Tutorial_1 but I have encountered an error that it doesn't show the correct route correctly. It just shows a straight line from Point A to Point B.
What I want to achieve is to show the correct route from these points. I'm guessing the error is that it doesn't recognize any nodes to go through.
A similar question has been also asked and I am assuming I have the same problem if I haven't explained my question well.
Similar question can be found here: OSMDroid Routing problems when following a tutorial
Here is a part of my code using RoadManager
Here is a part of the code.
try {
//get current longlat
gpsLocator.getLocation();
cur_loc_lat =gpsLocator.getLatitude();
cur_loc_long =gpsLocator.getLongitude();
} catch (Exception e) {
// TODO: handle exception
}
//--- Create Another Overlay for multi marker
anotherOverlayItemArray = new ArrayList<OverlayItem>();
anotherOverlayItemArray.add(new OverlayItem(
"UST", "UST", new GeoPoint( testlat, testlong)));
//--- Create Another Overlay for multi marker
anotherOverlayItemArray.add(new OverlayItem(
locDefine[0], "UST", new GeoPoint( sel_latitude, sel_longitude)));
ItemizedIconOverlay<OverlayItem> anotherItemizedIconOverlay
= new ItemizedIconOverlay<OverlayItem>(
TomWalks.this, anotherOverlayItemArray, myOnItemGestureListener);
myOpenMapView.getOverlays().add(anotherItemizedIconOverlay);
//---
//Add Scale Bar
ScaleBarOverlay myScaleBarOverlay = new ScaleBarOverlay(TomWalks.this);
myOpenMapView.getOverlays().add(myScaleBarOverlay);
try {
//1 Routing via road manager
RoadManager roadManager = new MapQuestRoadManager();
roadManager.addRequestOption("routeType=pedestrian");
/*
roadManager.addRequestOption("units=m");
roadManager.addRequestOption("narrativeType=text");
roadManager.addRequestOption("shapeFormat=raw");
roadManager.addRequestOption("direction=0");
*/
//Then, retrieve the road between your start and end point:
ArrayList<GeoPoint> waypoints = new ArrayList<GeoPoint>();
waypoints.add(new GeoPoint(testlat, testlong));
waypoints.add(new GeoPoint(sel_latitude,sel_longitude)); //end point
Road road = roadManager.getRoad(waypoints);
// then, build an overlay with the route shape:
PathOverlay roadOverlay = RoadManager.buildRoadOverlay(road, myOpenMapView.getContext());
roadOverlay.setColor(Color.GREEN);
//Add Route Overlays into map
myOpenMapView.getOverlays().add(roadOverlay);
myOpenMapView.invalidate();//refesh map
final ArrayList<ExtendedOverlayItem> roadItems =
new ArrayList<ExtendedOverlayItem>();
ItemizedOverlayWithBubble<ExtendedOverlayItem> roadNodes =
new ItemizedOverlayWithBubble<ExtendedOverlayItem>(TomWalks.this, roadItems, myOpenMapView);
myOpenMapView.getOverlays().add(roadNodes);
myOpenMapView.invalidate();//refesh map
int nodesize=road.mNodes.size();
double length = road.mLength;
Drawable marker = getResources().getDrawable(R.drawable.marker_node);
Toast.makeText(TomWalks.this, " Distance : " + length + " Nodes : "+nodesize ,Toast.LENGTH_SHORT).show();
for (int i=0; i<road.mNodes.size(); i++)
{
RoadNode node = road.mNodes.get(i);
ExtendedOverlayItem nodeMarker = new ExtendedOverlayItem("Step "+i, "", node.mLocation, TomWalks.this);
nodeMarker.setMarkerHotspot(OverlayItem.HotspotPlace.CENTER);
nodeMarker.setMarker(marker);
roadNodes.addItem(nodeMarker);
nodeMarker.setDescription(node.mInstructions);
nodeMarker.setSubDescription(road.getLengthDurationText(node.mLength, node.mDuration));
Drawable icon = getResources().getDrawable(R.drawable.marker_node);
nodeMarker.setImage(icon);
}//end for
myOpenMapView.getOverlays().add(roadNodes);
myOpenMapView.invalidate();//refesh map
} catch (Exception e) {
// TODO: handle exception
Toast.makeText(TomWalks.this,e.getMessage(),Toast.LENGTH_SHORT).show();
}
myMapController.setCenter(new GeoPoint( sel_latitude, sel_longitude));
} catch (Exception e) {
// TODO: handle exception
}
}
}
}//===================================================================================================
Let's try to provide a complete answer to this quite frequent question.
Basically, when you get the "straight line", it means that the RoadManager got an error.
So, first of all, in your code, you should check the result of getRoad, this way:
if (road.mStatus != Road.STATUS_OK){
//handle error... warn the user, etc.
}
Now, where this error is coming from?
=> You must search in the logcat. You should find the full url that has been sent, and probably a stacktrace about the error.
I strongly recommend that you copy/paste this full url in a browser , and check the result.
Here are the typical errors, by decreasing probability:
1) You didnt' read carefully the "Important note" at the beginning of the Tutorial_0, and you are trying to do a Network call in the main thread, with an SDK >= 3.0.
=> Read this "Important note".
2) You asked for a route that is not possible (really not possible, or because of weird positions, or because of setting unsupported options).
=> This is easy to check by copy/pasting the full url in a web browser, and looking at the answer.
3) Your device has no network connectivity.
4) The routing service changed its API (this happened, more than once...).
=> Could be checked by copy/pasting the full url in a browser.
In this case, raise an Issue in OSMBonusPack project, so that we can take it into account ASAP.
5) The routing service is down.
=> Easy to check by copy/pasting the full url in a browser.
I think it is better to use AsyncTasks in this case:
/**
* Async task to get the road in a separate thread.
*/
private class UpdateRoadTask extends AsyncTask<Object, Void, Road> {
protected Road doInBackground(Object... params) {
#SuppressWarnings("unchecked")
ArrayList<GeoPoint> waypoints = (ArrayList<GeoPoint>)params[0];
RoadManager roadManager = new OSRMRoadManager();
return roadManager.getRoad(waypoints);
}
#Override
protected void onPostExecute(Road result) {
road = result;
// showing distance and duration of the road
Toast.makeText(getActivity(), "distance="+road.mLength, Toast.LENGTH_LONG).show();
Toast.makeText(getActivity(), "durée="+road.mDuration, Toast.LENGTH_LONG).show();
if(road.mStatus != Road.STATUS_OK)
Toast.makeText(getActivity(), "Error when loading the road - status="+road.mStatus, Toast.LENGTH_SHORT).show();
Polyline roadOverlay = RoadManager.buildRoadOverlay(road,getActivity());
map.getOverlays().add(roadOverlay);
map.invalidate();
//updateUIWithRoad(result);
}
}
then call it new UpdateRoadTask().execute(waypoints);
new Thread(new Runnable()
{
public void run()
{
RoadManager roadManager = new OSRMRoadManager();
ArrayList<GeoPoint> waypoints = new ArrayList<GeoPoint>();
GeoPoint startPoint = new GeoPoint(source_lat, source_longi);
waypoints.add(startPoint);
GeoPoint endPoint = new GeoPoint(desti_lat,desti_longi);
waypoints.add(endPoint);
try
{
road = roadManager.getRoad(waypoints);
}
catch (Exception e)
{
e.printStackTrace();
}
runOnUiThread(new Runnable()
{
public void run()
{
if (road.mStatus != Road.STATUS_OK)
{
//handle error... warn the user, etc.
}
Polyline roadOverlay = RoadManager.buildRoadOverlay(road, Color.RED, 8, context);
map.getOverlays().add(roadOverlay);
}
});
}
}).start();
And i am use two jar files 1)slf4j-android-1.5.8.jar and 2)osmdroid-android-4.2.jar and osmbonuspack library.
A strange error I found regarding this is as follows:
Firstly I mention following line of code for taking directions for the vehicle "BIKE"
((OSRMRoadManager) roadManager).setMean(OSRMRoadManager.MEAN_BY_BIKE);
Now when it was first called it follows the following URL:
https://routing.openstreetmap.de/routed-car/route/v1/driving/68.8889678000,23.2151582000;73.1808008000,22.3110728000?alternatives=false&overview=full&steps=true
Now when calling the second time{same MEAN_BY_BIKE}, it is following this URL:
:https://routing.openstreetmap.de/routed-bike/route/v1/driving/68.8889678000,23.2151582000;73.1808008000,22.3110728000?alternatives=false&overview=full&steps=true
So the issue is that no response is for the "routed-bike" and it is calling automatically itself when called for second time.
So as a solution I changed my code to the following:
((OSRMRoadManager) roadManager).setMean(OSRMRoadManager.MEAN_BY_CAR);
You can check your LogCat for the same.
I'm trying to create a spreadsheet via my android app. So far I've been only successful in creating an empty text document. Google's Spreadsheet API instructs me to follow Google Documents List API in order to create a spreadsheet document in Google Drive. In Google Documents List API it says:
To create a new, empty spreadsheet, follow the instructions in
Creating a new document or file with metadata only. When doing so, use
a category term of http://schemas.google.com/docs/2007#spreadsheet.
In the link above I've found the next .NET code:
using System;
using Google.GData.Client;
using Google.GData.Documents;
namespace MyDocumentsListIntegration
{
class Program
{
static void Main(string[] args)
{
DocumentsService service = new DocumentsService("MyDocumentsListIntegration-v1");
// TODO: Authorize the service object for a specific user (see Authorizing requests)
// Instantiate a DocumentEntry object to be inserted.
DocumentEntry entry = new DocumentEntry();
// Set the document title
entry.Title.Text = "Legal Contract";
// Add the document category
entry.Categories.Add(DocumentEntry.DOCUMENT_CATEGORY);
// Make a request to the API and create the document.
DocumentEntry newEntry = service.Insert(
DocumentsListQuery.documentsBaseUri, entry);
}
}
}
I've used this code to try and create a spreadsheet, but only the third variant worked (using DocsService, without adding Category and using feedUrl URL object).
Here's part of my working code (upload() is being called when user clicks a button):
private void upload() {
SpreadSheetAsyncTask sprdSheetAsyncTsk = new SpreadSheetAsyncTask();
sprdSheetAsyncTsk.execute();
}
public class SpreadSheetAsyncTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
spreadSheetService = new SpreadsheetService("Salary_Calculator");
docService = new DocsService("Salary_Calculator");
try {
spreadSheetService.setUserCredentials(USERNAME, PASSWORD);
docService.setUserCredentials(USERNAME, PASSWORD);
URL feedUrl = new URL(
"https://docs.google.com/feeds/default/private/full/");
URL tmpFeedUrl = new URL(
"https://spreadsheets.google.com/feeds/worksheets/key/private/full");
DocumentEntry entry = new DocumentEntry();
Calendar timeRightNow = GregorianCalendar.getInstance();
entry.setTitle(new PlainTextConstruct(
"Salary Calculator Spreadsheet "
+ timeRightNow.get(Calendar.DAY_OF_MONTH) + "/"
+ (timeRightNow.get(Calendar.MONTH) + 1) + "/"
+ timeRightNow.get(Calendar.YEAR)));
// Category object = new Category("spreadsheet",
// "http://schemas.google.com/docs/2007#spreadsheet");
//
//
// entry.getCategories().add(object);
/*
* TODO TEST AREA
*/
entry = docService.insert(feedUrl, entry);
/*
* TODO TEST AREA
*/
} catch (AuthenticationException e) {
cancel(true);
loginDialog("Wrong username or password");
} catch (IOException e) {
e.printStackTrace();
return null;
} catch (ServiceException e) {
cancel(true);
loginDialog("Wrong username or password");
} catch (Exception e) {
loginDialog("Wrong username or password");
}
return null;
}
}
The non working code uses the category object object (as shown in the code comment) above and uses entry = spreadSheetService.insert(feedUrl, entry);
My question is - what did they want me to do when they wrote use a category term of http://schemas.google.com/docs/2007#spreadsheet?
I am creating testing purpose paypal app. i have created testing paypal account and wrote the bellow given code in my activity on my button click. but nothing is display and getting exception :
09-26 13:52:51.908: E/NetworkHandler(540): postXML caught exception doing I/O, mobileclient.sandbox.paypal.com
Code:
float ammount = Float.parseFloat(_details.get(_G_no)
.get_product_price());
PayPalPayment newPayment = new PayPalPayment();
newPayment.setSubtotal(BigDecimal.valueOf(ammount));
newPayment.setCurrencyType("USD");
newPayment.setRecipient("account#gmail.com");
newPayment.setMerchantName("Merchant");
PayPal pp = PayPal.getInstance();
if(pp==null)
pp = PayPal.initWithAppID(this, id, PayPal.ENV_SANDBOX);
final Intent paypalIntent = pp.checkout(newPayment, this);
this.startActivityForResult(paypalIntent, 1);
Internet permission is there in my app. please help me.
I dont know , that this is correct or not . but i found the solution by creating internet connection before your code , thainks to Vikalp patel for identifying Have you found the solution of NetworkHandler Error .
public void PayPalButtonClick_ ( View v )
{
class asynctaskToInitLibrary extends AsyncTask<String, Integer, String >
{
#Override
protected String doInBackground(String... params)
{
URL actualUrl = null;
try
{
actualUrl = new URL("http://www.google.com") ;
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
try
{
HttpURLConnection cn = (HttpURLConnection)actualUrl.openConnection();
Log.i(cn.getResponseMessage(),"tushar:connectionResponse") ;
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
PayPal pp = PayPal.getInstance();
// If the library is already initialized, then we don't need to initialize it again.
if(pp == null)
{
// This is the main initialization call that takes in your Context, the Application ID, and the server you would like to connect to.
pp = PayPal.initWithAppID(Paypal_MPL.this, "APP-80W284485P519543T", PayPal.ENV_SANDBOX );
// -- These are required settings.
pp.setLanguage("en_US"); // Sets the language for the library.
// --
// -- These are a few of the optional settings.
// Sets the fees payer. If there are fees for the transaction, this person will pay for them. Possible values are FEEPAYER_SENDER,
// FEEPAYER_PRIMARYRECEIVER, FEEPAYER_EACHRECEIVER, and FEEPAYER_SECONDARYONLY.
pp.setFeesPayer(PayPal.FEEPAYER_EACHRECEIVER);
// Set to true if the transaction will require shipping.
pp.setShippingEnabled(true);
// Dynamic Amount Calculation allows you to set tax and shipping amounts based on the user's shipping address. Shipping must be
// enabled for Dynamic Amount Calculation. This also requires you to create a class that implements PaymentAdjuster and Serializable.
pp.setDynamicAmountCalculationEnabled(false);
// --
}
if (pp.isLibraryInitialized())
{
return "initialized" ;
}
else
{
return "not-initialized" ;
}
}
protected void onPostExecute(String result)
{
initializationStatus ( result ) ;
}
}
asynctaskToInitLibrary object = new asynctaskToInitLibrary() ;
object.execute("") ;
}
I have updated from MPL library (that is being deprecated) to new PayPal Android SDK. I have solved this error.