在活动暂停或停止时删除事件侦听器

时间:2016-06-11 05:47:05

标签: android firebase

我在删除事件侦听器时遇到问题。 我正在使用Activity中的onStart()内部初始化一个监听器 收集用户数据后,应用程序向用户显示数据已上传的干杯,然后我调用onBackPressed()方法。

但我注意到,在活动暂停或停止后,侦听器仍在运行,因为它正在创建在onCancelled()事件下调用的toast。

所以我尝试重写onPause和onStop方法。

@Override
public void onPause() {
    super.onPause();
    // Remove post value event listener
      if (mListener != null) {
        mReadReference.removeEventListener(mListener);
       }
}  

但这导致错误:

java.lang.RuntimeException: Unable to pause activity {deventree.com.thetimothyinitiative/deventree.com.thetimothyinitiative.Attendance}: java.lang.NullPointerException: listener must not be null

我希望在上传数据之后和活动调用onBackPressed()方法之前删除ValueEventListener

活动代码:

public class Attendance extends Activity {

Map<String, Boolean> td;
ArrayList<String> valu;


private SparseBooleanArray sbArray;

private static final String TAG = "Attendance";

CustomAdapter myAdapter;
ListView listview;

private DatabaseReference mReadReference;
private DatabaseReference mPostReference;
private ValueEventListener mListener;

private Button mButton;
private Button btnAll;
private Button btnNone;

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

    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
    String eid=user.getEmail();
    System.out.println(eid);
    //String[] parts = eid.split("@");
    String[] parts = eid.split("\\.");
    eid = parts[0];
    System.out.println(eid);
    Date dNow = new Date( );
    SimpleDateFormat ft = new SimpleDateFormat("E dd-MM-yyyy 'at' HH:mm:ss");

     final ListView listview = (ListView) findViewById(R.id.listq);
    // Initialize Database
    mReadReference = FirebaseDatabase.getInstance().getReference()
            .child("Lists").child(eid);
    mPostReference = FirebaseDatabase.getInstance().getReference()
            .child("Users").child(eid).child(ft.format(dNow)).child("Attendance Record");

    //UI Elements
    btnAll=(Button)findViewById(R.id.button40);
    btnNone=(Button)findViewById(R.id.button33);
    mButton=(Button)findViewById(R.id.button42);

    btnAll.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            for (int i = 0; i < listview.getCount(); i++) {
                listview.setItemChecked(i, true);
            }
        }
    });
    btnNone.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            int len=listview.getCount();
            int lou=listview.getChildCount();
            System.out.println(len+" "+lou);
            for ( int i=0; i < listview.getCount(); i++) {
                listview.setItemChecked(i, false);
            }
        }
    });

    mButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            System.out.println("Hello MF");
            SparseBooleanArray checked = listview.getCheckedItemPositions();
            for (int i=0; i<checked.size(); i++) {
                if (checked.valueAt(i)) {
                    String item = listview.getAdapter().getItem(checked.keyAt(i)).toString();
                    td.put(item, true);
                }
                else{
                    String item = listview.getAdapter().getItem(checked.keyAt(i)).toString();
                    td.put(item, false);
                     }
            }
            mPostReference.setValue(td);
            for (Map.Entry entry : td.entrySet()) {
                System.out.println(entry.getKey() + ", " + entry.getValue());
            }
            Toast.makeText(getApplicationContext(), "Attendance Uploaded",Toast.LENGTH_SHORT).show();
            onBackPressed();
        }
    });
}
@Override
public void onStart() {
    super.onStart();
    ValueEventListener mListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            System.out.println("here");
            td = (Map<String,Boolean>) dataSnapshot.getValue();
            for (Map.Entry<String, Boolean> entry : td.entrySet()) {
                td.put(entry.getKey(),false);
            }

            valu = new ArrayList<String>(td.keySet());
            ArrayAdapter<String> dataAdapter = new ArrayAdapter(getApplicationContext(), R.layout.rowview, valu);
            listview = (ListView) findViewById(R.id.listq);
            listview.setAdapter(dataAdapter);

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
            Toast.makeText(Attendance.this, "Failed to load list.",
                    Toast.LENGTH_SHORT).show();

        }
    };
    mReadReference.addValueEventListener(mListener);
}

@Override
public void onStop() {
    // Remove post value event listener
    if (mListener != null) {
        mReadReference.removeEventListener(mListener);
        System.out.println("Doness");
    }
    super.onStop();

}

@Override
public void onPause() {

    // Remove post value event listener
    if (mListener != null) {
        mReadReference.removeEventListener(mListener);
        System.out.println("Here");
    }
    super.onPause();
}

}

1 个答案:

答案 0 :(得分:5)

super()来电之前执行此操作。像这样:

@Override
public void onPause() {

    // Remove post value event listener
      if (mListener != null && mReadReference!=null) {
        mReadReference.removeEventListener(mListener);
       }
      super.onPause();
}  

Stop()上的相同内容:

@Override
public void onStop() {

    // Remove post value event listener
    if (mListener != null && mReadReference!=null) {
        mReadReference.removeEventListener(mListener);
    }
    super.onStop();
}
  

编辑1:只需从onStart()删除声明即可修改onStart()以下代码:

@Override
public void onStart() {
    super.onStart();

     // Removed  ValueEventListener mListener =new ValueEventListener() {

     mListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            System.out.println("here");
            td = (Map<String,Boolean>) dataSnapshot.getValue();
            for (Map.Entry<String, Boolean> entry : td.entrySet()) {
                td.put(entry.getKey(),false);
            }

            valu = new ArrayList<String>(td.keySet());
            ArrayAdapter<String> dataAdapter = new ArrayAdapter(getApplicationContext(), R.layout.rowview, valu);
            listview = (ListView) findViewById(R.id.listq);
            listview.setAdapter(dataAdapter);

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
            Toast.makeText(Attendance.this, "Failed to load list.",
                    Toast.LENGTH_SHORT).show();

        }
    };
    mReadReference.addValueEventListener(mListener);
}

只需将其声明为onCreate()onStart()以上。

希望这会有所帮助:)