为什么Observable.create()在单击时不起作用?

时间:2018-09-16 06:49:42

标签: android android-studio rx-android

在我的应用程序中,我在menuitemclicked中添加了Observable方法,但是当我两次单击它时,它仍在工作。单按。方法不起作用,但是按钮可以很好地暗示或改变方法。

case R.id.upload:

fetch() 休息;

io.reactivex.Observable fetchObservable(){

return io.reactivex.Observable.create(new ObservableOnSubscribe<Data>() {
    @Override
    public void subscribe(ObservableEmitter<Data> emitter) throws Exception {


        try {


            final Cursor cursor = getActivity().getContentResolver().query(android.provider.ContactsContract.CommonDataKinds.Phone.CONTENT_URI, new String[]{"display_name", "data1"}, null, null, null);


            //  final Map contact =new HashMap();


            while (cursor.moveToNext()) {

                Data data = new Data();


                try {

                    String name = cursor.getString(cursor.getColumnIndex(Display_name));
                    String number = cursor.getString(cursor.getColumnIndex(Data1));
                    data.setContact_name(name);
                    data.setNumber(number);

                    Thread.sleep(60);

                    emitter.onNext(data);

                } catch (Exception e) {

                    Toast.makeText(context, "not insert , Toast.LENGTH_SHORT).show();
                }
            }

            emitter.onComplete();
        }catch (Exception e){

            emitter.onError(e);
        }

        }


});

//获取方法代码

void fetch(){

fetchObservable()。subscribeOn(Schedulers.newThread())。observeOn(AndroidSchedulers.mainThread())。subscribe(new Observer(){           @Override           public void onSubscribe(Disposable d){

      }

      @Override
      public void onNext(Data data) {


          data.Contact_name=data.getContact_name();
          data.number=data.getNumber();


              String name=  data.Contact_name;
              String number=   data.number;





          }




              count++;
              textprogress.setText(String.valueOf(count));







          }

      }

      @Override
      public void onError(Throwable e) {

      }

      @Override
      public void onComplete() {

      }
  });

}

1 个答案:

答案 0 :(得分:1)

因为您没有在主线程中运行UI 像这样

new Handler(Looper.getMainLooper()).post(new Runnable() {
                 @Override
                 public void run() {

                     textprogress.setVisibility(View.VISIBLE);
                     textprogress.setVisibility(View.VISIBLE);

                 }
             });