我有一个传感器,它捕获数据并每隔几秒钟发布到Firebase。因此,我制作了一个android客户端来显示数据。但是,我尝试了几次,但是代码始终返回'java.lang.NullPointerException'。希望有丰富编码经验的人可以看到发生了什么,谢谢。
Android代码:
public class MainActivity extends AppCompatActivity {
private TextView temperature;
private TextView humidity ;
private Button updatebutton;
DatabaseReference myRef;
String tempData;
String humidData ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
temperature = (TextView)findViewById(R.id.tempdata);
humidity = (TextView)findViewById(R.id.humiddata);
updatebutton=(Button)findViewById(R.id.update_btn);
updatebutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
myRef= FirebaseDatabase.getInstance().getReference().child("sensor_1").child("dht");
myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
String tempdata= Objects.requireNonNull(dataSnapshot.child("temp").getValue()).toString();
String humidData= Objects.requireNonNull(dataSnapshot.child("humidity").getValue()).toString();
temperature.setText(tempdata);
humidity.setText(humidData);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
});
}
}
Firebase
错误
Process: com.example.rpi_weatherapp, PID: 11254
java.lang.NullPointerException
at java.util.Objects.requireNonNull(Objects.java:98)
at com.example.rpi_weatherapp.MainActivity$1$1.onDataChange(MainActivity.java:52)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database@@16.0.4:75)
at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database@@16.0.4:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database@@16.0.4:55)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5399)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:927)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:722)
XML代码
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#B70199EB"
tools:context=".MainActivity">
<TextView
android:id="@+id/humiddata"
android:layout_width="131dp"
android:layout_height="97dp"
android:layout_marginStart="24dp"
android:layout_marginTop="328dp"
android:layout_marginEnd="24dp"
android:text="humid_data"
android:textSize="15sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/temp_textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="52dp"
android:layout_marginEnd="8dp"
android:text="Temperature"
android:textColor="#FFFFFF"
android:textSize="15sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/tempdata"
android:layout_width="131dp"
android:layout_height="97dp"
android:layout_marginStart="24dp"
android:layout_marginTop="108dp"
android:layout_marginEnd="24dp"
android:text="temp_data"
android:textSize="24sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/degreecelcius"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="24dp"
android:layout_marginTop="108dp"
android:layout_marginEnd="24dp"
android:text="℃"
android:textSize="15sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.722"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/humidity_textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="24dp"
android:layout_marginTop="284dp"
android:layout_marginEnd="24dp"
android:text="Humidity"
android:textColor="#FFFFFF"
android:textSize="15sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/percentage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="24dp"
android:layout_marginTop="328dp"
android:layout_marginEnd="24dp"
android:text="%"
android:textSize="15sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.724"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/update_btn"
style="@style/Widget.AppCompat.Button.Colored"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="24dp"
android:layout_marginTop="500dp"
android:layout_marginEnd="24dp"
android:layout_marginBottom="24dp"
android:text="Update "
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.201" />
</android.support.constraint.ConstraintLayout>
完整Logcat
05-17 01:40:44.118 20828-20828/? I/PMFunc: prepare 0 com.example.rpi_weatherapp
05-17 01:40:44.118 20828-20828/? I/art: Late-enabling -Xcheck:jni
05-17 01:40:44.148 20828-20828/? D/Environment: 111 rawUserId = 0
05-17 01:40:44.148 20828-20828/? D/AndroidKeyStoreProvider: overseas product
05-17 01:40:44.148 20828-20842/? I/art: Debugger is no longer active
05-17 01:40:44.208 20828-20828/? W/ComponentDiscovery: Application info not found.
05-17 01:40:44.208 20828-20828/? W/ComponentDiscovery: Could not retrieve metadata, returning empty list of registrars.
05-17 01:40:44.218 20828-20828/? D/FirebaseApp: com.google.firebase.auth.FirebaseAuth is not linked. Skipping initialization.
05-17 01:40:44.218 20828-20828/? D/FirebaseApp: com.google.firebase.iid.FirebaseInstanceId is not linked. Skipping initialization.
05-17 01:40:44.218 20828-20828/? D/FirebaseApp: com.google.firebase.crash.FirebaseCrash is not linked. Skipping initialization.
05-17 01:40:44.218 20828-20828/? D/FirebaseApp: com.google.android.gms.measurement.AppMeasurement is not linked. Skipping initialization.
05-17 01:40:44.218 20828-20828/? I/FirebaseInitProvider: FirebaseApp initialization successful
05-17 01:40:44.298 20828-20828/? W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
05-17 01:40:44.308 20828-20828/? D/PhoneWindow: DEBUG_SYSTEMUI:origin statusbar style
05-17 01:40:44.308 20828-20828/? D/PhoneWindow: DEBUG_SYSTEMUI:windowDrawsFlag set
05-17 01:40:44.308 20828-20828/? D/PhoneWindow: DEBUG_SYSTEMUI:IconColor=1
05-17 01:40:44.308 20828-20828/? D/PhoneWindow: DEBUG_SYSTEMUI:StatusBarColor final set ff00574b
05-17 01:40:44.328 20828-20828/? I/art: Rejecting re-init on previously-failed class java.lang.Class<android.support.v4.view.ViewCompat$OnUnhandledKeyEventListenerWrapper>
05-17 01:40:44.328 20828-20828/? I/art: Rejecting re-init on previously-failed class java.lang.Class<android.support.v4.view.ViewCompat$OnUnhandledKeyEventListenerWrapper>
05-17 01:40:44.458 20828-20828/? I/ViewRootImpl: CPU Rendering VSync enable = true
05-17 01:40:44.458 20828-20855/? D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
05-17 01:40:44.468 20828-20828/? D/Atlas: Validating map...
05-17 01:40:44.508 20828-20855/? I/Adreno: QUALCOMM build : 814500f, If3abccc389
Build Date : 03/15/17
OpenGL ES Shader Compiler Version: XE031.06.00.03
Local Branch :
Remote Branch : refs/tags/AU_LINUX_ANDROID_LA.BR.1.3.2.C2.05.01.01.199.103
Remote Branch : NONE
Reconstruct Branch : NOTHING
05-17 01:40:44.518 20828-20855/? I/OpenGLRenderer: Initialized EGL, version 1.4
05-17 01:40:44.528 20828-20855/? D/OpenGLRenderer: Enabling debug mode 0
05-17 01:40:44.588 20828-20828/? I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@2ab3aeb3 time:26150979
05-17 01:40:45.898 20828-20828/com.example.rpi_weatherapp D/AndroidRuntime: Shutting down VM
05-17 01:40:45.898 20828-20828/com.example.rpi_weatherapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.rpi_weatherapp, PID: 20828
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
at com.example.rpi_weatherapp.MainActivity$1$1.onDataChange(MainActivity.java:53)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database@@16.0.4:75)
at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database@@16.0.4:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database@@16.0.4:55)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5399)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:927)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:722)
05-17 01:40:45.918 20828-20828/com.example.rpi_weatherapp I/Process: Sending signal. PID: 20828 SIG: 9
传感器代码(Python)
import RPi.GPIO as GPIO
from time import sleep
import datetime
from firebase import firebase
import Adafruit_DHT
import urllib2, urllib, httplib
import json
import os
from functools import partial
GPIO.setmode(GPIO.BCM)
GPIO.cleanup()
GPIO.setwarnings(False)
# Sensor should be set to Adafruit_DHT.DHT11,
# Adafruit_DHT.DHT22, or Adafruit_DHT.AM2302.
sensor = Adafruit_DHT.DHT11
# Example using a Beaglebone Black with DHT sensor
# connected to pin P8_11.
pin = 17
# Try to grab a sensor reading. Use the read_retry method which will retry up
# to 15 times to get a sensor reading (waiting 2 seconds between each retry).
humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
firebase = firebase.FirebaseApplication('https://project.firebaseio.com/', None)
#firebase.put("/dht", "/temp", "0.00")
#firebase.put("/dht", "/humidity", "0.00")
def update_firebase():
humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
if humidity is not None and temperature is not None:
sleep(5)
str_temp = ' {0:0.2f} *C '.format(temperature)
str_hum = ' {0:0.2f} %'.format(humidity)
print('Temp={0:0.1f}*C Humidity={1:0.1f}%'.format(temperature, humidity))
else:
print('Failed to get reading. Try again!')
sleep(10)
data = {"temp": temperature, "humidity": humidity}
firebase.post('/sensor_1/dht', data)
while True:
update_firebase()
#sleepTime = int(sleepTime)
sleep(5)