Recyclerview不显示数据

时间:2019-05-07 17:13:55

标签: java android

我正在设置我的recyclerview以从Firebase存储和Firebase数据库检索数据。但是存储中的图像没有出现。

我的适配器无法更新的另一个问题

我已经尝试过firebaseui recyler以及其他实现recyclerview来检索图像的方法。

我有以下链接示例: https://github.com/mitchtabian/Recyclerview https://github.com/jdulal/AndroidUploadRetrieveimagesusingFirebaseStorage/tree/83d96192f92c2b96288c30234f3a3eb09e928228

这是我的模型类Sample.java

public class Sample {
 private String SampleID;
 private String SampleDate;
 private String SampleTime;
 private String SampleLocation;
 private String SampleImageUrl;

 public Sample() {}

 public Sample(String sampleID, String sampleDate, String sampleTime, String sampleLocation, String sampleImageUrl) {
  SampleID = sampleID;
  SampleDate = sampleDate;
  SampleTime = sampleTime;
  SampleLocation = sampleLocation;
  SampleImageUrl = sampleImageUrl;
 }

 public String getSampleID() {
  return SampleID;
 }
 public String getSampleImageUrl() {
  return SampleImageUrl;
 }

 public String getSampleDate() {
  return SampleDate;
 }

 public String getSampleTime() {
  return SampleTime;
 }

 public String getSampleLocation() {
  return SampleLocation;
 }

 public void setSampleID(String sampleID) {
  SampleID = sampleID;
 }

 public void setSampleDate(String sampleDate) {
  SampleDate = sampleDate;
 }

 public void setSampleTime(String sampleTime) {
  SampleTime = sampleTime;
 }

 public void setSampleLocation(String sampleLocation) {
  SampleLocation = sampleLocation;
 }

 public void setSampleImageUrl(String sampleImageUrl) {
  SampleImageUrl = sampleImageUrl;
 }
}

适配器类SampleListAdater.java

public class SampleListAdapter extends RecyclerView.Adapter < SampleListAdapter.ImageViewHolder > {
 private Context mContext;
 private List < Sample > mSample;

 public SampleListAdapter(Context context, List < Sample > samples) {
  mContext = context;
  mSample = samples;
 }

 @NonNull
 @Override
 public ImageViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
  View v = LayoutInflater.from(mContext).inflate(R.layout.activity_sample_list_item, viewGroup, false);
  return new ImageViewHolder(v);
 }

 @Override
 public void onBindViewHolder(@NonNull ImageViewHolder imageViewHolder, int position) {
  Sample sample = mSample.get(position);
  imageViewHolder.textViewID.setText(sample.getSampleID());
  Picasso.get()
   .load(sample.getSampleImageUrl())
   .placeholder(R.drawable.photo)
   .fit()
   .centerCrop()
   .into(imageViewHolder.imageView);
 }

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



 class ImageViewHolder extends RecyclerView.ViewHolder {
  TextView textViewID;
  ImageView imageView;

  public ImageViewHolder(View itemView) {
   super(itemView);

   textViewID = itemView.findViewById(R.id.text_view_id);
   imageView = itemView.findViewById(R.id.image_view_upload);
  }
 }
}

这是我的活动代码SampleList.java

public class SampleList extends AppCompatActivity
{
    DatabaseReference mRef;
    StorageReference storageRef;
    RecyclerView recyclerView;
    ArrayList<Sample> list;
    SampleListAdapter sampleListAdapter;

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

        recyclerView = findViewById(R.id.ImgViewer);
        recyclerView.setHasFixedSize(true);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(manager);
        recyclerView.setHasFixedSize(true);

        storageRef = FirebaseStorage.getInstance().getReference().child("Sample Images/");
        mRef = FirebaseDatabase.getInstance().getReference().child("Samples");


        mRef.addValueEventListener(new ValueEventListener()
        {
             @Override
             public void onDataChange(@NonNull DataSnapshot dataSnapshot)
             {
             list = new ArrayList<Sample>();

                for(DataSnapshot dataSnapshot1: dataSnapshot.getChildren())
                {
                    Sample s= dataSnapshot1.getValue(Sample.class);
                    list.add(s);
                }
                sampleListAdapter = new SampleListAdapter(SampleList.this,list);
                recyclerView.setAdapter(sampleListAdapter);
                sampleListAdapter.notifyDataSetChanged();
             }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError)
            {
                Toast.makeText(SampleList.this, "Opsss.... Something is wrong", Toast.LENGTH_SHORT).show();
            }
        });
    }
}

这是将数据添加到Firebase数据库的活动

public class RegisterSample extends AppCompatActivity implements DatePickerDialog.OnDateSetListener, TimePickerDialog.OnTimeSetListener
{

    public Button btn_datePicker;
    public Button btn_timePicker;
    public Button btn_Camera;
    public Button btn_AddSam;

    private EditText SamID, DateText, TimeText, LocText;
    private ImageView SamImage;


    private int REQUEST_CAMERA = 0, SELECT_FILE =1;
    private String userChooseTask;

    Uri FilePathUri;

    DatabaseReference databaseReference;
    StorageReference storageReference;
    String Storage_Path = "Sample Images/";
    String Database_Path = "Samples";
    ProgressDialog progressDialog ;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register_sample);
        if(getSupportActionBar() != null){
            getSupportActionBar().setTitle("Sample Registration");
        }

        SamID = findViewById(R.id.SamID);
        DateText = findViewById(R.id.DateText);
        TimeText = findViewById(R.id.TimeText);
        LocText = findViewById(R.id.LocText);

        databaseReference = FirebaseDatabase.getInstance().getReference(Database_Path);
        storageReference = FirebaseStorage.getInstance().getReference();

        progressDialog = new ProgressDialog(RegisterSample.this);

        btn_AddSam = findViewById(R.id.btn_AddSam);
        btn_AddSam.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
                addSample();
            }
        });

        btn_datePicker = findViewById(R.id.btn_datepicker);
        btn_datePicker.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogFragment datePicker = new DatePickerFragment();
                datePicker.show(getSupportFragmentManager(), "date picker");
            }
        });

        btn_timePicker = findViewById(R.id.btn_timepicker);
        btn_timePicker.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogFragment timePicker = new TimePickerFragment();
                timePicker.show(getSupportFragmentManager(), "time picker");
            }
        });


        btn_Camera = findViewById(R.id.btn_Camera);
        btn_Camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
                selectImage();
            }
        });

        SamImage = findViewById(R.id.SamImage);
    }

    @Override
    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
        Calendar c = Calendar.getInstance();
        c.set(Calendar.YEAR, year);
        c.set(Calendar.MONTH, month);
        c.set(Calendar.DAY_OF_MONTH, dayOfMonth);
        String currentDateString = DateFormat.getDateInstance().format(c.getTime());

        TextView DateText = findViewById(R.id.DateText);
        DateText.setText(currentDateString);


    }

    @Override
    public void onTimeSet(TimePicker view, int hourOfDay, int minute ) {

        TextView TimeText = findViewById(R.id.TimeText);
        TimeText.setText(String.format("%02d:%02d", hourOfDay, minute));
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case Utility.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    if (userChooseTask.equals("Take Photo"))
                        cameraIntent();
                    else if (userChooseTask.equals("Choose from Gallery"))
                        galleryIntent();
                } else {
                    Toast.makeText(RegisterSample.this, "Access Denied",Toast.LENGTH_LONG).show();
                }
                break;
        }
    }

    private void selectImage() {
        final CharSequence[] items = {"Take Photo", "Choose from Gallery",
                "Cancel"};

        AlertDialog.Builder builder = new AlertDialog.Builder(RegisterSample.this);
        builder.setTitle("Add Photo");
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                boolean result = Utility.checkPermission(RegisterSample.this);

                if (items[item].equals("Take Photo")) {
                    userChooseTask = "Take Photo";
                    if (result)
                        cameraIntent();
                } else if (items[item].equals("Choose from Gallery")) {
                    userChooseTask = "Choose from Gallery";
                    if (result)
                        galleryIntent();
                } else if (items[item].equals("Cancel")) {
                    dialog.dismiss();
                }
            }
        });
        builder.show();
    }

    private void galleryIntent() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);//
        startActivityForResult(Intent.createChooser(intent, "Select File"), SELECT_FILE );
    }

    private void cameraIntent() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent, REQUEST_CAMERA);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == SELECT_FILE)
                onSelectFromGalleryResult(requestCode, resultCode, data);
            else if (requestCode == REQUEST_CAMERA)
                onCaptureImageResult(requestCode, resultCode, data);
        }
    }


    private void onCaptureImageResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CAMERA && resultCode == RESULT_OK && data != null && data.getData() != null)
        {
            FilePathUri = data.getData();

            try
            {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), FilePathUri);
                SamImage.setImageBitmap(bitmap);
            }
            catch (FileNotFoundException e)
            {
                e.printStackTrace();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }


    @SuppressWarnings("deprecation")
    protected void onSelectFromGalleryResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == SELECT_FILE && resultCode == RESULT_OK && data != null && data.getData() != null)
        {

            FilePathUri = data.getData();

            try
            {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), FilePathUri);
                SamImage.setImageBitmap(bitmap);
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }

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



    public void addSample()
    {
        if (FilePathUri != null)
        {
            progressDialog.setTitle("Image is Uploading...");
            progressDialog.show();
            StorageReference storageReference2nd = storageReference.child(Storage_Path + System.currentTimeMillis() + "." + GetFileExtension(FilePathUri));

            storageReference2nd.putFile(FilePathUri)
                    .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>()
                    {
                        @Override
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot)
                        {
                            String sampleID = SamID.getText().toString().trim();
                            String sampleDate = DateText.getText().toString().trim();
                            String sampleTime = TimeText.getText().toString().trim();
                            String sampleLocation = LocText.getText().toString().trim();

                            progressDialog.dismiss();

                            Toast.makeText(getApplicationContext(), "Image Uploaded Successfully ", Toast.LENGTH_LONG).show();

                            @SuppressWarnings("VisibleForTests")
                            Sample sample = new Sample (sampleID,sampleDate,sampleTime,sampleLocation, taskSnapshot.getStorage().getDownloadUrl().toString());
                            databaseReference.child(sampleID).setValue(sample);
                            SamID.setText("");
                            DateText.setText("");
                            TimeText.setText("");
                            LocText.setText("");

                            Intent intent = new Intent(RegisterSample.this, SampleList.class);
                            startActivity(intent);



                        }

                    })

                    .addOnFailureListener(new OnFailureListener()
                    {
                        @Override
                        public void onFailure(@NonNull Exception exception)
                        {

                            progressDialog.dismiss();
                            Toast.makeText(RegisterSample.this, exception.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    })

                    .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>()
                    {
                        @Override
                        public void onProgress(UploadTask.TaskSnapshot taskSnapshot)
                        {

                            // Setting progressDialog Title.
                            progressDialog.setTitle("Image is Uploading...");

                        }
                    });

        }
        else
        {
            Toast.makeText(RegisterSample.this, "Please insert corresponding field", Toast.LENGTH_LONG).show();
        }
    }
}

我的数据库的屏幕截图: firebase database structure firebase storage structure

我需要图片显示在回收者视图活动中。

0 个答案:

没有答案