user3829961 user3829961 - 3 months ago 29
Android Question

How to fix java.lang.NullPointerException 'void android.widget.Textview.setText'

I have looked everywhere online to help fix my

NullPointerException
error, but nothing seems to be working.

The id is correct and android studio is up to date.

The exception message is particular to
TextView
.

I believe that the error happens on line 85 when I set up the text.

My code:

import android.net.Uri;
import android.os.Bundle;
import android.media.MediaRecorder;
import android.os.Handler;
import android.util.Log;
import android.media.MediaPlayer;
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.widget.TextView;
import android.os.Vibrator;

import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;

import java.io.IOException;

public class MainActivity extends Activity implements SensorEventListener {

//Sound ping
private MediaPlayer golfSound;
private MediaRecorder soundCapture;
private Thread recording;
private static double mEMA = 0.0;
static final private double EMA_FILTER = 0.6;

//Accelerometer
private float lastX, lastY, lastZ;
private SensorManager sensorManager;
private Sensor accelerometer;
private float deltaX = 0;
private float deltaY = 0;
private float deltaZ = 0;
private TextView currentX, currentY, currentZ, maxX, maxY, maxZ;
private Vibrator v;

//Compass
private TextView tvHeading;
private SensorManager mSensorManager;

//running ping
private final Runnable show = new Runnable() {

public void run() {

updateTv();
}
};

private final Handler myHandler = new Handler();
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

//Sound Ping
golfSound = MediaPlayer.create(this, R.raw.golfswing);

//Accelerometer finding
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
if (sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) != null) {
accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
} else {
// fail we don't have an accelerometer
}
//Vibration
v = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE);

//Print Degrees
tvHeading = (TextView) findViewById(R.id.tvHeading);
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);

//run the microphone
if (recording == null) {
recording = new Thread() {
public void run() {
while (recording != null) {
try {
Thread.sleep(1000);
Log.i("Noise", "Running");
} catch (InterruptedException ignored) {
}
myHandler.post(show);
}
}
};
recording.start();
Log.d("Working", "start recording()");
}
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}

//what it does when listening
@Override
public void onResume() {
super.onResume();
startRecorder();
sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION), SensorManager.SENSOR_DELAY_GAME);
}

//what it does when stopped
@Override
public void onPause() {
super.onPause();
stopRecorder();
sensorManager.unregisterListener(this);
mSensorManager.unregisterListener(this);
}

//recording sounds around
private void startRecorder() {
if (soundCapture == null) {
soundCapture = new MediaRecorder();
soundCapture.setAudioSource(MediaRecorder.AudioSource.MIC);
soundCapture.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
soundCapture.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
soundCapture.setOutputFile("/dev/null");
try {
soundCapture.prepare();
} catch (IOException ioe) {
Log.e("[Monkey]", "IOException: " + Log.getStackTraceString(ioe));

} catch (SecurityException e) {
Log.e("[Monkey]", "SecurityException: " + Log.getStackTraceString(e));
}
try {
soundCapture.start();
} catch (SecurityException e) {
Log.e("[Monkey]", "SecurityException: " + Log.getStackTraceString(e));
}
}
}

//stoping it after 1000 milliseconds
private void stopRecorder() {
if (soundCapture != null) {
soundCapture.stop();
soundCapture.release();
soundCapture = null;
}
}

//returns the highest sound (getMaxAmplitude) within the range
private double getAmplitude() {
if (soundCapture != null)
return (soundCapture.getMaxAmplitude());
else
return 0;

}

//changes from getAmplitude value to decibel
private double getAmplitudeEMA() {
double amp = getAmplitude();
mEMA = EMA_FILTER * amp + (1.0 - EMA_FILTER) * mEMA;
return mEMA;
}

//If the sound is higher than 9000 db, sound comes
private void updateTv() {
double ping = getAmplitudeEMA();
if (ping >= 9000) {
golfSound.start();
}
}

//Finds the x, y, and z coordinates of the Accelerometer and compass headings
@Override
public void onSensorChanged(SensorEvent event) {

// clean current values
displayCleanValues();
// display the current x,y,z accelerometer values
displayCurrentValues();

// get the change of the x,y,z values of the accelerometer
deltaX = Math.abs(lastX - event.values[0]);
deltaY = Math.abs(lastY - event.values[1]);
deltaZ = Math.abs(lastZ - event.values[2]);

// if the change is below 2, it is just plain noise
if (deltaX < 2)
deltaX = 0;
if (deltaY < 2)
deltaY = 0;
if (deltaZ < 2)
deltaZ = 0;

vibrate();


//get the angle around the z-axis rotated
float degree = Math.round(event.values[0]);
tvHeading.setText("Heading: " + Float.toString(degree) + " degrees");
}

//Vibrate test
private void vibrate() {
float vibrateThreshold = 0;
if ((deltaX > vibrateThreshold) || (deltaY > vibrateThreshold) || (deltaZ > vibrateThreshold)) {
v.vibrate(50);
}
}

//Displays at the start Accelerometer
private void displayCleanValues() {
currentX.setText("0.0");
currentY.setText("0.0");
currentZ.setText("0.0");
}

//Displays in current position Accelerometer
private void displayCurrentValues() {
currentX.setText(Float.toString(deltaX));
currentY.setText(Float.toString(deltaY));
currentZ.setText(Float.toString(deltaZ));
}

//Need this for Accelerometer and compass
public void onAccuracyChanged(Sensor sensor, int i) {

}


/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
public Action getIndexApiAction() {
Thing object = new Thing.Builder()
.setName("Main Page") // TODO: Define a title for the content shown.
// TODO: Make sure this auto-generated URL is correct.
.setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
.build();
return new Action.Builder(Action.TYPE_VIEW)
.setObject(object)
.setActionStatus(Action.STATUS_TYPE_COMPLETED)
.build();
}

@Override
public void onStart() {
super.onStart();

// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
AppIndex.AppIndexApi.start(client, getIndexApiAction());
}

@Override
public void onStop() {
super.onStop();

// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
AppIndex.AppIndexApi.end(client, getIndexApiAction());
client.disconnect();
}
}

Answer

Your tvHeading textView is not the problem; these ones are:

private TextView currentX, currentY, currentZ

You're using setText() on those too in displayCurrentValues() and you've not initialized them anywhere.

Initialize those 3 textViews and you'll get rid of the error.

Comments