从片段android调用方法

时间:2017-04-07 14:57:23

标签: android android-activity methods

我尝试从片段活动中调用一个方法。

public class FragmentHome extends Fragment {

    private String DATABASE_NAME = "Alarm.sqlite";
    private SQLiteDatabase Database;

    ListView listView;
    ArrayList<alarm> list;
    AdapterAlarm adapterAlarm;

    Intent intent;
    AlarmManager alarmManager;
    PendingIntent pendingIntent;

    Switch aSwitch;

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_fragment_home, container, false);
        listView = (ListView)view.findViewById(R.id.lv);
        //khoi tao arraylist va adapter
        list = new ArrayList<alarm>();
        adapterAlarm = new AdapterAlarm(list, getActivity());
        //set adapter len listview
        listView.setAdapter(adapterAlarm);
        //đăng ký context menu
        registerForContextMenu(view.findViewById(R.id.lv));

        return  view;
    }

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

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        this.getActivity().getMenuInflater().inflate(R.menu.menu_listview_home, menu);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        alarm al = list.get(info.position);
        int id = al.getId();
        switch(item.getItemId()) {
            case R.id.edit:
                //sửa báo thức
                Intent in = new Intent(getActivity(), EditActivity.class);
                Bundle b = new Bundle();
                b.putInt("Id", id);
                in.putExtra("data", b);
                startActivity(in);

                break;
            case R.id.delete:
                //xóa báo thức
                deleteItem(id);
                break;
        }
        return true;
    }

    public void getData(){
        //doc du lieu tu db len arraylist
        Database = database.initDatabase(getActivity(), DATABASE_NAME);
        Cursor cursor = Database.rawQuery("SELECT*FROM Alarm", null);
        list.clear();
        for(int i=0; i<cursor.getCount(); i++) {
            //di chuyển cursor đến vị trí thứ i
            cursor.moveToPosition(i);
            //thêm đối tượng vào list
            list.add(new alarm(cursor.getInt(0), cursor.getString(1), cursor.getString(2)
                    , cursor.getInt(3), cursor.getInt(4), cursor.getInt(5)));

            //Lấy giờ từ db ra, tách giờ, phút
            alarm al = list.get(i);
            int hour = 0, minute=0;
            for (int j=0; j<al.getTime().length(); j++){
                //lấy giờ
                String ch1 = String.valueOf(al.getTime().charAt(0));
                String ch2 = String.valueOf(al.getTime().charAt(1));
                String t;
                if(ch2.equals(":")){
                    t = ch1;
                }else{
                    t=ch1+ch2;
                }
                hour = Integer.parseInt(t);

                //lấy phút
                String ch3 = String.valueOf(al.getTime().charAt(3));
                String ch4 = String.valueOf(al.getTime().charAt(4));
                //kiem tra neu so cuoi cung cua minute la " " thi chi lay ki tu thu 3
                String m;
                if(ch4.equals(" ")){
                    m =ch3;
                }else{
                    m =ch3+ch4;
                }

                minute = Integer.parseInt(m);

            }
            if(cursor.getInt(5)==1){
                setAlarm(hour, minute, getActivity());
            }
        }
        //bat su kien khi co thay doi du lieu tren adapter
        adapterAlarm.notifyDataSetChanged();
    }

    public void setAlarm(int hour, int minute, Context context){
        //khởi tạo đối tượng calender
        Calendar calendar = Calendar.getInstance();
        //lấy giờ hiện tại của hệ thống
        calendar.setTimeInMillis(System.currentTimeMillis());
        //đặt giờ báo thức
        calendar.set(Calendar.HOUR_OF_DAY, hour);
        calendar.set(Calendar.MINUTE, minute);
        calendar.set(Calendar.SECOND, 0);
        //khởi tạo intent
        intent = new Intent(getContext(), Alarm_Receiver.class);
        intent.putExtra("extra", "yes");
        //khởi tạo đối tượng pending intent
        pendingIntent = PendingIntent.getBroadcast(getContext(), 0, intent, 0);
        //khởi tạo đối tường alarmmanager
        alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        //đặt báo thức lặp lại hằng ngày
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
    }

    public void cancelAlarm(){
        if(alarmManager!=null){
            intent.putExtra("extra", "no");
            alarmManager.cancel(pendingIntent);
            getActivity().sendBroadcast(intent);
        }
    }

    private void deleteItem(final int id){
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("Confirm");
        builder.setMessage("Are you sure, Do you want delete?");
        builder.setNegativeButton("No", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                dialog.dismiss();
            }
        });

        builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                // TODO Auto-generated method stub
                Database = database.initDatabase(getActivity(), DATABASE_NAME);
                Database.delete("Alarm", "ID = ?", new String[]{id+""});

                //doc lại dữ liệu cho listview
                Database = database.initDatabase(getActivity(), DATABASE_NAME);
                Cursor cursor = Database.rawQuery("SELECT*FROM Alarm", null);
                list.clear();
                for(int i=0; i<cursor.getCount(); i++){
                    //di chuyển cursor đến vị trí thứ i
                    cursor.moveToPosition(i);
                    //thêm đối tượng vào list
                    list.add(new alarm(cursor.getInt(0), cursor.getString(1), cursor.getString(2)
                            , cursor.getInt(3), cursor.getInt(4), cursor.getInt(5)));
                }
                //bat su kien khi co thay doi du lieu tren adapter
                adapterAlarm.notifyDataSetChanged();

                Toast.makeText(getActivity(), "Delete sucessfully!", Toast.LENGTH_SHORT).show();
            }
        });
        builder.setIcon(R.drawable.logo);
        builder.create().show();
    }

    @Override
    public void onResume() {
        super.onResume();
    }
}

我尝试在另一项活动

中从cancelAlarm()调用方法FragmentHome
FragmentHome fh = new FragmentHome();
fh.cancelAlarm();

但它不起作用?

1 个答案:

答案 0 :(得分:0)

看起来问题是你永远不会初始化alarmManager变量,所以当这个代码被命中时它是null,所以没有任何反应。

public void cancelAlarm(){
    if(alarmManager!=null){ ...

根据你的代码,你似乎必须在调用cancelAlarm()之前调用setAlarm()。

尝试类似:

FragmentHome fh = new FragmentHome();
fh.setAlarm(12, 30, this);
fh.cancelAlarm();

我建议花点时间学习设置断点并在调试模式下运行应用程序。像这样的错误很容易被发现。