我无法在TextView中显示计时器

时间:2018-08-12 15:41:27

标签: java android listview countdowntimer

我创建了一个带有倒数计时器的Listview,下面是代码:

public class TicketAdapter extends ArrayAdapter<TicketModel> implements View.OnClickListener{

    private ArrayList<TicketModel> dataSet;
    Context mContext;
    long timeLeftMS ;

    // View lookup cache
    private class ViewHolder {
        TextView txtName;
        TextView txtType;
        TextView txtTempsRestant;
        TextView txtDate;
        TextView txtSLA;
        ImageView info;
        RelativeLayout layout;

        Handler handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                System.out.println("handler");

                int hour = (int) ((timeLeftMS / (1000*60*60)) % 24);
                int minute = (int) ((timeLeftMS / (60000)) % 60);
                int seconde = (int)timeLeftMS % 60000 / 1000;

                String timeLeftText = "";

                if (hour<10) timeLeftText += "0";
                timeLeftText += hour;
                timeLeftText += ":";
                if (minute<10) timeLeftText += "0";
                timeLeftText += minute;
                timeLeftText += ":";
                if (seconde<10) timeLeftText += "0";
                timeLeftText += seconde;

                txtTempsRestant.setText(timeLeftText);
            }
        };

    }


    public TicketAdapter(ArrayList<TicketModel> data, Context context) {
        super(context, R.layout.row_item_ticket, data);
        this.dataSet = data;
        this.mContext=context;
        //startUpdateTimer();
    }


    @Override
    public void onClick(View v) {
        int position=(Integer) v.getTag();
        Object object= getItem(position);
        TicketModel TicketModel=(TicketModel)object;

        switch (v.getId())
        {
            case R.id.item_info:

                Snackbar.make(v, "is Late? : " +TicketModel.isTicketEnRetard(), Snackbar.LENGTH_LONG)
                        .setAction("No action", null).show();
                break;
        }
    }

    private int lastPosition = -1;


    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // Get the data item for this position
        TicketModel TicketModel = getItem(position);
        // Check if an existing view is being reused, otherwise inflate the view
        final ViewHolder viewHolder; // view lookup cache stored in tag

        final View result;

        if (convertView == null) {

            viewHolder = new ViewHolder();
            LayoutInflater inflater = LayoutInflater.from(getContext());
            convertView = inflater.inflate(R.layout.row_item_ticket, parent, false);
            viewHolder.txtName = (TextView) convertView.findViewById(R.id.titreTV);
            viewHolder.txtDate = (TextView) convertView.findViewById(R.id.dateTV);
            viewHolder.txtSLA = (TextView) convertView.findViewById(R.id.slaTV);
            viewHolder.txtTempsRestant = (TextView) convertView.findViewById(R.id.SLARestantTV);
            viewHolder.info = (ImageView) convertView.findViewById(R.id.item_info);
            viewHolder.layout = (RelativeLayout) convertView.findViewById(R.id.backgroundRow);


            result=convertView;

            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
            result=convertView;
        }

        Animation animation = AnimationUtils.loadAnimation(mContext, (position > lastPosition) ? R.anim.up_from_bottom : R.anim.down_from_top);
        result.startAnimation(animation);
        lastPosition = position;

        viewHolder.txtName.setText(TicketModel.getTitreTicket());
        viewHolder.txtDate.setText(TicketModel.getDateTicket());
        viewHolder.txtSLA.setText(TicketModel.getSlaTicket());
        //viewHolder.txtTempsRestant.setText(TicketModel.getTempsRestantTicket());
        viewHolder.info.setImageResource(getIconUrgence(TicketModel.getUrgenceTicket()));
        viewHolder.layout.setBackgroundColor(getColorBG(TicketModel.isTicketEnRetard()));
        viewHolder.info.setOnClickListener(this);
        viewHolder.info.setTag(position);

        System.out.println("Here : "+TicketModel.getTitreTicket()); //getting each item's name
        System.out.println("Time = "+TicketModel.getTempsRestantTicket()); //getting each item's time left and it's correct

        timeLeftMS = Long.valueOf(TicketModel.getTempsRestantTicket());


        startTimer(viewHolder.handler);



        // Return the completed view to render on screen
        return convertView;
    }

    private void startTimer(final Handler handler) {
        CountDownTimer countDownTimer = new CountDownTimer(timeLeftMS, 1000) {

            @Override
            public void onTick(long l) {
                timeLeftMS = l;
                handler.sendEmptyMessage(0);
            }

            @Override
            public void onFinish() {

            }
        }.start();
    }


    private int getColorBG(boolean ticketEnRetard) {
        int color;

        if (ticketEnRetard){
            color = Color.parseColor("#3caa0000");
        }
        else{
            color = Color.parseColor("#ffffff");
        }
        return color;
    }



    private int getIconUrgence(String urgenceTicket) {
        int icon;

        if((urgenceTicket.equals("Très basse"))||(urgenceTicket.equals("Basse"))){
            icon = R.drawable.basse;
        }
        else if((urgenceTicket.equals("Haute"))||(urgenceTicket.equals("Très haute"))){
            icon = R.drawable.haute;
        }
        else {
            icon = R.drawable.moyenne;
        }

        return icon;
    }


}

TicketModel 类:

public class TicketModel {
    String titreTicket;
    String slaTicket;
    String DateTicket;

    String UrgenceTicket;

    boolean ticketEnRetard;

    String TempsRestantTicket;

    public TicketModel(String titreTicket, String slaTicket, String dateTicket, String tempsRestantTicket) {
        this.titreTicket = titreTicket;
        this.slaTicket = slaTicket;
        DateTicket = dateTicket;
        TempsRestantTicket = tempsRestantTicket;
    }

    public String getTitreTicket() {
        return titreTicket;
    }

    public String getSlaTicket() {
        return slaTicket;
    }

    public String getDateTicket() {
        return DateTicket;
    }

    public String getUrgenceTicket() {
        return UrgenceTicket;
    }

    public void setUrgenceTicket(String urgenceTicket) {
        UrgenceTicket = urgenceTicket;
    }

    public void setTempsRestantTicket(String tempsRestantTicket) {
        TempsRestantTicket = tempsRestantTicket;
    }

    public String getTempsRestantTicket() {
        return TempsRestantTicket;
    }

    public boolean isTicketEnRetard() {
        return ticketEnRetard;
    }

    public void setTicketEnRetard(boolean ticketEnRetard) {
        this.ticketEnRetard = ticketEnRetard;
    }
}

我要填充ListView的位置:

public class ListTickets extends AppCompatActivity {

    ArrayList<TicketModel> TicketModels;
    ListView listView;
    private static TicketAdapter adapter;
    String session_token, nameUser, idUser, firstnameUser, nbTicket;
    RequestQueue queue;
    String titreTicket, slaTicket, urgenceTicket,
    demandeurTicket, categorieTicket, etatTicket, dateDebutTicket,
            dateEchanceTicket, dateClotureTicket, descriptionTicket, lieuTicket;
    boolean ticketEnretard;

    public static int nbTicketTab = 6;
    public static int nbInfoTicket = 12;

    public static String[][] ticketTab ;
    public static String[][] infoTicket ;

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

        queue = Volley.newRequestQueue(this);

        Intent i = getIntent();
        session_token = i.getStringExtra("session");
        nbTicket = i.getStringExtra("nb");
        nameUser = i.getStringExtra("nom");
        firstnameUser = i.getStringExtra("prenom");
        idUser = i.getStringExtra("id");

        listView=(ListView)findViewById(R.id.list);


        TicketModels = new ArrayList<>();
        ticketTab = new String[Integer.valueOf(nbTicket)][nbTicketTab];
        infoTicket = new String[Integer.valueOf(nbTicket)][nbInfoTicket];


        String url = FirstEverActivity.GLPI_URL+"search/Ticket";



        List<KeyValuePair> params = new ArrayList<>();
        params.add(new KeyValuePair("criteria[0][field]","5"));
        params.add(new KeyValuePair("criteria[0][searchtype]","equals"));
        params.add(new KeyValuePair("criteria[0][value]",idUser));
        params.add(new KeyValuePair("forcedisplay[0]","4"));
        params.add(new KeyValuePair("forcedisplay[1]","10"));
        params.add(new KeyValuePair("forcedisplay[2]","7"));
        params.add(new KeyValuePair("forcedisplay[3]","12"));
        params.add(new KeyValuePair("forcedisplay[4]","15"));
        params.add(new KeyValuePair("forcedisplay[5]","30"));
        params.add(new KeyValuePair("forcedisplay[6]","18"));
        params.add(new KeyValuePair("forcedisplay[7]","21"));
        params.add(new KeyValuePair("forcedisplay[8]","83"));
        params.add(new KeyValuePair("forcedisplay[9]","82"));
        params.add(new KeyValuePair("forcedisplay[10]","16"));

        final JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, generateUrl(url, params), null,
                new Response.Listener<JSONObject>()
                {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            JSONArray Jdata = response.getJSONArray("data");
                            for (int i=0; i < Jdata.length(); i++) {
                                    try {
                                        JSONObject oneTicket = Jdata.getJSONObject(i);
                                        // Récupération des items pour le row_item
                                        titreTicket = oneTicket.getString("1");
                                        slaTicket = oneTicket.getString("30");
                                        dateDebutTicket = oneTicket.getString("15");
                                        urgenceTicket = oneTicket.getString("10");

                                        //Récupération du reste
                                        demandeurTicket = oneTicket.getString("4");
                                        categorieTicket = oneTicket.getString("7");
                                        etatTicket = oneTicket.getString("12");
                                        dateEchanceTicket = oneTicket.getString("18");
                                        descriptionTicket = oneTicket.getString("21");

                                        lieuTicket = oneTicket.getString("83");
                                        dateClotureTicket = oneTicket.getString("16");
                                        ticketEnretard = getBooleanFromSt(oneTicket.getString("82"));


                                        System.out.println("Direct = " + oneTicket.getString("82") + "\n After f(x) = " + getBooleanFromSt(oneTicket.getString("82")));
                                    } catch (JSONException e) {
                                        Log.e("Nb of data: "+Jdata.length()+" || "+"Error JSONArray at "+i+" : ", e.getMessage());
                                    }


                                ticketTab[i][0] = titreTicket;
                                ticketTab[i][1] = slaTicket;
                                ticketTab[i][2] = dateDebutTicket;
                                ticketTab[i][3] = urgenceText(urgenceTicket);
                                ticketTab[i][4] = calculTempsRestant(dateDebutTicket, slaTicket); //TimeLeft value here
                                ticketTab[i][5] = String.valueOf(ticketEnretard);




                                infoTicket[i][0] = demandeurTicket;
                                infoTicket[i][1] = urgenceText(urgenceTicket);
                                infoTicket[i][2] = categorieTicket;
                                infoTicket[i][3] = etatText(etatTicket);
                                infoTicket[i][4] = dateDebutTicket;
                                infoTicket[i][5] = slaTicket;
                                infoTicket[i][6] = dateEchanceTicket;
                                infoTicket[i][7] = titreTicket;
                                infoTicket[i][8] = descriptionTicket;
                                infoTicket[i][9] = lieuTicket;
                                infoTicket[i][10] = calculTempsRestant(dateDebutTicket, slaTicket);
                                infoTicket[i][11] = dateClotureTicket;

                                System.out.println("Temps restant = "+calculTempsRestant(dateDebutTicket, slaTicket));
                                System.out.println("SLA = "+slaTicket);
                                System.out.println("Between : "+getBetweenBrackets(slaTicket));
                                System.out.println("Minimum : "+getMinTemps(slaTicket));
                                System.out.println("Maximim : "+getMaxTemps(slaTicket));



                            }


                            System.out.println("*** Tab Ticket ***");
                            System.out.println("isLate: "+ticketTab[0][5]);
                            System.out.println("\n\n*** Info Ticket ***");
                            System.out.println("Titre: "+infoTicket[0][7]);

                            // Populate the ListView
                            addModelsFromTab(ticketTab);

                            adapter = new TicketAdapter(TicketModels,getApplicationContext());

                            listView.setAdapter(adapter);
                            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                @Override
                                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                                    TicketModel TicketModel= TicketModels.get(position);

                                    Snackbar.make(view, "Index = "+position, Snackbar.LENGTH_LONG)
                                            .setAction("No action", null).show();

                                    Intent i = new Intent(getApplicationContext(), InfoTicket.class);
                                    i.putExtra("session",session_token);
                                    i.putExtra("nom",nameUser);
                                    i.putExtra("prenom",firstnameUser);
                                    i.putExtra("id",idUser);
                                    i.putExtra("infoTicket", infoTicket[position]);

                                    startActivity(i);



                                }
                            });


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


                    }
                },
                new Response.ErrorListener()
                {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        //progressBar.setVisibility(View.GONE);
                        Log.e("Error.Response", error.toString());
                    }

                }
        ){
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> params = new HashMap<String, String>();
                params.put("App-Token",FirstEverActivity.App_Token);
                params.put("Session-Token",session_token);
                return params;
            }

        };

        // add it to the RequestQueue
        queue.add(getRequest);

    }


        private void addModelsFromTab(String[][] ticketTab) {
        for (int i = 0; i < ticketTab.length; i++){
                TicketModel ticket = new TicketModel(ticketTab[i][0], ticketTab[i][1], ticketTab[i][2], ticketTab[i][4]);
                ticket.setUrgenceTicket(ticketTab[i][3]);
                ticket.setTicketEnRetard(Boolean.parseBoolean(ticketTab[i][5]));
                //ticket.setTempsRestantTicket(ticketTab[i][4]);

                TicketModels.add(ticket);
        }
    }


    private String calculTempsRestant(String dateDebutTicket, String slaTicket) {
        String minTemps = getMinTemps(slaTicket);
        String maxTemps = getMaxTemps(slaTicket);

        long dateDebutMS = getDateDebutMS(dateDebutTicket);
        long currentTimeMS = CurrentTimeMS();

        long minTempsMS = hourToMSConvert(minTemps);

        long differenceCurrentDebut = currentTimeMS - dateDebutMS;

        long tempsRestant = minTempsMS - differenceCurrentDebut;

        return String.valueOf(tempsRestant);
    }


}

我的问题是我想在timeLeftText TextView中显示计时器(txtTempsRestant字符串),但是我无法访问它。谁能给我建议?

当我在控制台中打印并且输出正确时,但是我无法显示它。我应该改变工作方式吗?

3 个答案:

答案 0 :(得分:1)

修改后的适配器类,以使倒计时正常工作。

public class TicketAdapter extends ArrayAdapter<TicketModel> implements View.OnClickListener{

    private ArrayList<TicketModel> dataSet;
    Context mContext;

    // View lookup cache
    private class ViewHolder {
        TextView txtName;
        TextView txtType;
        TextView txtTempsRestant;
        TextView txtDate;
        TextView txtSLA;
        ImageView info;
        RelativeLayout layout;

        Handler handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                System.out.println("handler");

                Bundle bundle = msg.getData();
                long timeLeftMS = bundle.getLong("time");
                int hour = (int) ((timeLeftMS / (1000*60*60)) % 24);
                int minute = (int) ((timeLeftMS / (60000)) % 60);
                int seconde = (int)timeLeftMS % 60000 / 1000;

                String timeLeftText = "";

                if (hour<10) timeLeftText += "0";
                timeLeftText += hour;
                timeLeftText += ":";
                if (minute<10) timeLeftText += "0";
                timeLeftText += minute;
                timeLeftText += ":";
                if (seconde<10) timeLeftText += "0";
                timeLeftText += seconde;

                txtTempsRestant.setText(timeLeftText);
            }
        };

        public void startTimer(long timeLeftMS) {
            CountDownTimer countDownTimer = new CountDownTimer(timeLeftMS, 1000) {

                @Override
                public void onTick(long l) {
                    Bundle bundle = new Bundle();
                    bundle.putLong("time", l);
                    Message message = new Message();
                    message.setData(bundle);
                    handler.sendMessage(message);
                }

                @Override
                public void onFinish() {

                }
            }.start();
        }

      }


    public TicketAdapter(ArrayList<TicketModel> data, Context context) {
        super(context, R.layout.row_item_ticket, data);
        this.dataSet = data;
        this.mContext=context;
        //startUpdateTimer();
    }


    @Override
    public void onClick(View v) {
        int position=(Integer) v.getTag();
        Object object= getItem(position);
        TicketModel TicketModel=(TicketModel)object;

        switch (v.getId())
        {
            case R.id.item_info:

                Snackbar.make(v, "is Late? : " +TicketModel.isTicketEnRetard(), Snackbar.LENGTH_LONG)
                        .setAction("No action", null).show();
                break;
        }
    }

    private int lastPosition = -1;


    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // Get the data item for this position
        TicketModel TicketModel = getItem(position);
        // Check if an existing view is being reused, otherwise inflate the view
        final ViewHolder viewHolder; // view lookup cache stored in tag

        final View result;

        if (convertView == null) {

            viewHolder = new ViewHolder();
            LayoutInflater inflater = LayoutInflater.from(getContext());
            convertView = inflater.inflate(R.layout.row_item_ticket, parent, false);
            viewHolder.txtName = (TextView) convertView.findViewById(R.id.titreTV);
            viewHolder.txtDate = (TextView) convertView.findViewById(R.id.dateTV);
            viewHolder.txtSLA = (TextView) convertView.findViewById(R.id.slaTV);
            viewHolder.txtTempsRestant = (TextView) convertView.findViewById(R.id.SLARestantTV);
            viewHolder.info = (ImageView) convertView.findViewById(R.id.item_info);
            viewHolder.layout = (RelativeLayout) convertView.findViewById(R.id.backgroundRow);


            result=convertView;
viewHolder.startTimer(Long.valueOf(TicketModel.getTempsRestantTicket()));
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
            result=convertView;
        }

        Animation animation = AnimationUtils.loadAnimation(mContext, (position > lastPosition) ? R.anim.up_from_bottom : R.anim.down_from_top);
        result.startAnimation(animation);
        lastPosition = position;

        viewHolder.txtName.setText(TicketModel.getTitreTicket());
        viewHolder.txtDate.setText(TicketModel.getDateTicket());
        viewHolder.txtSLA.setText(TicketModel.getSlaTicket());
        //viewHolder.txtTempsRestant.setText(TicketModel.getTempsRestantTicket());
        viewHolder.info.setImageResource(getIconUrgence(TicketModel.getUrgenceTicket()));
        viewHolder.layout.setBackgroundColor(getColorBG(TicketModel.isTicketEnRetard()));
        viewHolder.info.setOnClickListener(this);
        viewHolder.info.setTag(position);

        System.out.println("Here : "+TicketModel.getTitreTicket()); //getting each item's name
        System.out.println("Time = "+TicketModel.getTempsRestantTicket()); //getting each item's time left and it's correct    

        // Return the completed view to render on screen
        return convertView;
    }

    private int getColorBG(boolean ticketEnRetard) {
        int color;

        if (ticketEnRetard){
            color = Color.parseColor("#3caa0000");
        }
        else{
            color = Color.parseColor("#ffffff");
        }
        return color;
    }



    private int getIconUrgence(String urgenceTicket) {
        int icon;

        if((urgenceTicket.equals("Très basse"))||(urgenceTicket.equals("Basse"))){
            icon = R.drawable.basse;
        }
        else if((urgenceTicket.equals("Haute"))||(urgenceTicket.equals("Très haute"))){
            icon = R.drawable.haute;
        }
        else {
            icon = R.drawable.moyenne;
        }

        return icon;
    }


}

答案 1 :(得分:0)

如果要更改值,则不想将TextView声明为静态。

尝试在此方法之外声明它:

public class TicketAdapter extends ArrayAdapter<TicketModel> implements       View.OnClickListener{

    private ArrayList<TicketModel> dataSet;
    Context mContext;
    static long timeLeftMS = Long.valueOf(TicketModel.getTempsRestantTicket());


     private  TextView txtTempsRestant ;

    // View lookup cache
    private static class ViewHolder {
        TextView txtName;
        TextView txtType;
        TextView txtDate;
        TextView txtSLA;
        ImageView info;
        RelativeLayout layout;

        TextView txtTempsRestant ;
    }

答案 2 :(得分:0)

嗨,我有一个很好的密码 因为你不需要左右3,....的定义3 textview 您将创建一个TextView并将此代码用于创建

    private void Time() {

    mCountTimer = new CountDownTimer(aTime, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            aMinute = (int) (millisUntilFinished / 1000) / 60;
            mSecond = (int) (millisUntilFinished / 1000) % 60;
            mTimer.setText(String.format(Locale.getDefault(), "%d:%02d", aMinute, mSecond));
        }
        @Override
        public void onFinish() {
            mTimer.setText(String.format(Locale.getDefault(), "%d:%02d", 0, 0));
            mSend_Again.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                //Your EVENT
                }
            });

        }
    }.start();

}