java - 如何解决GPS服务程序中的空指针异常?

原文 标签 java android gps

我刚接触Android,我想将GPS显示的坐标保存在文本文件中。我早些时候问了这个问题,并且收到了答复。但是,当我尝试代码时,遇到了空指针异常。是否有人对如何解决此问题有任何想法? (以下大多数代码不是我的)。

链接到我之前的问题:How do I get coordinates from a GPS service into a text file?

当前代码:

public class MainActivity extends AppCompatActivity {

private Button btn_start, btn_stop;
public Button save;
BufferedWriter writer;

private BroadcastReceiver broadcastReceiver;
int delay = 1000; // delay for 1 sec.
int period = 10000; // repeat every 10 sec.
Timer timer = new Timer();
public EditText editText;
public TextView textView;

public String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/aaTutorial";





@Override
protected void onResume() {
    super.onResume();
    if(broadcastReceiver == null){
        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent)
                {

                    textView.append("\n" +intent.getExtras().get("coordinates"));

                    try {
                        writer.write((String) intent.getExtras().get("coordinates"));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    try {
                        writer.newLine();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }
            };
        };
        registerReceiver(broadcastReceiver,new IntentFilter("location_update"));
    }




protected void onDestroy() {
    super.onDestroy();
    try {
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    if(broadcastReceiver != null){
        unregisterReceiver(broadcastReceiver);
    }
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    try {
        writer = new BufferedWriter(new FileWriter("mnt/sdcard/gps.txt"));
    } catch (IOException e) {
        e.printStackTrace();
    }


    btn_start = (Button) findViewById(R.id.button);
    btn_stop = (Button) findViewById(R.id.button2);
    textView = (TextView) findViewById(R.id.textView);
 //   save = (Button) findViewById(R.id.save);
    File dir = new File(path);
    dir.mkdirs();

    if(!runtime_permissions())
        enable_buttons();

}

private void enable_buttons() {

    btn_start.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent i =new Intent(getApplicationContext(),GPS_Service.class);
            startService(i);
        }
    });




    btn_stop.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Intent i = new Intent(getApplicationContext(),GPS_Service.class);
            stopService(i);

        }
    });

}

private boolean runtime_permissions() {
    if(Build.VERSION.SDK_INT >= 23 && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED){

        requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},100);

        return true;
    }
    return false;
}


@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if(requestCode == 100){
        if( grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED){
            enable_buttons();
        }else {
            runtime_permissions();
        }
    }
}
}


该错误发生在OnResume方法下的第一次try / catch中。




尝试在logcat中的空对象引用上调用虚拟方法'void java.io.BufferedWriter.write(java.lang.String)'。

最佳答案

您的编写器未初始化,因为您要写入的文件无效。首先,您省略了/开头,您的意思是/mnt/sdcard。其次,无法保证将sdcard安装在此处。请勿在android中使用SD卡的直接路径,请使用getExternalDirectory进行查找。第三,在kitkat或更高版本上,由于您没有对sdcard根目录的写权限,因此这仍然会失败。

关于java - 如何解决GPS服务程序中的空指针异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38623709/

相关文章:

android - 推送通知仅适用于外国第三方推送提供商服务?

android - 如何制作 map 中标记的地点的 ListView ?

java - 使用Java中的正则表达式解析SQL表定义

java - 从服务器下载过程中损坏的xlsx文件

android - 将double值传递给Android Java中的其他类

iOS检测模拟位置

go - 无法通过串口解析 GPS 信息

android - android 中的 GPS、AGPS、LBS 是什么?

java - 数字拼图编码

java - TabbedPane循环迭代