我正在尝试将编辑文本中的值插入firebase。这是MainActivity代码和XML代码。
MainActivity.java
public class MainActivity extends AppCompatActivity {
private FirebaseDatabase database;
private DatabaseReference myRef;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void buttonClicked(View view){
database = FirebaseDatabase.getInstance();
myRef = database.getReference().child("Users");
EditText editname = (EditText)findViewById(R.id.name);
String name_content = editname.getText().toString();
myRef = database.getReference();
myRef.setValue(name_content);
}
}
XML代码:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:orientation="vertical"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.suzancruz.firebasesample.MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Name"
android:id="@+id/name"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="buttonClicked"
android:text="Enter Values"
/>
我无法弄清问题究竟是什么。在编辑文本中输入值后单击按钮后,应用程序崩溃并在日志中出现以下错误:尝试在空对象上调用虚拟方法'android.text.Editable android.widget.EditText.getText()'参考
答案 0 :(得分:0)
请尝试在EditText
中保留对onCreate()
的引用。每次单击按钮时查找EditText
视图都很昂贵。
public class MainActivity extends AppCompatActivity {
private FirebaseDatabase database;
private DatabaseReference myRef;
private EditText editname;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editname = (EditText)findViewById(R.id.name);
}
public void buttonClicked(View view){
//...
String name_content = editname.getText().toString();
//...
}
}
如果您坚持在单击按钮时找到EditText
,则可以这样做:
public void buttonClicked(View view){
//...
EditText editname = (EditText)view.getRootView().findViewById(R.id.name);
String name_content = editname.getText().toString();
//...
}