GPS并不总是获得坐标 - Android

时间:2014-12-17 10:43:11

标签: android gps

我试图获取拍摄照片的地方的GPS坐标。但有时,纬度和经度具有默认的0.0d值,应用程序崩溃,即使GPS已激活。为什么我总能获得坐标?

public class FragmentTab2_Image extends Fragment {

GPSTracker gps;

// Fragment request codes
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
public static final int MEDIA_TYPE_IMAGE = 1;

// directory name to store captured images
private static final String IMAGE_DIRECTORY_NAME = "blabla";

private Uri fileUri; // file url to store image

private ImageView imgPreview;
private Button btnCapturePicture;
Context thiscontext;

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
}


@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
@Override
public void onViewStateRestored(Bundle savedInstanceState) {
    super.onViewStateRestored(savedInstanceState);
    if (savedInstanceState != null)
        savedInstanceState.getParcelable("file_uri");
}

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState){
    View view = inflater.inflate(R.layout.image_capture, container, false);

    thiscontext = container.getContext();
    imgPreview = (ImageView) view.findViewById(R.id.imgPreview);
    btnCapturePicture = (Button) view.findViewById(R.id.btnCapturePicture);

    /**
     * Capture image button click event
     * */
    btnCapturePicture.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // capture picture
            captureImage();
        }
    });

    return view;
}

//
/**
 * Receiving activity result method will be called after closing the camera
 * + get gps location of picture
 * */

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    // if the result is capturing Image
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
        //TODO
        gps = new GPSTracker(thiscontext);
        if (resultCode == Activity.RESULT_OK) {
            // successfully captured the image
            // display it in image view
            previewCapturedImage();

            //get gps location coordinates
            if(gps.canGetLocation())
            {
                double latitude = gps.getLatitude();
                double longitude = gps.getLongitude();

                Toast.makeText(thiscontext, "Your Location is - \nLat: " + latitude + "\nLong: "
                        + longitude, Toast.LENGTH_LONG).show();

                //from latitude and longitude to address
                Geocoder gcd = new Geocoder(thiscontext, Locale.getDefault());
                List<Address> addresses = null;
                try {
                    addresses = gcd.getFromLocation(latitude, longitude, 1);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if(latitude != 0.0d && longitude != 0.0d)
                    if (addresses.size() > 0) {
                        String tara = addresses.get(0).getCountryName();
                        String judet = addresses.get(0).getLocality();
                        String oras = addresses.get(0).getSubLocality();
                        String adresa = addresses.get(0).getAddressLine(0);
                        System.out.println(tara + ", " + judet + ", " + oras + ", " + adresa + "\n");
                    }
                if (latitude == 0.0d || longitude == 0.0d)
                        Toast.makeText(thiscontext, "Coordinates weren't taken",
                                Toast.LENGTH_LONG).show();
            } else {
                // Can't get location.
                // GPS or network is not enabled.
                // Ask user to enable GPS/network in settings.
                Toast.makeText(thiscontext, "Activate GPS", Toast.LENGTH_LONG).show();

            }


            //TODO
            //GET DATE OF IMAGE
            String pathToFile = fileUri.getPath();
            File file = new File(pathToFile);
            if(file.exists()) {
                String date = new SimpleDateFormat("dd-MM-yyyy HH-mm-ss").format(
                        new Date(file.lastModified())
                );
                Toast.makeText(thiscontext, date, Toast.LENGTH_LONG)
                        .show();
            }



        } else if (resultCode == Activity.RESULT_CANCELED) {
            // user cancelled Image capture
            Toast.makeText(thiscontext,
                    "Canceled", Toast.LENGTH_SHORT)
                    .show();
        } else {
            // failed to capture image
            Toast.makeText(thiscontext,
                    "Error!", Toast.LENGTH_SHORT)
                    .show();
        }
    }

}

/**
 * Here we store the file url as it will be null after returning from camera
 * app
 */
@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    // save file url in bundle as it will be null on scren orientation
    // changes
    outState.putParcelable("file_uri", fileUri);
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    if (savedInstanceState != null) {
        // Restore last state for checked position.
        fileUri = savedInstanceState.getParcelable("file_uri");
    }
}



/*
________________________________________________________________________________________
helper methods :
*/

//method to fire camera
private void captureImage() {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);

    intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

    // start the image capture Intent
    startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);

}

/**
 * Creating file uri to store image/video
 */
public Uri getOutputMediaFileUri(int type) {
    return Uri.fromFile(getOutputMediaFile(type));
}

/*
 * returning image / video
 */
private static File getOutputMediaFile(int type) {

    // External sdcard location
    File mediaStorageDir = new File(
            Environment
                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            IMAGE_DIRECTORY_NAME);

    // Create the storage directory if it does not exist
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            Log.d(IMAGE_DIRECTORY_NAME, "File"
                    + IMAGE_DIRECTORY_NAME + " was not created");
            return null;
        }
    }

    // Create a media file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
            Locale.getDefault()).format(new Date());
    File mediaFileName;
    if (type == MEDIA_TYPE_IMAGE) {
        mediaFileName = new File(mediaStorageDir.getPath() + File.separator
                + "IMG_" + timeStamp + ".jpg");
    } else {
        return null;
    }

    return mediaFileName;
}

/*
 * Display image from a path to ImageView
 */
private void previewCapturedImage() {
    try {
        imgPreview.setVisibility(View.VISIBLE);

        // bimatp factory
        BitmapFactory.Options options = new BitmapFactory.Options();

        // downsizing image as it throws OutOfMemory Exception for larger
        // images
        options.inSampleSize = 8;

        final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
                options);

        imgPreview.setImageBitmap(bitmap);

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



}

片段是MainActivity的一部分。

logcat的:

java.lang.RuntimeException: Failure delivering result ResultInfo{who=android:fragment:1, request=100, result=-1, data=null} to activity {package/package.MainActivity}: java.lang.NullPointerException
        at android.app.ActivityThread.deliverResults(ActivityThread.java:3551)
        at android.app.ActivityThread.handleSendResult(ActivityThread.java:3594)
        at android.app.ActivityThread.access$1400(ActivityThread.java:161)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1313)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:157)
        at android.app.ActivityThread.main(ActivityThread.java:5356)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
        at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.NullPointerException
        at ro.asisoft.ImaginiAsigurari.app1.fragments.FragmentTab2_Image.onActivityResult(FragmentTab2_Image.java:130)
        at android.app.Activity.dispatchActivityResult(Activity.java:5622)
        at android.app.ActivityThread.deliverResults(ActivityThread.java:3547)

        at android.app.ActivityThread.handleSendResult(ActivityThread.java:3594)
        at android.app.ActivityThread.access$1400(ActivityThread.java:161)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1313)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:157)
        at android.app.ActivityThread.main(ActivityThread.java:5356)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
        at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:3)

尝试将GPSTracker对象初始化为onCreateView()onCreate()

 gps = new GPSTracker(getActivity());
相关问题