【发布时间】:2020-05-24 17:48:42
【问题描述】:
我的第一个方法deviceList 能够成功运行,并且我能够在变量String.id 中存储一个值。然后我尝试在我的第二种方法addReview1 中使用该字符串在我的数据库搜索中实现该字符串。但是,方法addReview1 是通过单击按钮请求的。我尝试将我的第二种方法设置为addRview1 (String id),但是按钮 onclick 不起作用,应用程序会崩溃。因此,我需要帮助将字符串 ID 从deviceList 发送到addReview1。
方法设备列表
public void deviceList (View V){
db.collection("devices")
.whereEqualTo("name", value)
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if(task.isSuccessful()){
for (final QueryDocumentSnapshot document : task.getResult()){
Log.i("DeviceId", document.getId());
String id = document.getId();
}
}
else
{
Log.i("Devices","Error" + task.getException());
Toast.makeText(getBaseContext(),"Error retrieving getting device names",Toast.LENGTH_LONG).show();
}
}
});
};
方法addReview1
public void addReview1 (View V){
Name = (EditText) findViewById(R.id.Name);
Content = (EditText) findViewById(R.id.Content);
Rating = (EditText) findViewById(R.id.Rating);
button4 = (Button) findViewById(R.id.button4);
Map<String, Object> review = new HashMap<>();
review.put("date", new Date());
review.put("name", Name.getText().toString());
review.put("content", Content.getText().toString());
review.put("rating", Integer.parseInt(Rating.getText().toString()));
db.collection("devices").document("1").collection("reviews").add(review)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
@Override
public void onSuccess(DocumentReference documentReference) {
Toast.makeText(getApplicationContext(), "Comment added", Toast.LENGTH_LONG).show();
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
});
};
【问题讨论】:
-
logcat 说什么错误?以及在哪一行。
-
只需将字符串变量设为全局变量或获取值的位置将其放在共享首选项或其他此类区域中,您可以在其中随时随地访问变量
-
public class MyClass { public static String id = null; public void deviceList (View V){ ... id = document.getId(); ... } ... }。现在你可以在任何地方使用这个变量了。