简体   繁体   中英

How do I fix the null pointer exception in a GPS service program?

I am fairly new to Android, and I want to save the coordinates displayed by a GPS in a text file. I asked this question earlier, and I received a response. However, when I tried the code I encountered a null pointer exception. Does anyone have any ideas on how to solve this issue? (Most of the code below is not mine).

Link to my previous question: How do I get coordinates from a GPS service into a text file?

Current code:

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();
        }
    }
}
}

The error occurs in the first try/catch under the OnResume method.

With

Attempt to invoke virtual method 'void java.io.BufferedWriter.write(java.lang.String)' on a null object reference in the logcat.

Your writer isn't initialized because the file you're trying to write to is invalid. First, you left off the opening / , you meant /mnt/sdcard . Secondly, there's no promise that's where the sdcard is mounted. Never use the direct path of an sd card in android, use getExternalDirectory to find it. Third, on kitkat and above this will still fail as you don't get write access to the root of an sdcard.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM