Доступ к Arraylistиз сервиса bind возвращается пустой - PullRequest
0 голосов
/ 24 ноября 2018

Я обращаюсь к 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 голосов
/ 24 ноября 2018

Когда вы вызываете 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(); 
}
...