我是一个开发Android应用程序的新手,但这里是。我正在尝试设计一个应用程序来获取用户的GPS位置,所以我有代码获取GPS位置,以及.php页面发布数据,但我面临的问题是,但现在我我遇到了空指针异常错误和android.view.WindowLeaked。
package com.wise.ezzie_taxie;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class AndroidGPSTrackingActivity extends Activity {
double latitude;
double longitude;
String IMEINumber;
JSONParser jsonParser = new JSONParser();
// Progress Dialog
private ProgressDialog pDialog;
Button btnShowLocation;
// GPSTracker class
GPSTracker gps;
// url to add coordinates
private static final String url_add_coordinate = "http://10.0.2.2/project/create.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_LATITUDE = "latitude";
private static final String TAG_LONGITUDE = "longitude";
private static final String TAG_IMEI = "imeino";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnShowLocation = (Button) findViewById(R.id.btnShowLoation);
// show location button click event
btnShowLocation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
IMEINumber = tm.getDeviceId();// get IMEI no.
// create class object
gps = new GPSTracker(AndroidGPSTrackingActivity.this);
// check if GPS enabled
if (gps.canGetLocation()) {
latitude = gps.getLatitude();
longitude = gps.getLongitude();
// \n is for new line
Toast.makeText(
getApplicationContext(),
"Your Location is - \nLat: " + latitude
+ "\nLong: " + 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();
}
new Entercoordinate().execute();
}
});
}
/**
* Background Async Task to Create new product
* */
class Entercoordinate extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AndroidGPSTrackingActivity.this);
pDialog.setMessage("adding new coordinate..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* adding new coordinate
* */
@Override
protected String doInBackground(String... args) {
String lati = String.valueOf(latitude);
String longi = String.valueOf(longitude);
String imeino = String.valueOf(IMEINumber);
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(TAG_LATITUDE, lati));
params.add(new BasicNameValuePair(TAG_LONGITUDE, longi));
params.add(new BasicNameValuePair(TAG_IMEI, imeino));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_add_coordinate,
"POST", params);
// check log cat for response
// Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully entered coordinate
Toast.makeText(getApplicationContext(),
"Your Location is added successfully ",
Toast.LENGTH_LONG).show();
// closing this screen
finish();
} else {
// failed to enter coordinate
Toast.makeText(getApplicationContext(),
"Your Location is not added successfully ",
Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
@Override
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
pDialog.dismiss();
pDialog.dismiss();
}
}
}
我的gps跟踪器类是 包com.wise.ezzie_taxie;
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.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
public class GPSTracker extends Service implements LocationListener {
/*
* COMMENTS LocationListner is used for receiving notifications from the
* LocationManager when the location has changed.
* refrence:http://developer.android.
* .com/reference/android/location/LocationListener.html to access system
* services global variable declaration to use anywhere
*/
private final Context mContext;
// GPS status flag to check if GPS is switched on or not
boolean isGPSEnabled = false;
// network status flag to check if network provider connection is switched
// on or not
boolean isNetworkEnabled = 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() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
alertDialog.setMessage("no network provider is enabled");
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
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 (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get latitude/longitude 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
* launch Settings Options
* */
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog
.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button, to display settings pages
alertDialog.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button, to cancel
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
}
我的json解析器类是
package com.wise.ezzie_taxie;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,List<NameValuePair> params) {
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Making HTTP request
try {
// check for request method
if (method == "POST") {
// request method is POST
// defaultHttpClient
// Construct the client and the HTTP request.
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
httpResponse = httpClient.execute(httpPost);// Execute the POST request and store the response locally.
httpEntity = httpResponse.getEntity();// Extract data from the response.
//is = httpEntity.getContent();// Open an inputStream with the data content.
} else if (method == "GET") {
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
httpEntity = httpResponse.getEntity();
if(httpEntity !=null)
{
Log.i("RESPONSE", EntityUtils.toString(httpEntity));
}
else{
Log.i("NULL", EntityUtils.toString(httpEntity));
}
}
if(httpEntity != null)
{
is = httpEntity.getContent();
//Log.i("RESPONSE", EntityUtils.toString(httpEntity));
} else {
httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
//Log.i("NULL", EntityUtils.toString(httpEntity));
}
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
// Create a BufferedReader to parse through the inputStream.
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "ISO-8859-1"), 8);
StringBuilder sb = new StringBuilder(50);// Declare a string builder to help with the parsing.
String line = null;// Declare a string to store the JSON object data in string form.
line = reader.readLine();
while ((line = reader.readLine()) != null) {// Build the string until null.
sb.append(line + "\n");
}
is.close();// Close the input stream.
json = sb.toString();// Convert the string builder data to an actual string.
//json = json.replaceAll("db_connect.php", "");
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
我发布的php代码看起来像dis
<?php
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['latitude']) && isset($_POST['longitude']) && isset($_POST['imeino'])) {
$lat = $_POST['latitude'];
$long = $_POST['longitude'];
$imei = $_POST['imeino'];
// include db connect class
require_once '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$result = mysql_query("INSERT INTO coordinate(imei, latitude, longitude) VALUES('$imei','$lat', '$long')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "entry successfully created.";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
我的logcat向我显示以下错误..
10-18 02:52:55.920: D/GPS Enabled(427): GPS Enabled
10-18 02:52:58.550: E/JSON Parser(427): Error parsing data org.json.JSONException: End of input at character 0 of
10-18 02:52:58.550: W/dalvikvm(427): threadid=8: thread exiting with uncaught exception (group=0x4001d800)
10-18 02:52:58.710: D/dalvikvm(427): GC_FOR_MALLOC freed 2568 objects / 165384 bytes in 144ms
10-18 02:52:58.710: E/AndroidRuntime(427): FATAL EXCEPTION: AsyncTask #1
10-18 02:52:58.710: E/AndroidRuntime(427): java.lang.RuntimeException: An error occured while executing doInBackground()
10-18 02:52:58.710: E/AndroidRuntime(427): at android.os.AsyncTask$3.done(AsyncTask.java:200)
10-18 02:52:58.710: E/AndroidRuntime(427): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
10-18 02:52:58.710: E/AndroidRuntime(427): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
10-18 02:52:58.710: E/AndroidRuntime(427): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
10-18 02:52:58.710: E/AndroidRuntime(427): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
10-18 02:52:58.710: E/AndroidRuntime(427): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
10-18 02:52:58.710: E/AndroidRuntime(427): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
10-18 02:52:58.710: E/AndroidRuntime(427): at java.lang.Thread.run(Thread.java:1096)
10-18 02:52:58.710: E/AndroidRuntime(427): Caused by: java.lang.NullPointerException
10-18 02:52:58.710: E/AndroidRuntime(427): at com.wise.ezzie_taxie.AndroidGPSTrackingActivity$Entercoordinate.doInBackground(AndroidGPSTrackingActivity.java:137)
10-18 02:52:58.710: E/AndroidRuntime(427): at com.wise.ezzie_taxie.AndroidGPSTrackingActivity$Entercoordinate.doInBackground(AndroidGPSTrackingActivity.java:1)
10-18 02:52:58.710: E/AndroidRuntime(427): at android.os.AsyncTask$2.call(AsyncTask.java:185)
10-18 02:52:58.710: E/AndroidRuntime(427): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
10-18 02:52:58.710: E/AndroidRuntime(427): ... 4 more
10-18 02:52:59.350: E/WindowManager(427): Activity com.wise.ezzie_taxie.AndroidGPSTrackingActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@45fcf4c0 that was originally added here
10-18 02:52:59.350: E/WindowManager(427): android.view.WindowLeaked: Activity com.wise.ezzie_taxie.AndroidGPSTrackingActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@45fcf4c0 that was originally added here
10-18 02:52:59.350: E/WindowManager(427): at android.view.ViewRoot.<init>(ViewRoot.java:247)
10-18 02:52:59.350: E/WindowManager(427): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148)
10-18 02:52:59.350: E/WindowManager(427): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
10-18 02:52:59.350: E/WindowManager(427): at android.view.Window$LocalWindowManager.addView(Window.java:424)
10-18 02:52:59.350: E/WindowManager(427): at android.app.Dialog.show(Dialog.java:241)
10-18 02:52:59.350: E/WindowManager(427): at com.wise.ezzie_taxie.AndroidGPSTrackingActivity$Entercoordinate.onPreExecute(AndroidGPSTrackingActivity.java:109)
10-18 02:52:59.350: E/WindowManager(427): at android.os.AsyncTask.execute(AsyncTask.java:391)
10-18 02:52:59.350: E/WindowManager(427): at com.wise.ezzie_taxie.AndroidGPSTrackingActivity$1.onClick(AndroidGPSTrackingActivity.java:87)
10-18 02:52:59.350: E/WindowManager(427): at android.view.View.performClick(View.java:2408)
10-18 02:52:59.350: E/WindowManager(427): at android.view.View$PerformClick.run(View.java:8816)
10-18 02:52:59.350: E/WindowManager(427): at android.os.Handler.handleCallback(Handler.java:587)
10-18 02:52:59.350: E/WindowManager(427): at android.os.Handler.dispatchMessage(Handler.java:92)
10-18 02:52:59.350: E/WindowManager(427): at android.os.Looper.loop(Looper.java:123)
10-18 02:52:59.350: E/WindowManager(427): at android.app.ActivityThread.main(ActivityThread.java:4627)
10-18 02:52:59.350: E/WindowManager(427): at java.lang.reflect.Method.invokeNative(Native Method)
10-18 02:52:59.350: E/WindowManager(427): at java.lang.reflect.Method.invoke(Method.java:521)
10-18 02:52:59.350: E/WindowManager(427): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
10-18 02:52:59.350: E/WindowManager(427): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
10-18 02:52:59.350: E/WindowManager(427): at dalvik.system.NativeStart.main(Native Method)
需要绝望的帮助。