Home > OS >  How can i store uri.toString to my java class?
How can i store uri.toString to my java class?

Time:11-03

I want to store a uri to my donation.java class so that ill be able to fetch an image from firebase storage and display it on a cardview. However uri.toString is highlighted red and shows a "Cannot resolve constructor 'donation(java.lang.String)'"

donate.java

package com.example.byete_hunger_mobileapp;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.RecyclerView;

import android.app.Activity;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.media.Image;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.byete_hunger_mobileapp.databinding.ActivityDonateBinding;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.snackbar.Snackbar;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FileDownloadTask;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

public class donate extends AppCompatActivity {

    Spinner spinner;
    Button Submit;
    ImageView back, account, chooseImage;
    EditText weight, datePurchased, dateExpired, contactNo, notes;
    DatabaseReference dbRef;
    FirebaseStorage storage;
    StorageReference storageRef;
    FirebaseAuth fAuth;
    FirebaseUser currentUser;
    RecyclerView recyclerView;
    Timer timer;
    ActivityResultLauncher<String> launcher;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_donate);

        chooseImage = findViewById(R.id.donate_uploadImage);
        back = findViewById(R.id.donate_back_button);
        account = findViewById(R.id.donate_account_page_icon);
        recyclerView = findViewById(R.id.rv_donationstracker);
        spinner = findViewById(R.id.spinner_donate);
        weight = findViewById(R.id.et_donate_weight);
        datePurchased = findViewById(R.id.et_donate_donatePurchased);
        dateExpired = findViewById(R.id.et_donate_donateExpired);
        contactNo = findViewById(R.id.et_donate_contactNo);
        notes = findViewById(R.id.et_donate_notes);
        Submit = findViewById(R.id.button4_donate_submit);

        fAuth = FirebaseAuth.getInstance();
        currentUser = fAuth.getCurrentUser();
        dbRef = FirebaseDatabase.getInstance().getReference();
        storage = FirebaseStorage.getInstance();
        storageRef = storage.getReference();

        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.DonationType, android.R.layout.simple_spinner_dropdown_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);

        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        account.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(donate.this, Account.class));
            }
        });

        //choose image in files
        chooseImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                launcher.launch("image/*");
            }
        });

        launcher = registerForActivityResult(new ActivityResultContracts.GetContent(), new ActivityResultCallback<Uri>() {
            @Override
            public void onActivityResult(Uri result) {
                chooseImage.setImageURI(result);

                Submit.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        InsertData();
                        timer = new Timer();
                        timer.schedule(new TimerTask() {
                            @Override
                            public void run() {
                                finish();
                            }
                        }, 1000);
                    }

                    public void InsertData() {
                        String type = spinner.getSelectedItem().toString();
                        String wt = weight.getText().toString();
                        String dP = datePurchased.getText().toString();
                        String dE = dateExpired.getText().toString();
                        String cN = contactNo.getText().toString();
                        String nts = notes.getText().toString();
                        String id = dbRef.push().getKey();
                        String imageUrl = "";

                        //show when new card was added to donations
                        Date date = new Date();
                        Date time = new Date();
                        SimpleDateFormat formatter = new SimpleDateFormat("dd MMMM yyyy");
                        SimpleDateFormat formatter2 = new SimpleDateFormat("hh:mm:ss");
                        String dateAdded = formatter.format(date);
                        String dateAddedTime = formatter2.format(time);

                        donation Donation = new donation(type, wt, dP, dE, cN, nts, id, dateAdded, dateAddedTime,imageUrl);

                        dbRef.child("Users").child(currentUser.getUid()).child("donation").child(id).setValue(Donation).addOnCompleteListener(new OnCompleteListener<Void>() {
                            @Override
                            public void onComplete(@NonNull Task<Void> task) {
                                if(task.isSuccessful()){
                                    Toast.makeText(donate.this,"Donation details inserted", Toast.LENGTH_LONG).show();
                                }
                            }
                        });

                        // firebase storage folder location
                        StorageReference riversRef = storageRef.child("images/").child(currentUser.getUid()).child(date.toString());

                        // uploads image to firebase storage
                        riversRef.child(id   "."   GetFileExtension(result)).putFile(result).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                            @Override
                            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                                riversRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                                    @Override
                                    public void onSuccess(Uri uri) {
                                        donation image = new donation(uri.toString());
                                        dbRef.child("Users").child(currentUser.getUid()).child("donation").child(id).child("image").setValue(image);
                                    }
                                });
                                Toast.makeText(getApplicationContext(), "Image Uploaded.", Toast.LENGTH_LONG).show();
                            }
                        }).addOnFailureListener(exception -> Toast.makeText(getApplicationContext(), "Failed to Upload Image.", Toast.LENGTH_LONG).show());
                    }

                });
            }
        });

    }

    public String GetFileExtension(Uri uri){
        ContentResolver contentResolver = getContentResolver();
        MimeTypeMap map = MimeTypeMap.getSingleton();
        return map.getExtensionFromMimeType(contentResolver.getType(uri));
    }

}

donation.java

package com.example.byete_hunger_mobileapp;

import android.net.Uri;

import com.google.android.gms.tasks.Task;

public class donation {
    private String type, weight, datePurchased, dateExpired, contactNo, notes, id, dateAdded, dateAddedTime, imageUrl;


    public donation() {
    }

    public donation(String type, String weight, String datePurchased, String dateExpired, String contactNo, String notes, String id, String dateAdded, String dateAddedTime, String imageUrl) {
        this.type = type;
        this.weight = weight;
        this.datePurchased = datePurchased;
        this.dateExpired = dateExpired;
        this.contactNo = contactNo;
        this.notes = notes;
        this.id = id;
        this.dateAdded = dateAdded;
        this.dateAddedTime = dateAddedTime;
        this.imageUrl = imageUrl;
    }


    public String getType() {return type;}

    public String getWeight() {
        return weight;
    }

    public String getDatePurchased() {return datePurchased;}

    public String getDateExpired() {
        return dateExpired;
    }

    public String getContactNo() {
        return contactNo;
    }

    public String getNotes() {
        return notes;
    }

    public String getId() {
        return id;
    }

    public String getDateAdded() {
        return dateAdded;
    }

    public String getDateAddedTime() {
        return dateAddedTime;
    }

    public String getImageUrl() {
        return imageUrl;
    }


}

I've tried storing the uri to a different class which was successful but I had to make another list for myAdapter which added more problems to the table.

MyAdapter.java

package com.example.byete_hunger_mobileapp;

import android.content.Context;
import android.content.Intent;
import android.transition.AutoTransition;
import android.transition.TransitionManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;

import java.util.ArrayList;
import java.util.List;

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
    Context context;
    ArrayList<donation> list;

    public MyAdapter(Context context, ArrayList<donation> list) {
        this.context = context;
        this.list = list;
    }

    @NonNull
    @Override
    public MyAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(context).inflate(R.layout.donation_card, parent, false);
        return new MyAdapter.MyViewHolder(v);
    }

    @Override
    public void onBindViewHolder(@NonNull MyAdapter.MyViewHolder holder, int position) {
        donation Donation = list.get(position);

        holder.type.setText(Donation.getType());
        holder.weight.setText(Donation.getWeight());
        holder.datePurchased.setText(Donation.getDatePurchased());
        holder.dateExpired.setText(Donation.getDateExpired());
        holder.notes.setText(Donation.getNotes());
        holder.id.setText(Donation.getId());
        holder.dateAdded.setText(Donation.getDateAdded());
        holder.dateAddedTime.setText(Donation.getDateAddedTime());
        Glide.with(context).load(Donation.getImageUrl()).into(holder.donationCardImage);
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {

        TextView type, weight, datePurchased, dateExpired, notes, id, dateAdded, dateAddedTime;
        Button track;
        CardView cardView;
        ImageView donationCardImage;

        RelativeLayout donationcardcontent;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);

            type = itemView.findViewById(R.id.tv_donationcard_typedesc);
            weight = itemView.findViewById(R.id.tv_donationcard_weightdesc);
            datePurchased = itemView.findViewById(R.id.tv_donationcard_dateofpurchasedesc);
            dateExpired = itemView.findViewById(R.id.tv_donationcard_expirationdatedesc);
            notes = itemView.findViewById(R.id.tv_donationcard_notesdesc);
            id = itemView.findViewById(R.id.tv_donationcard_uidCode);
            dateAdded = itemView.findViewById(R.id.tv_donationcard_dateadded);
            dateAddedTime = itemView.findViewById(R.id.tv_donationcard_dateaddedTime);
            donationCardImage = itemView.findViewById(R.id.iV_donationcard);

            track = itemView.findViewById(R.id.btn_donationcard_track);

            cardView = itemView.findViewById(R.id.cv_donationCard);
            donationcardcontent = itemView.findViewById(R.id.rl_donationcard_content);


            track.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(cardView.getContext(),statustracker.class);
                    cardView.getContext().startActivity(intent);
                }
            });

            // donation card expands and collapses
            cardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (donationcardcontent.getVisibility() == View.GONE) {
                    TransitionManager.beginDelayedTransition(cardView, new AutoTransition());
                    donationcardcontent.setVisibility(View.VISIBLE);
                } else if (donationcardcontent.getVisibility() != View.GONE) {
                    TransitionManager.beginDelayedTransition(cardView, new AutoTransition());
                    donationcardcontent.setVisibility(View.GONE);
                }
            }
        });
        }
    }
}

So I want to know if there's a possible work around for storing the uri to my donation class.

CodePudding user response:

The line

donation image = new donation(uri.toString());

will create a new donation from String. Probably this is not what is wanted. If the goal is to set imageUrl after the image is uploaded, then replace this line with:

Donation.setImageUrl(uri.toString());

And in donation.java, add setter for imageUrl:

public void setImageUrl(String url) {
    this.imageUrl = url;
}
  • Related