Я пытаюсь вызвать "getVenueZipcode" изнутри onClick, который находится внутри setOnclickListener. Я ожидаю, что будет вызван "getVenueZipcode" и будет напечатано "zipcode [0] =" + zipcode [0] "перед" ZIPCODE = "+ zipcode. Однако это не так. Распечатывается ZIPCODE = null и затем zipcode [0] = напечатано 12345.
Так работает onClick Listener или я что-то упустил?
mAdd_gigEvent_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
gigEvent = new GigEvent();
mBand_name_editText = findViewById(R.id.add_band_name_editText);
mVenue_name_editText = findViewById(R.id.add_venue_name_editText);
mDate_editText = findViewById(R.id.add_date_editText);
mTime_editText = findViewById(R.id.add_time_editText);
String venue_name = mVenue_name_editText.getText().toString();
String zipcode = getVenueZipcode(venue_name);
System.out.println("ZIPCODE = " + zipcode);
gigEvent.setGigAuth(userID);
gigEvent.setBand(mBand_name_editText.getText().toString());
gigEvent.setVenue(mVenue_name_editText.getText().toString());
gigEvent.setDate(mDate_editText.getText().toString());
gigEvent.setTime(mTime_editText.getText().toString());
gigEvent.setZipcode(zipcode);
mDatabase.child(userID).setValue(gigEvent);
Toast.makeText(AddGigEvent.this, "Gig/Event added!",
Toast.LENGTH_LONG).show();
startActivity(new Intent(AddGigEvent.this, Search.class));
}
});
}
public String getVenueZipcode(String name) {
final Query venue_query;
final String v_name = name;
final String[] zipcode = new String[1];
DatabaseReference mDatabase =
FirebaseDatabase.getInstance().getReference().child("venues");
venue_query = mDatabase.orderByChild("uid");
venue_query.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()) {
if(snapshot.child("name").getValue().toString().equals(v_name)) {
zipcode[0] = snapshot.child("venue_zipcode").getValue().toString();
System.out.println("zipcode[0] = " + zipcode[0]);
return;
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
return zipcode[0];
}