无法在firebase上的对象中创建一个数组

时间:2017-02-12 23:27:44

标签: android firebase firebase-realtime-database

我有2个字符串值,1个int值和1个数组值的对象。当我在firebase上添加对象时,我在数据库中看到字符串和int值,但不是数组。请有人帮忙,如何在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;
    }
}

1 个答案:

答案 0 :(得分:1)

图像字节的上载是在工作线程上执行的,需要一些时间才能将数据传输到Firebase服务器。用于将URL添加到数组列表OnSuccessListener的{​​{1}}异步触发,很久之后执行以下代码:

slike2

结果是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(); 已正确存储,但不包含网址列表,因为item为空。

Tasks类提供了创建任务的方法,该任务在任务集合完成时完成。考虑使用这些功能来重写代码。