-1

I would like to get data from Firebase and put in as double[]. This is my data on Firebase:

enter image description here

I just want data on the dataSet, or, alternative one is I like to get in as List<Double> So how can i solve this?

Edited

        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);
}
}

That is my full code, the data I want is double[] because I like to transfer data from fragment to fragment.

Error

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)
Appem
  • 295
  • 1
  • 3
  • 16
  • Please edit the question to show the code that you tried that doesn't work the way you expect. The documentation for querying Realtime Database starts here: https://firebase.google.com/docs/database/android/read-and-write – Doug Stevenson Jun 11 '19 at 00:24

2 Answers2

1

Do a loop on your child data set using 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++;
        }
    }
ismail alaoui
  • 5,748
  • 2
  • 21
  • 38
0

The main issue in your code is that you cannot return the target array as a result of a method. This is because you are trying to fill that array with elements that are not loaded from the database yet. This is happening beucase onDataChange() method has an asynchronous behavior. For more details, please see my answer from the following post:

To solve, please use the following lines of code:

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);
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • i edited like your code, but how can i get that double[] data? i try using callback and give me error on, `newdataset = double` – Appem Jun 11 '19 at 08:58
  • How to get, exactly as in my above answer. You can use the `double[] target` only inside the callback, right where you find that comment. If you try to iterate through the array, do you get the correct doubles? Beside that, in `readData()` you should just read the data, not addig data to the callback. Take a closer look to that answer. – Alex Mamo Jun 11 '19 at 09:01
  • i already edit my code, but, its giveing me an error because i cant get the data from double[] – Appem Jun 11 '19 at 11:32
  • "its giveing me an error" doesn't help me understand the problem. What's the error? At which line of code occurs? But as I see in your code, you are using the old code along with the one I have provided you. **As I asked you before, if you are only using my code and iterate the array where that comment exists, does it work?** – Alex Mamo Jun 11 '19 at 11:36
  • "it doesnt work" doesn't help either. If you don't provide me details and don't answer the questions in the comments, I cannot be much of a help. – Alex Mamo Jun 11 '19 at 11:44
  • the log cat doesn't show anything, because my app just crashed after deploy, but when i try to exclude 2 line of code from `readData(); double[] newDataSet = model.getDoubles();` its work again :( – Appem Jun 11 '19 at 12:00
  • If the app crashes, there is a stack trace. Please look that up on logcat, and add it to your question. – Alex Mamo Jun 11 '19 at 12:24
  • Beside that, you are **not** using the code I have provided you. You are using `double[] newDataSet = model.getDoubles();` which makes sense not to work. Try only the code I gave you, does it work? – Alex Mamo Jun 11 '19 at 12:25
  • i dont understand you said i didnt use your code, i put your code on `void readdata`, and use double to put on model class `model.setDoubles(target);`, after that, i take the data using `double[] newDataSet = model.getDoubles();`, – Appem Jun 11 '19 at 12:54
  • No, it won't work that way. Please comment all the other code and try to use **ONLY** the code that I provided you and tell me if it works. It's the third time I've asked you the same thing. – Alex Mamo Jun 11 '19 at 12:58
  • I already use it, i try to put into `OnViewDescriptions`, and the error i got down bellow, i'm only using your code. – Appem Jun 11 '19 at 17:54
  • Seeing your error now, yes, you're right. Please see my updated answer. Should work now, right? – Alex Mamo Jun 12 '19 at 05:58
  • Have you tired my change above, does it work? Using that change you can also solve this [question](https://stackoverflow.com/questions/56563646/how-to-compare-data-in-double-and-data-in-firebase), right? – Alex Mamo Jun 12 '19 at 13:45
  • Ok, keep me posted. Once you finish, tell me if it works. – Alex Mamo Jun 12 '19 at 14:09
  • Have you finished it? – Alex Mamo Jun 24 '19 at 18:40
  • yeah i finish it i'm sory for my late post, i try to consider my method with my prof so i cant reply your reply :D – Appem Jul 18 '19 at 05:40