Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
119 views
in Technique[技术] by (71.8m points)

I m trying to develop an android app to get the location using googleapi. but it is showing error like could not get the connection factory client

 MainActivity.java

 package com.example.checkgps;
 import com.google.android.maps.MapActivity;
  import com.google.android.maps.MapView;

   import android.os.Bundle;

   public class MainActivity extends MapActivity {
       @Override
       public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
       MapView view=(MapView) findViewById(R.id.themap);
       view.setBuiltInZoomControls(true);
   }

    @Override
    protected boolean isRouteDisplayed() {
        // TODO Auto-generated method stub
        return false;
    }    

}


 manifest file


 <?xml version="1.0" encoding="utf-8"?>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.checkgps"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="14" />

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

   <application
     android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
     <uses-library android:name="com.google.android.maps"/>
    <activity
        android:name="com.example.checkgps.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>
 </application>

</manifest>

 xml file

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

 <com.google.android.maps.MapView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/themap"
android:clickable="true"
android:apiKey="AIzaSyARFKGTbhWqCIpc_b64w6AEYA4saHg9wVk"
/>

</RelativeLayout>

Logcat file

11-28 15:45:30.473: E/AndroidRuntime(30197): FATAL EXCEPTION: main
 11-28 15:45:30.473: E/AndroidRuntime(30197): java.lang.RuntimeException: Unable to      start activity   ComponentInfo{com.example.gpstracking/com.example.gpstracking.AndroidGPSTrackingActivity}: java.lang.NullPointerException
 11-28 15:45:30.473: E/AndroidRuntime(30197):   at  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1728)
 11-28 15:45:30.473: E/AndroidRuntime(30197):   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1747)
  11-28 15:45:30.473: E/AndroidRuntime(30197):  at android.app.ActivityThread.access$1500(ActivityThread.java:155)
  11-28 15:45:30.473: E/AndroidRuntime(30197):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:993)
  11-28 15:45:30.473: E/AndroidRuntime(30197):  at android.os.Handler.dispatchMessage(Handler.java:130)
  11-28 15:45:30.473: E/AndroidRuntime(30197):  at android.os.Looper.loop(SourceFile:351)
  11-28 15:45:30.473: E/AndroidRuntime(30197):  at android.app.ActivityThread.main(ActivityThread.java:3814)
  11-28 15:45:30.473: E/AndroidRuntime(30197):  at java.lang.reflect.Method.invokeNative(Native Method)
  11-28 15:45:30.473: E/AndroidRuntime(30197):  at java.lang.reflect.Method.invoke(Method.java:538)
  11-28 15:45:30.473: E/AndroidRuntime(30197):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
  11-28 15:45:30.473: E/AndroidRuntime(30197):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:659)
   11-28 15:45:30.473: E/AndroidRuntime(30197):     at dalvik.system.NativeStart.main(Native Method)
   11-28 15:45:30.473: E/AndroidRuntime(30197): Caused by: java.lang.NullPointerException
   11-28 15:45:30.473: E/AndroidRuntime(30197):     at com.example.gpstracking.AndroidGPSTrackingActivity.onCreate(AndroidGPSTrackingActivity.java:78)
   11-28 15:45:30.473: E/AndroidRuntime(30197):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1082)
   11-28 15:45:30.473: E/AndroidRuntime(30197):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1692)
    11-28 15:45:30.473: E/AndroidRuntime(30197):    ... 11 more

I m trying to develop an android application to get the location using google API.I have also registerd @ google and get V2 license but it is showing error like could not get the connection factory client..resole it ASAp....

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use my code to get the location. Turn your gps and wifi on before :-

Use my Code. I have successfully found my current address using coordinates but for that you have to enable wifi and gps. first add all these permissions in your android manifest file

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

AndroidGPSTrackingActivity.java*

package com.example.gpstracking;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Toast;
import android.widget.ToggleButton;

public class AndroidGPSTrackingActivity extends Activity {

    Button btnShowLocation;

    // GPSTracker class
    GPSTracker gps;
    ToggleButton gpstoggle,wifitoggle;
    static WifiManager wifiManager;
    LocationManager lm;
    WebView web;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        btnShowLocation = (Button) findViewById(R.id.btnShowLocation);

        gpstoggle = (ToggleButton) findViewById(R.id.gps);
        wifitoggle = (ToggleButton) findViewById(R.id.wifi);

        wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE); 

        lm = (LocationManager) getSystemService(LOCATION_SERVICE);

        //gps toggle
        gpstoggle.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    final Intent poke = new Intent();
                    poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider"); 
                    poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
                    poke.setData(Uri.parse("3")); 
                    getApplicationContext().sendBroadcast(poke);
                }
                else{
                    final Intent poke = new Intent();
                    poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider"); 
                    poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
                    poke.setData(Uri.parse("3")); 
                    getApplicationContext().sendBroadcast(poke);
                }
            }
        });
        //wifi toggle
        wifitoggle.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    wifiManager.setWifiEnabled(true);
                }
                else{
                    wifiManager.setWifiEnabled(false);
                }
            }
        });


        // show location button click event
        btnShowLocation.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {        
                // create class object
                gps = new GPSTracker(AndroidGPSTrackingActivity.this);

                // check if GPS enabled     
                if(gps.canGetLocation()){

                    double latitude = gps.getLatitude();
                    double longitude = gps.getLongitude();

                    Geocoder gcd = new Geocoder(getApplicationContext(), Locale.getDefault());
                    List<Address> addresses = null;
                    try {
                        addresses = gcd.getFromLocation(latitude, longitude, 1);
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    if(!(addresses == null)){
                        if (!addresses.isEmpty() ){
                            System.out.println(addresses.get(0).getLocality());

                            Address address = addresses.get(0);

                            String addressText = String.format("%s, %s, %s, %s, %s, %s",
                                    address.getAddressLine(0),
                                    address.getAddressLine(1),
                                    address.getAddressLine(2),
                                    address.getAddressLine(3),
                                    address.getPhone(),
                                    address.getPremises());

                            System.out.println(addressText);

                            // 
 is for new line
                            Toast.makeText(getApplicationContext(), "Your Location is - 
Lat: " + latitude + "
Long: " + longitude, Toast.LENGTH_LONG).show();
                        }else{
                            // can't get location
                            // GPS or Network is not enabled
                            // Ask user to enable GPS/network in settings
                            gps.showSettingsAlert();
                        }
                    }else{
                        // can't get location
                        // GPS or Network is not enabled
                        // Ask user to enable GPS/network in settings
                        gps.showSettingsAlert();
                    }

                }

            }
        });
    }

}

GPSTracker.java

package com.example.gpstracking;

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;

public class GPSTracker extends Service implements LocationListener {

    private final Context mContext;

    // flag for GPS status
    boolean isGPSEnabled = false;

    // flag for GPS status
    boolean canGetLocation = false;

    Location location; // location
    double latitude; // latitude
    double longitude; // longitude

    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

    // Declaring a Location Manager
    protected LocationManager locationManager;

    public GPSTracker(Context context) {
        this.mContext = context;
        getLocation();
    }

    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);

            // getting GPS status
            isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

            // getting network status
            boolean wifiEnabled = AndroidGPSTrackingActivity.wifiManager.isWifiEnabled();

            ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();

            this.canGetLocation = true;

            // if DATA Enabled get lat/long using WIFI Services
            if (activeNetwork.isConnected()) {
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d("Network", "Network");
                if (locationManager != null) {
                    location = locationManager
                            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

                }
            }
            // if WIFI Enabled get lat/long using WIFI Services
            if (wifiEnabled) {
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d("Network", "Network");
                if (locationManager != null) {
                    location = locationManager
                            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

                }
            }
            // if GPS Enabled get lat/long using GPS Services
            if (isGPSEnabled) {
                if (location == null) {
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("GPS Enabled", "GPS Enabled");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.GPS_PROVIDER);

                    }
                }
            }
            if (location != null) {
                latitude = location.getLatitude();
                longitude = location.getLongitude();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return location;
    }

    /**
     * Stop using GPS listener
     * Calling this function will stop using GPS in your app
     * */
    public void stopUsingGPS(){
        if(locationManager != null){
            locationManager.removeUpdates(GPSTracker.this);
        }       
    }

    /**
     * Function to get latitude
     * */
    public double getLatitude(){
        if(location != null){
            latitude = location.getLatitude();
        }

        // return latitude
        return latitude;
    }

    /**
     * Function to get longitude
     * */
    public double getLongitude(){
        if(location != null){
            longitude = location.getLongitude();
        }

        // return longitude
        return longitude;
    }

    /**
     * Function to check GPS/wifi enabled
     * @return boolean
     * */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }

    /**
     * Function to show settings alert dialog
     * On pressing Settings button will lauch Setting

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...