在函数外部访问变量

By simon at 2018-02-28 • 0人收藏 • 55人看过

如何访问要在适配器中访问的函数的变量 下面的对象? 这里的变量消息和日期n需要在适配器聊天中访问 模型。 我正在循环firebase中的每个对象以获取我的价值的用户名 插件在回收者视图的适配器中进行。 我试图使变量全局,静态和使用这个关键字,但 每个人都是在函数外部给出一个空值。我的整个代码:

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.example.acer.buildingmanagementsystem.Activities.LogiinActivity;
import com.example.acer.buildingmanagementsystem.Adapters.chatListAdapter;
import com.example.acer.buildingmanagementsystem.Others.Utils;
import com.example.acer.buildingmanagementsystem.Others.chatModel;
import com.example.acer.buildingmanagementsystem.R;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class chatListFragment extends Fragment{
    private List<chatModel> chatsList;
    private RecyclerView recyclerView;
    private chatListAdapter mAdapter;

    FirebaseDatabase database;
    DatabaseReference myRef;

    public String photoUrl;
    public String userName;
    String imgUrl;
    String subEmail;
    public String message;
    String url;
    public String date;

    DatabaseReference emailRef;
    private DatabaseReference mMessagesDatabaseReference;
    private DatabaseReference mReceiverDatabaseReference;
    private String TAG= getClass().getSimpleName();

    public chatListFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
       View rootView = inflater.inflate(R.layout.fragment_chat_list, container, false);


       setHasOptionsMenu(true);

        recyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
        recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), LinearLayoutManager.VERTICAL));
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(mAdapter);

        database = FirebaseDatabase.getInstance();
        myRef = database.getReference().child("Users");


        myRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot dsp : dataSnapshot.getChildren()) {
                    collectPhoneNumbers((Map<String,Object>) dataSnapshot.getValue(),dataSnapshot);
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

       return rootView;
    }
    private void collectPhoneNumbers(Map<String,Object> users,DataSnapshot dataSnapshot) {
        //Toast.makeText(getActivity(), "Inside Method", Toast.LENGTH_SHORT).show();
        //chatList = new ArrayList<String>();

        emailRef = FirebaseDatabase.getInstance().getReference().child("Users");
        //iterate through each user, ignoring their UID
        chatsList = new ArrayList<>();

        for (Map.Entry<String, Object> entry : users.entrySet()){
            emailRef.child("Image Url").addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    imgUrl = dataSnapshot.getValue(String.class);
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
            //Get user map
//            Map singleUser = (Map) entry;
            //Get phone field and append to list
            String child = entry.toString();
            Log.e("entry",entry.toString());
            String value;
            value = child.substring(1, child.length()-1);           //remove curly brackets
            String[] keyValuePairs = value.split(",");              //split the string to creat key-value pairs
            Map<String,String> map = new HashMap<>();

            for(String pair : keyValuePairs)                        //iterate over the pairs
            {
                String[] entrys = pair.split("=");                   //split the pairs to get key and value
                map.put(entrys[0].trim(), entrys[1].trim());          //add them to the hashmap and trim whitespaces
            }
            url = map.get("Image Url");


            Log.e("URL",url);
            userName = child.substring(0,child.indexOf("="));

            String email = FirebaseAuth.getInstance().getCurrentUser().getEmail();
            subEmail = email.substring(0,email.indexOf("@"));

            Log.e("Sub email",subEmail);
            Log.e("userName",userName);
            emailRef = Utils.getDatabase().getReference().child("Users").child(subEmail).child("messages").child(userName);

            SharedPreferences sp1 = getActivity().getSharedPreferences("Credential",0);
            String sender = sp1.getString("Sender","");
            String receiver = sp1.getString("Receiver","");
            **database = Utils.getDatabase();
            myRef = database.getReference().child("Last");
            Log.e("subEmaill",subEmail);
            Log.e("UUsername",userName);
            if(!subEmail.equals(userName))
            {
                mMessagesDatabaseReference = myRef.child(subEmail).child(userName);
                //mReceiverDatabaseReference = myRef.child(subEmail).child(userName);
                mMessagesDatabaseReference.addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        Log.e("TAG","Method called");
                        message = dataSnapshot.child("Last Message").getValue(String.class);
                        date = dataSnapshot.child("Last Time").getValue(String.class);
                        Toast.makeText(getActivity(), "Completed", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }
                });
                Toast.makeText(getActivity(), ""+message, Toast.LENGTH_SHORT).show();
                chatModel model = new chatModel(userName,message,url+"=media&token=9ae9e4a0-ed72-48e6-9713-ed4345dfb962",date);
                if (!model.getName().equals(subEmail))
                {
                    chatsList.add(model);
                }

                Log.e("Chat list",chatsList.toString());
            }**

        }
        mAdapter = new chatListAdapter(chatsList,getActivity());
        mAdapter.notifyDataSetChanged();
        recyclerView.setAdapter(mAdapter);

    }

    private void insertModel(String message, String date) {
        this.message = message;
        this.date = date;
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.main_menu,menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if(item.getItemId()==R.id.action_signOut)
        {
            FirebaseAuth.getInstance().signOut();
            startActivity(new Intent(getActivity(), LogiinActivity.class));
        }

        return super.onOptionsItemSelected(item);
    }
}

2 个回复 | 最后更新于 2018-02-28
2018-02-28   #1

最可能发生的事情是,你之前试图访问变量 “ValueEventListen”的“onDataChange”方法呃“被称为,解释 为什么你在访问它们时得到空值。 这里有一些代码可以帮助你理解:

public class chatListFragment extends Fragment{
    public String message;
    public String date;

    public chatListFragment() {
        // Required empty public constructor
    }

    private void collectPhoneNumbers(Map<String,Object> users,DataSnapshot dataSnapshot) {
        mMessagesDatabaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                Log.e("TAG","Method called");

                onDataReceived(
                    dataSnapshot.child("Last Message").getValue(String.class),
                    dataSnapshot.child("Last Time").getValue(String.class)
                )

                Toast.makeText(getActivity(), "Completed", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }

    private void onDataReceived(String message, String date) {
        this.message = message;
        this.date = date;

        // The vars are populated with data now,
        // you can proceed to parse it as you wish
    }
}
另外,请记住,按照惯例,在Java中的类(如在任何其他 编程语言,我猜)被命名为机智h首字母大写,所以 你是Fragment类的名字应该是“ChatListFragment”。这是 通常为了避免c与实例名称混淆。

2018-02-28   #2

这不完全是关于访问函数外部的变量。你做吧 与领域。你的实际问题不明白g Firebase运行在 背景,并做网络请求,你需要等待的 结果_从99999999以内9910,不在addValueEventListener之后 new ValueEventListener ()内的代码不会立即执行。 你不需要ArrayList中的数据创建一个适配器。 但是您需要在添加项目时立即通知。

    String email = FirebaseAuth.getInstance().getCurrentUser().getEmail();
    final String subEmail = email.substring(0,email.indexOf("@"));


    // Create the adapter
    mAdapter = new ChatListAdapter(chatsList, getActivity());
    recyclerView.setAdapter(mAdapter);

    // Wait for messages
    mMessagesDatabaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Log.e("TAG","Method called");
            final String message = dataSnapshot.child("Last Message").getValue(String.class);
            final String date = dataSnapshot.child("Last Time").getValue(String.class);
            Log.d("MESSAGE", String.valueOf(message));

            // Add data
            ChatModel model = new chatModel(userName,message,url+"=media&token=9ae9e4a0-ed72-48e6-9713-ed4345dfb962",date);
            if (!model.getName().equals(subEmail)) {
                chatsList.add(model);
                mAdapter.notifyItemInserted(chatsList.size());
            }

            // Log within the listener, not after
            Log.d("Chat list", chatsList.toString());
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
           Log.wtf("ERROR", databaseError.toString());
        }
    });
 // Your arraylist will be empty here

登录后方可回帖

Loading...