-1

I have list of music that user set time to play. I want to have a button to cancel m count down timer . I test some way but it doesn't work at all. here is my code to play and set time to play.

public class Main extends Activity {

public static int hour_device, minute_device;
public static int hour_user, minute_user;
Splash splash;
ListView listView;
Adaptor adaptor;
private MediaPlayer mediaPlayer;
static View lastview = null;
static MyIndexStore indexStore;

List<String> lines1 = new ArrayList<String>();
List<String> lines2 = new ArrayList<String>();
static List<String> array_audio = new ArrayList<String>();

InputStream in;
BufferedReader reader;
String line = "1";
String[] tracks;
String[] names;
String[] infos;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    indexStore = new MyIndexStore(getApplicationContext());
    setContentView(R.layout.main_activity);


    splash = new Splash(this);
    splash.set_identity("1");


    initiate();
    mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.a1);
    //lastview = null;
    listView = (ListView) findViewById(R.id.list);
    ReadText1();
    names = lines1.toArray(new String[0]);// = {"track one","the seconnd track","a nice track","name name name","the seconnd track","a nice track","name name name"};
    ReadText2();
    infos = lines2.toArray(new String[0]);
    tracks = array_audio.toArray(new String[0]);
    adaptor = new Adaptor(getApplicationContext(), tracks, names, infos);
    listView.setAdapter(adaptor);
    mediaPlayer.setOnCompletionListener(new OnCompletionListener() {

        @Override
        public void onCompletion(MediaPlayer arg0) {
            if (lastview != null) {
                ImageView play = (ImageView) lastview.findViewById(R.id.play_stop);
                play.setImageResource(R.drawable.n_btn_play_unselected);
            }
        }
    });
}

private static void initiate() {
    Field[] fields = R.raw.class.getFields();
    array_audio.clear();
    for (int count = 0; count < fields.length; count++) {
        array_audio.add("a" + (count + 1));
    }
}

private void play(int index) {
    mediaPlayer.release();
    index++;
    String s = "a" + index;
    Resources resources = getResources();
    final int resourceId = resources.getIdentifier(s, "raw", getPackageName());

    try {
        mediaPlayer = MediaPlayer.create(this, resourceId);
        mediaPlayer.start();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

@Override
protected void onPause() {
    mediaPlayer.release();
    listView.invalidateViews();
    super.onPause();
}


private void ReadText1() {
    lines1.clear();
    line = "1";
    try {
        in = this.getAssets().open("names.txt");
        reader = new BufferedReader(new InputStreamReader(in));
        while (line != null) {
            line = reader.readLine();
            if (line != null)
                lines1.add(line);
            else
                break;
        }

    } catch (IOException e) {
        e.printStackTrace();
    }
}

private void ReadText2() {
    lines2.clear();
    line = "1";
    try {
        in = this.getAssets().open("infos.txt");
        reader = new BufferedReader(new InputStreamReader(in));
        while (line != null) {
            line = reader.readLine();
            if (line != null)
                lines2.add(line);
            else
                break;
        }

    } catch (IOException e) {
        e.printStackTrace();
    }
}


public class Adaptor extends ArrayAdapter<String> {

    private final Context context;
    private final String[] tracks;
    private final String[] names;
    private final String[] infos;
    private HashMap<Integer,String> textMap;
    Typeface type_face;


    public Adaptor(Context context, String[] tracks, String[] names, String[] infos) {
        super(context, R.layout.track, tracks);
        this.context = context;
        this.tracks = tracks;
        this.names = names;
        this.infos = infos;
        type_face = Typeface.createFromAsset(context.getAssets(), "BTitrBd.ttf");
        this.textMap = new HashMap<>();
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        final View rowView = inflater.inflate(R.layout.track, parent, false);

        TextView name = (TextView) rowView.findViewById(R.id.track_name);
        final TextView time = (TextView) rowView.findViewById(R.id.time);
        //populate the textview from map
        if(textMap!=null && textMap.get(new Integer(position))!=null){
            time.setText(textMap.get(new Integer(position)));
        }
        name.setText(names[position]);
        name.setTypeface(type_face);
        name.setTypeface(type_face);
        final ImageView ringtone = (ImageView) rowView.findViewById(R.id.ringtone);
        if (position == indexStore.getindex())
            ringtone.setImageResource(R.drawable.n_btn_ringtone_seted);
        final ImageView play = (ImageView) rowView.findViewById(R.id.play_stop);
        ringtone.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                LayoutInflater factory = LayoutInflater.from(Main.this);
                final View deleteDialogView = factory.inflate(
                        R.layout.mylayout, null);
                final AlertDialog deleteDialog = new AlertDialog.Builder(Main.this).create();
                deleteDialog.setView(deleteDialogView);

                TextView device_time = (TextView) deleteDialogView.findViewById(R.id.current_time);
                Calendar c = Calendar.getInstance();
                int hour = c.get(Calendar.HOUR_OF_DAY);
                int minute = c.get(Calendar.MINUTE);
                hour_device = hour;
                minute_device = minute;
                device_time.setText(hour_device + ":" + minute_device);

                deleteDialogView.findViewById(R.id.set).setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {

                        TimePicker timePicker = (TimePicker) deleteDialogView.findViewById(R.id.timepicker);
                        timePicker.setIs24HourView(true);
                        hour_user = timePicker.getCurrentHour();
                        minute_user = timePicker.getCurrentMinute();
                        String time1 = hour_device + ":" + minute_device;
                        String time2 = hour_user + ":" + minute_user;
                        SimpleDateFormat format = new SimpleDateFormat("HH:mm");
                        Date date1 = null;
                        try {
                            date1 = format.parse(time1);
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        Date date2 = null;
                        try {
                            date2 = format.parse(time2);
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        long result = date2.getTime() - date1.getTime();


                        new CountDownTimer(result, 1000) {

                            public void onTick(long millisUntilFinished) {
                                time.setText(("seconds remaining: " + millisUntilFinished / 1000));
                                //create HashMap<Integer,String> textMap at the constructer of the adapter
                                //now fill this info int'o it
                                textMap.put(new Integer(position), "seconds remaining: " + millisUntilFinished / 1000);
                                //notify about the data change
                                notifyDataSetChanged();

                            }

                            public void onFinish() {
                                time.setVisibility(View.INVISIBLE);
                                //create HashMap<Integer,String> textMap at the constructer of the adapter
                                //now fill this info into it
                                textMap.put(new Integer(position),null);
                                //notify about the data change
                                notifyDataSetChanged();
                                Toast.makeText(getApplicationContext(), "finish", Toast.LENGTH_LONG).show();
                                if (rowView != lastview || mediaPlayer == null) {
                                    play(position);
                                    if (lastview != null)
                                        lastview = rowView;
                                } else {
                                    play.setImageResource(R.drawable.n_btn_play_unselected);
                                    mediaPlayer.release();
                                    lastview = null;
                                }


                            }

                        }.start();
                        deleteDialog.dismiss();
                    }
                });


                deleteDialog.show();


            }
        });

        play.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                if (rowView != lastview || mediaPlayer == null) {
                    play(position);
                    if (lastview != null)
                        lastview = rowView;
                } else {
                    play.setImageResource(R.drawable.n_btn_play_unselected);
                    mediaPlayer.release();

                    lastview = null;
                }
            }
        });
        return rowView;
    }





}

}

nsr
  • 95
  • 10
  • 2
    Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: [How to create a Minimal, Complete, and Verifiable example](http://www.stackoverflow.com/help/mcve). – Yassin Hajaj May 25 '16 at 05:31
  • so you dont know how to cancel the `CountDownTImer`? – pskink May 25 '16 at 05:32
  • Iio will edit this, thanks for suggestion@YassinHajaj – nsr May 25 '16 at 05:33
  • Call `CountDownTimer.cancel();` to cancel CountDownTimer – ρяσѕρєя K May 25 '16 at 05:33
  • it cant be cause this in inner class in side the getview@ρяσѕρєяK – nsr May 25 '16 at 05:39
  • yes I dont know how to cancel it @pskink – nsr May 25 '16 at 05:40
  • did you read `CountDownTimer` documentation? – pskink May 25 '16 at 05:43
  • yes , as you and the other said CountDownTimer.cancel(); must cancel this method. but if you pay attention I use CountDownTimer is one of my button onlick.@pskink – nsr May 25 '16 at 05:47

2 Answers2

1

make the count down timer an instance variable;

private CountDownTimer timer;

then delegate your count to this variable:

@Override
public void onClick(View v) {
    ...
    timer = new CountDownTimer(result, 1000) {
        ...
    }
}

now you can stop the timer whenever you want to:

timer.cancel();
Martin Frank
  • 3,238
  • 1
  • 25
  • 41
Malith Lakshan
  • 712
  • 5
  • 11
0

Check this code, working Successfull
call class from here

       timer = new CounterClass(timeInmilles, 1000);
                    timer.start();

CounterClass is here

  public class CounterClass extends CountDownTimer {
       public CounterClass(long millisInFuture, long countDownInterval) {
        super(millisInFuture, countDownInterval);
    }

    @Override
    public void onFinish() {

    }
      public void onTick(long millisUntilFinished) {
      }
}

use to cancel see below line

timer.cancel()
Aditay Kaushal
  • 630
  • 5
  • 16