Reputation: 1299
I have object with 2 string values, 1 int value and 1 array value. And when I add object on firebase, I see strings and int values in database,but not the array. Please, anybody help, how to add object with array value on firebase?
public class UploaderActivity extends AppCompatActivity {
EditText ime;
EditText opis;
EditText cena;
Button slikaj;
Button dodaj;
ArrayList<Uri> slike=new ArrayList<>();
ArrayList<String> slike2=new ArrayList<>();
UploadTask uploadTask;
FirebaseStorage storage;
StorageReference storageRef;
StorageReference mountainImagesRef;
DatabaseReference myRef;
private FirebaseAuth mFirebaseAuth;
private FirebaseUser mFirebaseUser;
private DatabaseReference mDatabase;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_uploader);
mFirebaseAuth = FirebaseAuth.getInstance();
mFirebaseUser = mFirebaseAuth.getCurrentUser();
mDatabase = FirebaseDatabase.getInstance().getReference();
storage = FirebaseStorage.getInstance();
storageRef = storage.getReferenceFromUrl("gs://materialdesign-fb467.appspot.com");
ime= (EditText) findViewById(R.id.ime);
opis= (EditText) findViewById(R.id.opis);
cena= (EditText) findViewById(R.id.cena);
slikaj= (Button) findViewById(R.id.slikaj);
dodaj= (Button) findViewById(R.id.dodaj);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==1 && resultCode==RESULT_OK && data!=null) {
Uri selectedImage = data.getData();
slike.add(selectedImage);
}
}
public void slikaj(View view){
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i,1);
}
public void dodaj(View view){
final ArrayList<Image> images;
try {
for (int i = 0; i < slike.size(); i++) {
Bitmap bitmapImage = MediaStore.Images.Media.getBitmap(this.getContentResolver(), slike.get(i));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmapImage.compress(Bitmap.CompressFormat.JPEG, 50, baos);
byte[] dataBytes = baos.toByteArray();
String pic = "Image" + i + ".jpg";
mountainImagesRef = storageRef.child(usernameFromEmail(mFirebaseUser.getEmail())).child(ime.getText().toString()).child(pic);
uploadTask = mountainImagesRef.putBytes(dataBytes);
uploadTask.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
// Handle unsuccessful uploads
Toast.makeText(UploaderActivity.this, "There was an error - please try again!", Toast.LENGTH_SHORT).show();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
Uri downloadUrl = taskSnapshot.getDownloadUrl();
Image img = new Image(downloadUrl.toString());
Toast.makeText(UploaderActivity.this, downloadUrl.toString(), Toast.LENGTH_SHORT).show();
slike2.add(img.getUrl());
}
} );
}
//DatabaseReference myRef = FirebaseDatabase.getInstance().getReference().child("trails").child(usernameFromEmail(mFirebaseUser.getEmail())).child(trail.getUnique_id()).push();
myRef = FirebaseDatabase.getInstance().getReference().child("Items").child(usernameFromEmail(mFirebaseUser.getEmail())).child(ime.getText().toString()).push();
Item item = new Item(ime.getText().toString(),opis.getText().toString(),Integer.parseInt(cena.getText().toString()),slike2);
myRef.setValue(item);
Toast.makeText(UploaderActivity.this, "Your image has been posted!", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
};
private String usernameFromEmail(String email) {
if (email.contains("@")) {
return email.split("@")[0];
} else {
return email;
}
}
}
public class Item {
private String name;
private String desription;
private int price;
private ArrayList<String> url;
public Item(){}
public Item(String name, String desription, int price, ArrayList<String> url){
this.name=name;
this.desription=desription;
this.price=price;
this.url=url;
}
public Item(String name,String desription,int price){
this.name=name;
this.desription=desription;
this.price=price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDesription() {
return desription;
}
public void setDesription(String desription) {
this.desription = desription;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public ArrayList<String> getUrl() {
return url;
}
public void setUrl(ArrayList<String> url) {
this.url = url;
}
}
Upvotes: 0
Views: 254
Reputation: 38299
The upload of the image bytes is performed on a worker thread and takes some time to transfer the data to the Firebase servers. The OnSuccessListener
that you use to add URLs to array list slike2
fires asynchronously, long after this code that follows it executes:
Item item = new Item(ime.getText().toString(),opis.getText().toString(),
Integer.parseInt(cena.getText().toString()),slike2);
myRef.setValue(item);
Toast.makeText(UploaderActivity.this, "Your image has been posted!",
Toast.LENGTH_SHORT).show();
The result is that item
is stored correctly, but does not contain the list of URLs, because slike2
is empty.
The Tasks class provides methods to create a task that completes when a collection of tasks completes. Consider using those capabilities to rework your code.
Upvotes: 1