简体   繁体   中英

Struggling to take values from Firebase Realtime Database

I'm really struggling to gather data from database. Im using the realtime database and i am adding the values to a list which is going to be clickable.

When i click on the user on the list i need to get the username value to create chat ids. This is my proble to get the values inside the keys. They way that i am doing doesnt seem to be working.

This is my Database

在此处输入图片说明

I need to take the value given to "name".

This is my code

package br.sosqueen.com.sosqueen;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Iterator;

public class UserMessageListFragment extends Fragment {

    private ProgressDialog progressDialog;
    private final String TAG = "UsersMessageLis";
    private ArrayList<String> arrayList = new ArrayList<>();
    private int totalUsers = 0;
    private ListView usersList;
    private TextView noUsersText;

    public static UserMessageListFragment newInstance() {
        return new UserMessageListFragment();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_user_message_list, container, false);

        usersList = view.findViewById(R.id.usersList);
        noUsersText = view.findViewById(R.id.noUsersText);

        progressDialog = new ProgressDialog(getContext());
        progressDialog.setMessage("Carregando...");
        progressDialog.show();

        //String url = "https://sosqueen-6b80b.firebaseio.com/users.json";
        String url = "https://sosqueen-6b80b.firebaseio.com/usuarios.json";
        StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                doOnSuccess(response);
            }
        }, new Response.ErrorListener(){
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d(TAG, "Error on trying to do request");
            }
        });

        RequestQueue rQueue = Volley.newRequestQueue(getContext());
        rQueue.add(request);

        usersList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                UserDetails.chatWith = arrayList.get(position);
                startActivity(new Intent(getContext(), Chat.class));
            }
        });

        return view;
    }

    public void doOnSuccess(String response) {

        try {
            JSONObject object = new JSONObject(response);
            Iterator iterator = object.keys();
            String key = "";

            while(iterator.hasNext()) {
                key = iterator.next().toString();

                if(! key.equals(UserDetails.username)) {
                    arrayList.add(key);
                }
                totalUsers++;
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

        checkIfThereIsAnUser(totalUsers);
    }

    public void checkIfThereIsAnUser(int totalUsers) {


        if(totalUsers <=1){
            noUsersText.setVisibility(View.VISIBLE);
            usersList.setVisibility(View.GONE);
        }
        else{
            noUsersText.setVisibility(View.GONE);
            usersList.setVisibility(View.VISIBLE);
            usersList.setAdapter(new ArrayAdapter<>(getContext(), R.layout.my_list, arrayList));
        }
        progressDialog.dismiss();
    }
}

You want to create a ChildEventListener and attach it to your "users" branch.

When you first connect to the branch using ChildEventListener , OnChildAdded will fire for each child member returning the child data branch snapshot.

Personally, I would store the entire datasnapshot result and when rendering it in the list, render the snapshot.getValue("name") instead of the branch Key.

Otherwise, you will need to store the branch key and name pair and then lookup the extra data information through DatabaseRef OnValue query.


Alternatively, you can create a Query based on some branch value (with the .indexon property enabled) such as the 'ciudad' and filter based on local names.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM