Android通过服务将领域对象传递给另一个活动

时间:2017-05-22 12:03:43

标签: java android service realm

我知道将领域对象传递给另一个活动非常困难。无论如何,我尝试通过服务这样做: 1)MainActivity to job,make realm object并使用setter在服务中保证安全, 2)服务就像两个活动之间的持有者或连接桥, 3)在第二个活动中尝试从服务中获取领域对象,

当然我在get行中有nullPointerException。 我知道有人说:你好sqlite更好,但我试着理解领域lib和服务如何合作。

这是我的代码: 主:

public class MainActivity extends AppCompatActivity {

    List<String> shopsNames;
    ArrayList<RowModel> rowModels;

    protected RealmService mService;
    protected boolean mBound = false;


    public Realm mRealm;
    @BindView(R.id.toolbar_layout)
    CollapsingToolbarLayout toolbarLayout;
    @BindView(R.id.app_bar)
    AppBarLayout appBar;
    private ShopsAdapter adapter;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);
        ButterKnife.bind(this);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        ConnectionDetector connectionDetector = new ConnectionDetector(this);
        if (!connectionDetector.isConnection()){
            finish();
        }
        rowModels = new ArrayList<>();
        shopsNames = new ArrayList<>();
        mRealm = Realm.getInstance(this);

        initCollapsingToolbar();

        adapter = new ShopsAdapter(MainActivity.this, shopsNames);

        RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(), 2);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(adapter);

        Intent intent = new Intent(getApplicationContext(), RealmService.class);
        bindService(intent, mConnection, this.BIND_AUTO_CREATE);

        AsyncTaskRetro asyncTaskRetro = new AsyncTaskRetro();
        asyncTaskRetro.execute();


    }

    private class AsyncTaskRetro extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... voids) {

            PlacesAPI.Factory.getInstance().getPlaces().enqueue(new Callback<Places>() {

                @Override
                public void onResponse(Call<Places> call, Response<Places> response) {
                    for (int i = 0; i < response.body().getPosts().size(); i++) {
                        RowModel rowModel = new RowModel(response.body().getPosts().get(i).getNazwa(),
                                Double.parseDouble(response.body().getPosts().get(i).getSzer()),
                                Double.parseDouble(response.body().getPosts().get(i).getDlug()));
                        rowModels.add(rowModel);



                    }
                    String oldName;
                    oldName = rowModels.get(0).getName();
                    shopsNames.add(rowModels.get(0).getName());

                    mRealm.beginTransaction();
                    RowModel rowModelRealm = mRealm.createObject(RowModel.class);
                    mRealm.commitTransaction();


                    for (int j = 0; j < rowModels.size(); j++) {
                        mRealm.beginTransaction();
                        rowModelRealm.setName(rowModels.get(j).getName());
                        rowModelRealm.setLattitude(rowModels.get(j).getLattitude());
                        rowModelRealm.setLongitude(rowModels.get(j).getLongitude());
                        mRealm.commitTransaction();


                        if (rowModels.get(j).getName().equals(oldName)) {
                            continue;
                        }
                        oldName = rowModels.get(j).getName();
                        shopsNames.add(rowModels.get(j).getName());
                    }
                    mService.setRealm(mRealm);
                    RealmResults<RowModel> rw = mRealm.where(RowModel.class).findAll();
                    Log.d("sdfsd",  Integer.toString(rw.size()));
                    //sortowanie listy z nazwami sklepow
                    Collections.sort(shopsNames);



                    adapter = new ShopsAdapter(MainActivity.this, shopsNames);

                    recyclerView.setAdapter(adapter);

                    try {
                        Glide.with(getApplicationContext()).load("http://www.wp.pl/shop-local-logo.png").
                                into((ImageView) findViewById(R.id.backdrop));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(Call<Places> call, Throwable t) {

                }
            });

            return null;
        }
    }

    private ServiceConnection mConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName className,
                                       IBinder service) {

            RealmService.LocalBinder  binder = (RealmService.LocalBinder) service;
            mService = binder.getService();
            mBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            mBound = false;
        }
    };

    private void initCollapsingToolbar() {
        final CollapsingToolbarLayout collapsingToolbar =
                (CollapsingToolbarLayout) findViewById(R.id.toolbar_layout);
        collapsingToolbar.setTitle(" ");
        AppBarLayout appBarLayout = (AppBarLayout) findViewById(R.id.app_bar);
        appBarLayout.setExpanded(true);

        // hiding & showing the title when toolbar expanded & collapsed
        appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            boolean isShow = false;
            int scrollRange = -1;

            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                if (scrollRange == -1) {
                    scrollRange = appBarLayout.getTotalScrollRange();
                }
                if (scrollRange + verticalOffset == 0) {
                    collapsingToolbar.setTitle(getString(R.string.app_name));
                    isShow = true;
                } else if (isShow) {
                    collapsingToolbar.setTitle(" ");
                    isShow = false;
                }
            }
        });
    }
}

我的第二堂课:

public class Test extends AppCompatActivity {

    protected RealmService mService;
    protected boolean mBound = false;

    public Realm mRealm;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.text);


        Intent intent = new Intent(this, RealmService.class);
        bindService(intent, mConnection, this.BIND_AUTO_CREATE);

        mRealm = mService.getRealm();

        mRealm.beginTransaction();
        RealmResults<RowModel> rowModels = mRealm.where(RowModel.class).findAll();

        if(!rowModels.isEmpty()){
            String s;
            for (int i = 0; i < rowModels.size(); i++) {

                s = rowModels.get(i).getName() + " " + rowModels.get(i).getLattitude()
                        + " " + rowModels.get(i).getLongitude();
                Log.d("S: ", s);
            }

        }


    }

    private ServiceConnection mConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName className,
                                       IBinder service) {

            RealmService.LocalBinder  binder = (RealmService.LocalBinder) service;
            mService = binder.getService();
            mBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            mBound = false;
        }
    };

}

和服务:

public class RealmService extends Service {
    public Realm getRealm() {
        return realm;
    }

    public void setRealm(Realm realm) {
        this.realm = realm;
    }

    public Realm realm;
    private final IBinder iBinder = new LocalBinder();

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return iBinder;
    }

    public class LocalBinder extends Binder {
        RealmService getService() {
            return RealmService.this;
        }
    }
}

0 个答案:

没有答案