从绑定服务访问Arraylist <string>并返回空

时间:2018-11-24 11:14:23

标签: android android-studio arraylist android-service-binding nul

我正在访问marraylist服务变量,尽管它是由Firebase中的数据初始化的,但是在marraylist中返回空的Activity却是通过从Firebase数据库获取数据在服务数组中初始化此变量的并在敬酒中,我从Firebase获取数据到marraylist,但是当我尝试访问活动中的变量时,它返回的是空ArrayList

绑定到服务的我的班级是

public class ProfileList extends AppCompatActivity  
  implements View.OnClickListener {
        private FirebaseAuth mAuth;
        Dialog Mydialog;
        private FirebaseAuth.AuthStateListener authStateListener;
        public DatabaseReference db;
        public String userid;
        FirebaseUser firebaseUser;
        public String iamlog="hy";
        List<String> listSt;
        String snapdata,log;
        ArrayList<String> m1arraylist = new ArrayList <String>();
        RecyclerView recyclerView;
        public ProfileService myservice;
        Intent intent;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.profilelist);
            db = FirebaseDatabase.getInstance().getReference().child("users");
            recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
            recyclerView.setLayoutManager(new LinearLayoutManager(this));

            Button button2 = (Button) findViewById(R.id.button2);
            mAuth = FirebaseAuth.getInstance();
            userid = mAuth.getCurrentUser().getUid();
            db = db.child(userid);
            Uri uri = Uri.parse(String.valueOf(db));
            Log.e(iamlog,String.valueOf(uri));

            Intent Profileserviceint = new Intent(this, ProfileService.class);
            Profileserviceint.putExtra("dbrefuri",String.valueOf(uri));
            bindService(Profileserviceint, connection, Context.BIND_AUTO_CREATE);

        }





        ServiceConnection connection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                Localservice localservice = (Localservice) service;
                myservice=localservice.getservice();
                m1arraylist=myservice.getdata();
                recyclerView.setAdapter(new ProgramingAdapter(ProfileList.this,localservice.getservice().marraylist));
                Log.e(iamlog,"Profile calss "+ String.valueOf(localservice.getservice().marraylist));

            }

            @Override
            public void onServiceDisconnected(ComponentName name) {

            }
        };

我的服务等级是

public class ProfileService extends Service {
    public DatabaseReference db;
    Intent intent;
    public String iamlog="hy";
    String dbref;

    public ArrayList<String> marraylist = new ArrayList<>() ;

    public IBinder mbinder = new Localservice();
    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     *
     * Used to name the worker thread, important only for debugging.
     */


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        dbref  =intent.getStringExtra("dbrefuri");
        return  mbinder;
    }

    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     *
     */


    public     class  Localservice extends Binder
    {
        public   ProfileService getservice()
        {
            return ProfileService.this;
        }
    }

    public  ArrayList<String> getdata()
    {
        db=  FirebaseDatabase.getInstance().getReferenceFromUrl(dbref);
        db.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot dataSnapshot2 : dataSnapshot.getChildren())
                {
                    marraylist.add(dataSnapshot2.getKey());
                }
                Toast toast =  Toast.makeText(ProfileService.this ,String.valueOf(marraylist),Toast.LENGTH_LONG);
                toast.show();
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

        return marraylist;
    }

}

1 个答案:

答案 0 :(得分:0)

致电时 getData() 它启动数据获取,但是获取尚未完成。 返回的ArrayList尚无任何项目。 一旦在内部获取数据

onDataChange(DataSnapshot dataSnapshot) 

数据已添加到列表中。 RecyclerView没有看到此更改。

您需要致电

notifyDataSetChanged() 

一旦数据被加载。 将您的代码更改为类似这样的内容

public class ProfileService extends Service {
    public DatabaseReference db;
    Intent intent;
    public String iamlog="hy";
    String dbref;
    WeakReference<ProfileServiceCallback> profileServiceCallBackRef;

    public ArrayList<String> marraylist = new ArrayList<>() ;

    public IBinder mbinder = new Localservice();
    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     *
     * Used to name the worker thread, important only for debugging.
     */


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        dbref  =intent.getStringExtra("dbrefuri");
        return  mbinder;
    }

    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     *
     */


    public     class  Localservice extends Binder
    {
        public   ProfileService getservice()
        {
            return ProfileService.this;
        }

        public void setCallback(ProfileServiceCallBack callback){
             profileServiceCallbackRef = new WeakReference<ProfileServiceCallBack>(callback);
        }
    }
    public static interface ProfileServiceCallBack {
           public void onDataChanged(List<String> data);
    }


    public  void getdata()
    {
        db=  FirebaseDatabase.getInstance().getReferenceFromUrl(dbref);
        db.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot dataSnapshot2 : dataSnapshot.getChildren())
                {
                    marraylist.add(dataSnapshot2.getKey());
                }
                Toast toast =  Toast.makeText(ProfileService.this ,String.valueOf(marraylist),Toast.LENGTH_LONG);
                toast.show();
                if(profileServiceCallbackRef != null){
                   ProfileServiceCallback callback = profileServiceCallbackRef.get();
                   if(callback != null){
                      profileServiceCallback.onDataChanged(mArrayList);
                   }
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }

}

活动

public class ProfileList extends AppCompatActivity  
implements View.OnClickListener,ProfileServiceCallback {
        private FirebaseAuth mAuth;
        Dialog Mydialog;
        private FirebaseAuth.AuthStateListener authStateListener;
        public DatabaseReference db;
        public String userid;
        FirebaseUser firebaseUser;
        public String iamlog="hy";
        List<String> listSt;
        String snapdata,log;
        ArrayList<String> m1arraylist = new ArrayList <String>();
        RecyclerView recyclerView;
        public ProfileService myservice;
        ProgramingAdapter programmingAdapter;
        Intent intent;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.profilelist);
            db = FirebaseDatabase.getInstance().getReference().child("users");
            recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
            recyclerView.setLayoutManager(new LinearLayoutManager(this));
            programmingAdapter = new ProgrammingAdapter();
            recyclerView.setAdapter(programmingAdapter);
            recyclerView.setAdapter();
            Button button2 = (Button) findViewById(R.id.button2);
            mAuth = FirebaseAuth.getInstance();
            userid = mAuth.getCurrentUser().getUid();
            db = db.child(userid);
            Uri uri = Uri.parse(String.valueOf(db));
            Log.e(iamlog,String.valueOf(uri));

            Intent Profileserviceint = new Intent(this, ProfileService.class);
            Profileserviceint.putExtra("dbrefuri",String.valueOf(uri));
            bindService(Profileserviceint, connection, Context.BIND_AUTO_CREATE);

        }

        @Override
        public void onDataChanged(List<String> data){
            programmingAdapter.setData(data);
            programmingAdapter.notifyDatasetChanged(); 
        }

        ServiceConnection connection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                Localservice localservice = (Localservice) service;
                myservice=localservice.getservice();
                myservice.getdata(ProfileList.this);
                myservice.setCallback();
                Log.e(iamlog,"Profile calss "+ String.valueOf(localservice.getservice().marraylist));

            }

            @Override
            public void onServiceDisconnected(ComponentName name) {

            }
        };

您需要在ProgrammingAdapter中添加一个方法

setData(List<String> data){
   this.data = data;
   notifyDatasetChanged(); 
}