打招呼,我很难在ValueEventListener中为变量设置int值,并在ValueEventListener之外获取要检查的方法的值为value == 1
,该方法将为return 1
,否则返回0
我已经尝试了多种方法,例如通过SharedPreferences保存值,将值设置为Textview并从textview调用,但是方法仍然总是return 0
,因为它无法读取在ValueEventListener中设置的值。任何帮助都非常感谢。谢谢
这里是我的代码
int status = 0;
protected void onCreate(Bundle savedInstanceState) {
...
btnSync_in.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (getCustomerList() == 1) {
msg = msg + "Get customer success \n";
} else {
msg = msg + "Get customer unsuccessful \n";
}
AlertDialog.Builder statusDialog = new AlertDialog.Builder(SyncActivity.this);
statusDialog.setPositiveButton("OK", null);
statusDialog.setTitle("Status");
statusDialog.setMessage(msg);
statusDialog.show();
msg = "";
}
});
}
将返回int的方法
private int getCustomerList() {
urlRef = myRef.child("...");
urlRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
...
StringRequest stringRequest = new StringRequest(Request.Method.GET, customerURL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
status = 1; //here my problem, value assign here is success
try {
...
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
...
status = 0; // here if unsuccessful
}
});
RequestQueue requestQueue = Volley.newRequestQueue(SyncActivity.this);
requestQueue.add(stringRequest);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
...
}
});
if (status == 1) {
return 1;
} else {
return 0;
}
}
答案 0 :(得分:0)
一种更好的方式为什么不在 AlertDialog
方法中显示getCustomerList()
像这样呼叫您的getCustomerList()
btnSync_in.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getCustomerList();
}
});
然后将您的 AlertDialog
这样添加到getCustomerList()
内
示例代码
private void getCustomerList() {
AlertDialog.Builder statusDialog = new AlertDialog.Builder(SyncActivity.this);
statusDialog.setPositiveButton("OK", null);
statusDialog.setTitle("Status");
urlRef = myRef.child("...");
urlRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
...
StringRequest stringRequest = new StringRequest(Request.Method.GET, customerURL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
msg = msg + "Get customer success \n";
statusDialog.setMessage(msg);
statusDialog.show();
msg = "";
try {
...
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
...
msg = msg + "Get customer unsuccessful \n";
statusDialog.setMessage(msg);
statusDialog.show();
msg = "";
}
});
RequestQueue requestQueue = Volley.newRequestQueue(SyncActivity.this);
requestQueue.add(stringRequest);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
...
}
});
}