我想从Firebase中获取数据并以double[]
的形式输入。这是我在Firebase上的数据:
我只想获取dataSet
上的数据,或者,我想以List<Double>
的身份进入,那么我该如何解决呢?
已编辑
public class ListFragment extends BaseFragment implements ListImageAdapter.OnItemClickListener {
public static final String TAG = "ListFragment";
private RecyclerView recyclerViewImages;
private FirebaseStorage mStorage;
private DatabaseReference databaseReference;
private Context context ;
private List<Model> mModel;
private ListImageAdapter listImageAdapter;
private Variable staticVariable = new Variable();
public ListFragment() {
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_list_batik, container, false);
findView(view);
initView(view);
initListener(view);
getDataFromFirebase();
return view;
}
private void getDataFromFirebase() {
simpleActivity.progressDialog(context);
recyclerViewImages.setHasFixedSize(true);
recyclerViewImages.setLayoutManager(new LinearLayoutManager(context));
mModel = new ArrayList<>();
listImageAdapter = new ListImageAdapter(context, mModel);
recyclerViewImages.setAdapter(listImageAdapter);
listImageAdapter.setOnItemClickListener(ListFragment.this);
mStorage = FirebaseStorage.getInstance();
databaseReference = FirebaseDatabase.getInstance().getReference(staticVariable.BATIK_DETECTIONS);
databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
mModel.clear();
for(DataSnapshot postSnapshot : dataSnapshot.getChildren()){
Model model = postSnapshot.getValue(Model.class);
mModel.add(model);
}
listImageAdapter.notifyDataSetChanged();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
simpleActivity.toastMessage(context, databaseError.getMessage());
}
});
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
this.context = context;
}
@Override
public void findView(View view) {
recyclerViewImages = view.findViewById(R.id.recycleview_image);
}
@Override
public void initView(View view) {
}
@Override
public void initListener(View view) {
}
@Override
public void OnItemClick(int position) {
simpleActivity.toastMessage(context, "Click on Positions : " + position);
}
@Override
public void OnViewDescriptions(int position) {
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference batikdetectionsRef = rootRef.child("Batikdetections");
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
Map<String, Double> dataSet = (Map<String, Double>) ds.child("dataSet").getValue();
double[] target = new double[dataSet.size()];
int count = 0;
for (Map.Entry<String, Double> entry : dataSet.entrySet()) {
target[count] = entry.getValue();
count++;
Log.v(TAG, String.valueOf(entry.getValue()));
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
batikdetectionsRef.addListenerForSingleValueEvent(valueEventListener);
}
@Override
public void OnEditItem(int position) {
Model selectedItem = mModel.get(position);
String selectedKey = selectedItem.getKey();
String selectedImage = selectedItem.getImagesUri();
String selecteDescriptions = selectedItem.getImageDescription();
String selectedImagesName = selectedItem.getImageNames();
readData();
double[] newDataSet = model.getDoubles();
EditFragment editFragment = new EditFragment();
FragmentTransaction fragmentTransaction =
getActivity().getSupportFragmentManager()
.beginTransaction();
Bundle bundle = new Bundle();
bundle.putString("Label", selectedKey);
bundle.putString("Image", selectedImage);
bundle.putString("Descriptions", selecteDescriptions);
bundle.putString("ImagesName", selectedImagesName);
bundle.putDoubleArray("DataSet", newDataSet);
editFragment.setArguments(bundle);
fragmentTransaction.setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_right,
R.anim.enter_from_right, R.anim.exit_to_right)
.replace(R.id.frame_edit, editFragment)
.addToBackStack(null)
.commit();
}
@Override
public void OnDeleteItem(int position) {
simpleActivity.toastMessage(context, "Delete Item :" + position);
Model selectedItem = mModel.get(position);
final String selectedKey = selectedItem.getKey();
StorageReference imageRef = mStorage.getReferenceFromUrl(selectedItem.getImagesUri());
imageRef.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
databaseReference.child(selectedKey).removeValue();
simpleActivity.toastMessage(context, "Item Deleted");
}
});
}
public void readData(){
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference batikdetectionsRef = rootRef.child("Batikdetections");
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
Map<String, Double> dataSet = (Map<String, Double>) ds.child("dataSet").getValue();
double[] target = new double[dataSet.size()];
int count = 0;
for (Map.Entry<String, Double> entry : dataSet.entrySet()) {
target[count] = entry.getValue();
count++;
Log.d(TAG, String.valueOf(entry.getValue()));
}
model.setDoubles(target);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
batikdetectionsRef.addListenerForSingleValueEvent(valueEventListener);
}
}
那是我的完整代码,我想要的数据是double[]
,因为我喜欢在片段之间传输数据。
错误
06-12 01:51:28.424 14704-14704/com.tugasakhir.batikdetections E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.tugasakhir.batikdetections, PID: 14704
java.lang.ClassCastException: java.util.ArrayList cannot be cast to java.util.Map
at com.tugasakhir.batikdetections.fragment.batiklopedia.ListFragment$2.onDataChange(ListFragment.java:137)
at com.google.firebase.database.Query$1.onDataChange(com.google.firebase:firebase-database@@16.0.6:183)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database@@16.0.6:75)
at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database@@16.0.6:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database@@16.0.6:55)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:1)
使用ValueEventListener
在您的子数据集上循环
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
//use int i and initialize it with 0
Double value = (Double) dataSnapshot.child(String.valueOf(i)).getValue();
///listDouble is an example of Double[] array
listDouble[i] = value;
i++;
}
}
答案 1 :(得分:0)
代码中的主要问题是,由于方法的原因,您无法返回target
数组。这是因为您尝试使用尚未从数据库加载的元素填充该数组。这是因为beucase onDataChange()
方法具有异步行为。有关更多详细信息,请参见以下帖子中的答案:
要解决此问题,请使用以下代码行:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference batikdetectionsRef = rootRef.child("Batikdetections");
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
ArrayList<Double> dataSet = (ArrayList<Double>) ds.child("dataSet").getValue();
double[] target = new double[dataSet.size()];
int count = 0;
for (Double d : dataSet) {
target[count] = d;
count++;
Log.d(TAG, String.valueOf(d));
}
//Do what you need to do with your target array
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
batikdetectionsRef.addListenerForSingleValueEvent(valueEventListener);