Hi团队已经开发了一个名为AutoDial的应用程序,它在该应用程序中成功运行 所有Android设备和三星设备都不能正常工作所以请帮我解决这个问题。
这是我的logcat:
04-09 10:32:12.521: I/log(5166): maaaap{}
04-09 10:32:12.543: D/GPS Enabled(5166): GPS Enabled
04-09 10:32:12.543: I/System.out(5166): inside location manager
04-09 10:32:12.546: D/AndroidRuntime(5166): Shutting down VM
04-09 10:32:12.547: W/dalvikvm(5166): threadid=1: thread exiting with uncaught exception (group=0x416c8d40)
04-09 10:32:12.548: E/AndroidRuntime(5166): FATAL EXCEPTION: main
04-09 10:32:12.548: E/AndroidRuntime(5166): Process: com.example.gpstracking, PID: 5166
04-09 10:32:12.548: E/AndroidRuntime(5166): java.lang.NullPointerException
04-09 10:32:12.548: E/AndroidRuntime(5166): at com.example.gpstracking.AndroidGPSTrackingActivity$1$1$1.run(AndroidGPSTrackingActivity.java:169)
04-09 10:32:12.548: E/AndroidRuntime(5166): at android.os.Handler.handleCallback(Handler.java:733)
04-09 10:32:12.548: E/AndroidRuntime(5166): at android.os.Handler.dispatchMessage(Handler.java:95)
04-09 10:32:12.548: E/AndroidRuntime(5166): at android.os.Looper.loop(Looper.java:136)
04-09 10:32:12.548: E/AndroidRuntime(5166): at android.app.ActivityThread.main(ActivityThread.java:5102)
04-09 10:32:12.548: E/AndroidRuntime(5166): at java.lang.reflect.Method.invokeNative(Native Method)
04-09 10:32:12.548: E/AndroidRuntime(5166): at java.lang.reflect.Method.invoke(Method.java:515)
04-09 10:32:12.548: E/AndroidRuntime(5166): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
04-09 10:32:12.548: E/AndroidRuntime(5166): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
04-09 10:32:12.548: E/AndroidRuntime(5166): at dalvik.system.NativeStart.main(Native Method)
以下是我的代码,并告诉我在此代码段中需要做的所有更改。
package com.example.gpstracking;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.TreeMap;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
public class AndroidGPSTrackingActivity extends Activity implements View.OnClickListener
{
Button btnShowLocation;
Button btnWriteSDFile;
Button btnClose;
EditText txtData;
GPSTracker gps;
private Spinner spinner1, spinner2;
private Button btnSubmit;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
addItemsOnSpinner2();
checkExternalMedia();
writeToExternalTextFile();
readfromFilesms();
addListenerOnButton();
addListenerOnSpinnerItemSelection();
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
{
Toast.makeText(this, "GPS is Enabled in your devide", Toast.LENGTH_SHORT).show();
}
else
{
showGPSDisabledAlertToUser();
}
btnShowLocation = (Button) findViewById(R.id.btnShowLocation);
btnShowLocation.setOnClickListener(new View.OnClickListener()
{
@SuppressWarnings("unused")
public void onClick(View v)
{
Context c = getApplicationContext();
SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(c);
SharedPreferences.Editor editor = app_preferences.edit();
TimerTask scanTask;
final Handler handler = new Handler();
Timer t = new Timer();
scanTask = new TimerTask()
{
GPSTracker gps;
List<Double> l = new ArrayList<Double>();
TreeMap<Double,List<Double>> list = new TreeMap<Double,List<Double>>();
public void run()
{
handler.post(new Runnable()
{
public void run()
{
Context c = getApplicationContext();
SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(c);
SharedPreferences.Editor editor = app_preferences.edit();
int counter = app_preferences.getInt("counter", 0);
Log.i("log", "maaaap"+list);
Double latitude=new Double(0.0d);
Double longitude=new Double(0.0d);
l = new ArrayList<Double>();
gps = new GPSTracker(AndroidGPSTrackingActivity.this);
if(gps.canGetLocation())
{
l.add(gps.getLatitude());
l.add(gps.getLongitude());
list.put(gps.getAccur(),l);
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + gps.getLatitude() + "\nLong:" + gps.getLongitude()+ "\nAccracy:"+gps.getAccur(), Toast.LENGTH_SHORT).show();
Log.i("log", "latitude"+gps.getLatitude());
Log.i("log", "longitude"+gps.getLongitude());
Log.i("log", "gps.getAccur()"+gps.getAccur());
Log.d("tag", "Finding Latitude");
latitude = gps.getLatitude();
Log.d("tag", "Lat: "+String.valueOf(latitude));
Log.d("tag", "Finding Longitude");
longitude = gps.getLongitude();
Log.d("tag", "Lon: "+String.valueOf(longitude));
String Text =
"\nLat: " + gps.getLatitude() +
"\nLan:" + gps.getLongitude()+"\nAcrcy="+gps.getAccur();
sendSMS(readfromFilesms(), Text);
}
else
{
}
if(counter<12)
{
if(gps.getAccur()<=3)
{
Double d = (Double)list.firstKey();
Log.i("log", "gps.firstKey()"+d);
List<?> l1 = (List<?>)list.get(d);
Log.i("log", "gps.l1()"+(Double)l1.get(0));
Log.i("log", "gps.l2"+(Double)l1.get(1));
latitude = (Double)l1.get(0);
longitude = (Double)l1.get(1);
editor.putInt("counter", 0);
editor.commit(); // Very important
cancel();
}
else
{
counter = app_preferences.getInt("counter", 0);
Log.i("log", "counter"+counter);
editor.putInt("counter", ++counter);
editor.commit();
}
}
else
{
Double d = (Double)list.firstKey();
Log.i("log", "gps.firstKey()"+d);
List<?> l1 = (List<?>)list.get(d);
Log.i("log", "gps.l1()"+(Double)l1.get(0));
Log.i("log", "gps.l2"+(Double)l1.get(1));
latitude = (Double)l1.get(0);
longitude = (Double)l1.get(1);
editor.putInt("counter", 0);
editor.commit(); // Very important
cancel();
}
}
});
}};
t.schedule(scanTask,1000,90000000);
}
});
btnClose = (Button) findViewById(R.id.btnClose);
btnClose.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
finish();
}
});
}
public void addListenerOnButton()
{
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner2 = (Spinner) findViewById(R.id.spinner2);
btnSubmit = (Button) findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Toast.makeText(AndroidGPSTrackingActivity.this,
String.valueOf(spinner2.getSelectedItem()),
Toast.LENGTH_SHORT).show();
sendSMS(readfromFilesms(),"on leave");
}
});
}
private void sendSMS(String phoneNumber, String message)
{
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,new Intent(SENT), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0, new Intent(DELIVERED), 0);
registerReceiver(new BroadcastReceiver()
{
public void onReceive(Context arg0, Intent arg1)
{
switch (getResultCode())
{
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS Sent",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getBaseContext(), "Generic Failure",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getBaseContext(), "No Service",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getBaseContext(), "null",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getBaseContext(), "Radio off",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(SENT));
registerReceiver(new BroadcastReceiver()
{
public void onReceive(Context arg0, Intent arg1)
{
switch (getResultCode())
{
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS Dlivered",
Toast.LENGTH_SHORT).show();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(getBaseContext(), "SMS not Delivered",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(DELIVERED));
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
}
private void showGPSDisabledAlertToUser()
{
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("GPS is disabled in your device. Would you like to enable it?")
.setCancelable(false)
.setPositiveButton("GPS Setting",
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
Intent callGPSSettingIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(callGPSSettingIntent);
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
public void addItemsOnSpinner2() {
spinner2 = (Spinner) findViewById(R.id.spinner2);
List<String> list = new ArrayList<String>();
list.add("Casual Leave");
list.add("Medical Leave");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(dataAdapter);
}
public void addListenerOnSpinnerItemSelection()
{
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner1.setOnItemSelectedListener(new CustomOnItemSelectedListener());
}
private void checkExternalMedia()
{
@SuppressWarnings("unused")
boolean mExternalStorageAvailable = false;
@SuppressWarnings("unused")
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state))
{
mExternalStorageAvailable = mExternalStorageWriteable = true;
}
else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state))
{
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
}
else
{
// Can't read or write
mExternalStorageAvailable = mExternalStorageWriteable = false;
}
}
private void writeToExternalTextFile()
{
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath() + "/PhoneNumber");
if(!dir.exists())
dir.mkdirs();
File file = new File(dir, "PhNumber.txt");
if (!file.exists ())
{
try
{
FileOutputStream f = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(f);
pw.flush();
pw.close();
f.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
private String readfromFilesms()
{
File root = android.os.Environment.getExternalStorageDirectory();
Log.i("log", "ddddddddddddddddddddddddddddddd"+root.getAbsolutePath());
File dir = new File(root.getAbsolutePath() + "/PhoneNumber");
String aBuffer = "";
File file = new File(dir, "PhNumber.txt");
if (file.exists ())
{
try
{
FileInputStream fIn = new FileInputStream(file);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
String aDataRow = "";
while ((aDataRow = myReader.readLine()) != null)
{
aBuffer += aDataRow ;
}
myReader.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
Log.i("TAG",
"******* File not found. Did you"
+ " add a WRITE_EXTERNAL_STORAGE permission to the manifest?");
}
catch (IOException e)
{
e.printStackTrace();
}
}
return aBuffer;
}
@Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
}
}
您还有一项名为GpsTracker活动的活动,因此必须对其进行更改 或者是什么帮助我使用代码片段。
这是我的GpsTracker活动:
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.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
Double accur;
public Double getAccur() {
return accur;
}
public void setAccur(Double accur) {
this.accur = accur;
}
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 12; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 0; // 1 sec
// Declaring a Location Manager
protected LocationManager locationManager;
public Object getAccuracy;
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
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// 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){
System.out.println("inside location");
latitude = location.getLatitude();
System.out.println("lat"+latitude);
longitude = location.getLongitude();
}
}
}
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) {
System.out.println("inside location manager");
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
System.out.println("inside location");
latitude = location.getLatitude();
System.out.println("lat"+latitude);
longitude = location.getLongitude();
}
}
}
}
}
if(location!=null)
{
setAccur(new Double(location.getAccuracy()));
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
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 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
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
/* 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;
}
}
答案 0 :(得分:0)
您正在打印日志:
"maaaap" + list
at
Log.i("log", "maaaap" + list);
其中list
为空
所以在你的activity
,在
scanTask = new TimerTask() {
表示“else
”部分:
Double d = (Double) list.firstKey();
list
为null,抛出NPE。
添加空指针检查:if(list!=null)
和/或将“else
”设为“else if
”
与上一个else
内部相似:
if(list!=null){
Double d = (Double)list.firstKey();
Log.i("log", "gps.firstKey()"+d);
List<?> l1 = (List<?>)list.get(d);
Log.i("log", "gps.l1()"+(Double)l1.get(0));
Log.i("log", "gps.l2"+(Double)l1.get(1));
latitude = (Double)l1.get(0);
longitude = (Double)l1.get(1);
editor.putInt("counter", 0);
editor.commit(); // Very important
cancel();
}
如果您的原始查询已被回答,请提出其他问题。
有关NPE的更多信息,
参考:
http://examples.javacodegeeks.com/java-basics/exceptions/java-lang-nullpointerexception-how-to-handle-null-pointer-exception/