使用片段从回收器视图中的Firebase检索数据花费太多时间
我在主要活动中使用了两个片段,第一个片段[FirstFragment]从firebase加载数据并显示在Recycler视图中,第二个片段[uploadUserCarInformation]从用户获取数据并存储在firebase中, 当应用程序启动,然后快速加载第一个片段并显示数据时,我面临一个问题。但当从第二个片段替换第一个片段时,以及从第二个片段替换回第一个片段时,需要4到5分钟才能在recyclerView中从firebase加载数据。 请告诉我在哪里修改代码 主要活动使用片段从回收器视图中的Firebase检索数据花费太多时间,firebase,android-fragments,android-recyclerview,Firebase,Android Fragments,Android Recyclerview,我在主要活动中使用了两个片段,第一个片段[FirstFragment]从firebase加载数据并显示在Recycler视图中,第二个片段[uploadUserCarInformation]从用户获取数据并存储在firebase中, 当应用程序启动,然后快速加载第一个片段并显示数据时,我面临一个问题。但当从第二个片段替换第一个片段时,以及从第二个片段替换回第一个片段时,需要4到5分钟才能在recyclerView中从firebase加载数据。 请告诉我在哪里修改代码 主要活动 public cl
public class MainActivity extends AppCompatActivity {
FrameLayout simpleFrameLayout;
TabLayout tabLayout;
Fragment fragment1 = new FirstFragment();
Fragment fragment2 =new SecondFragment();
@SuppressLint("WrongViewCast")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get the reference of FrameLayout and TabLayout
tabLayout=findViewById(R.id.simpleTabLayout);
simpleFrameLayout = (FrameLayout) findViewById(R.id.simpleFrameLayout);
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.simpleFrameLayout, fragment1);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();
// perform setOnTabSelectedListener event on TabLayout
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
// get the current selected tab's position and replace the fragment accordingly
switch (tab.getPosition()) {
case 0:
tab.getIcon().setColorFilter(null);
fragmentReplace(fragment1,"fragment1");
break;
case 1:
fragmentReplace(fragment2,"fragment2");
break;
}
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
public void fragmentReplace(Fragment fragment,String fragmentName)
{
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.simpleFrameLayout, fragment);
Log.d("Running Fragment",fragmentName+ " is running");
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();
}
}
FirstFragment
public class FirstFragment extends Fragment {
private RecyclerView mRecyclerView;
private ImageAdapter mAdapter;
private DatabaseReference mDatabaseRef;
private List<carInformation> mUpload;
View view;
public FirstFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//retrieveAndSendData();
Log.d("Lifecycle","onCreate called");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d("Lifecycle","onCreateView called");
view=inflater.inflate(R.layout.fragment_first,container,false);
mRecyclerView=view.findViewById(R.id.recyler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return view;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Log.d("Lifecycle","onViewCreate called");
retrieveAndSendData();
}
public void retrieveAndSendData()
{
mUpload=new ArrayList<>();
mDatabaseRef= FirebaseDatabase.getInstance().getReference();
ValueEventListener valueEventListener=new ValueEventListener() {
@Override
//get firebase data using datasnapshot (read data)
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot postSnapshot : dataSnapshot.getChildren())
{
String key = postSnapshot.getKey();
DatabaseReference databaseReference=mDatabaseRef.child(key);
for (DataSnapshot child: postSnapshot.getChildren())
{
String userBookId = child.getKey();
if(userBookId.equals("city") )
{
break;
}
else
{
// Toast.makeText(getActivity(),userBookId,Toast.LENGTH_LONG).show();
databaseReference.child(userBookId).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
carInformation userInformationObj=dataSnapshot.getValue(carInformation.class);
mUpload.add(userInformationObj);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
}
}
mAdapter = new ImageAdapter(getActivity(),mUpload);
mRecyclerView.setAdapter(mAdapter);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Toast.makeText(getActivity(),databaseError.getMessage(),Toast.LENGTH_SHORT).show();
}
};
mDatabaseRef.addValueEventListener(valueEventListener);
}
public类FirstFragment扩展了Fragment{
私人回收视图mRecyclerView;
专用图像适配器mAdapter;
私有数据库引用mDatabaseRef;
私有列表多路复用器;
视图;
公共第一片段(){
//必需的空公共构造函数
}
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
//retrieveAndSendData();
Log.d(“生命周期”,“调用onCreate”);
}
@凌驾
创建视图上的公共视图(布局、充气机、视图组容器、,
Bundle savedInstanceState){
d(“生命周期”,“调用onCreateView”);
视图=充气机。充气(右布局。首先是碎片,容器,错误);
mRecyclerView=view.findviewbyd(R.id.recyler\u视图);
mRecyclerView.setHasFixedSize(true);
setLayoutManager(新的LinearLayoutManager(getActivity());
返回视图;
}
@凌驾
已创建公用void onview(@NonNull视图,@Nullable Bundle savedInstanceState){
super.onViewCreated(视图,savedInstanceState);
Log.d(“生命周期”,“调用onViewCreate”);
retrieveAndSendData();
}
public void retrieveAndSendData()
{
mUpload=newarraylist();
mDatabaseRef=FirebaseDatabase.getInstance().getReference();
ValueEventListener ValueEventListener=新的ValueEventListener(){
@凌驾
//使用datasnapshot获取firebase数据(读取数据)
public void onDataChange(@NonNull DataSnapshot DataSnapshot){
对于(DataSnapshot postSnapshot:DataSnapshot.getChildren())
{
String key=postsnashot.getKey();
DatabaseReference DatabaseReference=mDatabaseRef.child(键);
对于(DataSnapshot子项:postSnapshot.getChildren())
{
字符串userBookId=child.getKey();
if(userBookId.equals(“城市”))
{
打破
}
其他的
{
//Toast.makeText(getActivity(),userBookId,Toast.LENGTH_LONG).show();
databaseReference.child(userBookId).addValueEventListener(新的ValueEventListener(){
@凌驾
public void onDataChange(@NonNull DataSnapshot DataSnapshot){
carinfo userInformationObj=dataSnapshot.getValue(carinfo.class);
添加(userInformationObj);
}
@凌驾
已取消的公共void(@NonNull DatabaseError DatabaseError){
}
});
}
}
}
mAdapter=newImageAdapter(getActivity(),mUpload);
mRecyclerView.setAdapter(mAdapter);
}
@凌驾
已取消的公共void(@NonNull DatabaseError DatabaseError){
Toast.makeText(getActivity(),databaseError.getMessage(),Toast.LENGTH_SHORT).show();
}
};
mDatabaseRef.addValueEventListener(valueEventListener);
}
上传用户信息
public class uploadUserCarInformation extends Fragment {
View view;
FirebaseAuth firebaseAuth;
DatabaseReference databaseReference;
StorageReference storageReference;
private StorageTask mUploadTask;
ImageView imageView;
static int PICK_IMAGE=1;
Spinner spin;
// mdatabase.push().getkey() -> generate uniqe id
RadioGroup radioGroupCondition,radioGroupTransmission,radioGroupSupported;
RadioButton radioButtonCondition,radioButtonTranmission,radioButtonSupported;
String radioButtonConditionString,radioButtonSupportedString,radioButtonTransmissionString;
Button addCar,signout;
int selectedIdCondition,selectedIdTransmission,selectedIdSupported;
String ownerName,carName,phoneNuberString,countryString;
TextInputLayout name,carNamePlusModel,phoneNumber,country;
carInformation car_Information=new carInformation();
private ProgressBar progressBar;
private Uri imageUri;
String[] bankNames=new String[374];
InputStream in;
int i=0;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
view=inflater.inflate(R.layout.upload_user_car_information,container,false);
firebaseAuth=FirebaseAuth.getInstance();
storageReference=FirebaseStorage.getInstance().getReference("uploads");
name=view.findViewById(R.id.textFieldCarOwner);
carNamePlusModel=view.findViewById(R.id.textFieldCarNameModel);
phoneNumber=view.findViewById(R.id.textFieldPhoneNumber2);
addCar=view.findViewById(R.id.addCar);
signout=view.findViewById(R.id.sign_out);
progressBar=view.findViewById(R.id.progress_bar);
// progressBar.getProgressDrawable().setColorFilter(
// Color.RED, android.graphics.PorterDuff.Mode.SRC_IN);
radioGroupCondition=view.findViewById(R.id.radioGroupCarCondtion);
radioGroupSupported=view.findViewById(R.id.radioGroupCarSupport);
radioGroupTransmission=view.findViewById(R.id.radioGroupCarTransmission);
// progressBar=new ProgressBar(getActivity());
spin = view.findViewById(R.id.Countryspinner2);
imageView=(ImageView) view.findViewById(R.id.selectImage);
//imageView.setImageResource(R.drawable.select_image);
try
{
InputStream fr = this.getResources().openRawResource(R.raw.cities);
BufferedReader br = new BufferedReader(new InputStreamReader(fr));
ArrayList<String> lines=new ArrayList<String>();
String currentLine=br.readLine();
while(currentLine!=null)
{
lines.add(currentLine);
currentLine=br.readLine();
}
Collections.sort(lines);
fr.close(); //closes the stream and release the resources
for(String line : lines)
{
bankNames[i]=line;
// System.out.println(line);
i++;
}
}
catch(IOException e)
{
e.printStackTrace();
}
ArrayAdapter<String> aa=new ArrayAdapter<String>(getActivity(),android.R.layout.simple_spinner_item,bankNames);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
AdapterView.OnItemSelectedListener listener = new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
};
spin.setOnItemSelectedListener(listener);
spin.setAdapter(aa);
signout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
firebaseAuth.signOut();
Fragment fragment = new SecondFragment();
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.simpleFrameLayout, fragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.commit();
}
});
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onFileChooser();
}
});
addCar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(mUploadTask !=null && mUploadTask.isInProgress())
{
Toast.makeText(getActivity(),"Uploading Task",Toast.LENGTH_SHORT).show();
}
else
{
carImageAndDetailUploading();
}
}
});
return view;
}
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == PICK_IMAGE && resultCode == RESULT_OK && data != null && data.getData() != null)
{
imageUri = data.getData();
//A powerful image downloading and caching library and get image from library for Android
Picasso.with(getActivity()).load(imageUri).into(imageView);
}
}
private void carImageAndDetailUploading()
{
FirebaseUser user=firebaseAuth.getCurrentUser();
databaseReference= FirebaseDatabase.getInstance().getReference(user.getUid());
selectedIdCondition=radioGroupCondition.getCheckedRadioButtonId();
radioButtonCondition=view.findViewById(selectedIdCondition);
radioButtonConditionString=radioButtonCondition.getText().toString();
selectedIdSupported=radioGroupSupported.getCheckedRadioButtonId();
radioButtonSupported=view.findViewById(selectedIdSupported);
radioButtonSupportedString=radioButtonSupported.getText().toString();
selectedIdTransmission=radioGroupTransmission.getCheckedRadioButtonId();
radioButtonTranmission=view.findViewById(selectedIdTransmission);
radioButtonTransmissionString=radioButtonTranmission.getText().toString();
ownerName=name.getEditText().getText().toString().trim();
carName=carNamePlusModel.getEditText().getText().toString().trim();
phoneNuberString=phoneNumber.getEditText().getText().toString().trim();
countryString=spin.getSelectedItem().toString();
if(TextUtils.isEmpty(ownerName) || TextUtils.isEmpty(carName) || TextUtils.isEmpty(phoneNuberString) || TextUtils.isEmpty(countryString))
{
Toast.makeText(getActivity(),"Please fill the empty fields ",Toast.LENGTH_LONG).show();
return; //return stooping the function to execute further
}
else if(imageUri == null)
{
Toast.makeText(getActivity(),"No file Selected ",Toast.LENGTH_LONG).show();
return;
}
long phone=Long.parseLong(phoneNuberString);
car_Information.setCarName(carName);
car_Information.setOwnerName(ownerName);
car_Information.setUserPhoneNumber(phone);
car_Information.setCountry(countryString);
car_Information.setCarCondtion(radioButtonConditionString);
car_Information.setCarSupported(radioButtonSupportedString);
car_Information.setCarTransmission(radioButtonTransmissionString);
StorageReference fileReference=storageReference.child(System.currentTimeMillis()+ "." + getFileExtension(imageUri));
mUploadTask = fileReference.putFile(imageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//below code user can see 100 % progress bar for 5 sec
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
progressBar.setProgress(0);
}
},5000);
String uniqueKey=databaseReference.push().getKey();
Task<Uri> urlTask = taskSnapshot.getStorage().getDownloadUrl();
while (!urlTask.isSuccessful());
Uri downloadUrl = urlTask.getResult();
car_Information.setImageUrl(downloadUrl.toString());
car_Information.setUnique_key(uniqueKey);
// databaseReference.child("car details"+car_Information.getUnique_key());
// databaseReference.child("car details"+car_Information.getUnique_key()).setValue(car_Information);
databaseReference.child(car_Information.getUnique_key());
databaseReference.child(car_Information.getUnique_key()).setValue(car_Information);
Toast.makeText(getActivity(),"Successfully Upload",Toast.LENGTH_SHORT).show();
clear_editText();
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(getActivity(),e.getMessage(),Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
@Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress=(100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
progressBar.setProgress((int) progress);
}
});
}
private void onFileChooser()
{
Intent intent =new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent,PICK_IMAGE);
//startActivityForResult(Intent.createChooser(intent,"Select Picture"),PICK_IMAGE);
}
private String getFileExtension(Uri uri)
{
//this method for get file extension
ContentResolver cR=getActivity().getContentResolver();
MimeTypeMap mime=MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(cR.getType(uri));
}
private void clear_editText()
{
name.getEditText().setText(" ");
carNamePlusModel.getEditText().setText(" ");
phoneNumber.getEditText().setText(" ");
}
}
public类uploadUserCarInformation扩展片段{
视图;
FirebaseAuth FirebaseAuth;
数据库参考数据库参考;
StorageReference-StorageReference;
专用存储任务mUploadTask;
图像视图图像视图;
静态int PICK_IMAGE=1;
旋转器旋转;
//mdatabase.push().getkey()->生成uniqe id
支持的放射组放射组条件、放射组传输、放射组;
RadioButton RadioButton条件、RadioButton传输、RadioButton支持;
字符串radioButtonConditionString、RadioButtonSupportString、radioButtonTransmissionString;
按钮addCar,注销;
int selectedCondition,selectedTransmission,selectedSupported;
字符串所有者名称、carName、phoneNuberString、countryString;
TextInputLayout名称、carNamePlusModel、电话号码、国家/地区;
carInformation car_Information=新carInformation();
私人ProgressBar ProgressBar;
私有Uri-imageUri;
字符串[]bankNames=新字符串[374];
输入流输入;
int i=0;
@凌驾
创建时的公共void(@Nullable Bundle savedInstanceState){
super.onCreate(savedInstanceState);
}
@RequiresApi(api=Build.VERSION\u CODES.O)
@凌驾
创建视图时的公共视图(@NonNull LayoutInflater inflater、@Nullable ViewGroup container、@Nullable Bundle savedInstanceState){
视图=充气机。充气(右布局。上传用户车辆信息,容器,错误);
firebaseAuth=firebaseAuth.getInstance();
storageReference=FirebaseStorage.getInstance().getReference(“上载”);
name=view.findviewbyd(R.id.textFieldCarOwner);
carNamePlusModel=view.findviewbyd(R.id.textfieldcanamemodel);
phoneNumber=view.findViewById(R.id.textFieldPhoneNumber2