【问题标题】:Display arrray of strings in same TextView with a time interval of 5 seconds以 5 秒的时间间隔在同一 TextView 中显示字符串数组
【发布时间】:2015-12-14 07:42:25
【问题描述】:

我正在开发 android 应用程序以从 url 检索 JSON 数据并显示它。

我的要求:- 我有 JSON 数据数组,我必须每 5 秒显示一次每个数组项数据,一旦执行了所有数组项,它应该像往常一样再次调用 onpostexecute 它应该从第一个数组开始

  private class DownloadJSON extends AsyncTask<Void,Void,Void> {

        @Override
        protected Void doInBackground(Void... params) {

            arraylist = new  ArrayList<HashMap<String, String>>();
            JSONObject jsonobject = JSONfunctions.getJSONfromURL(url);

            try {

                String link = jsonobject.getString("link");
                jsonarray = jsonobject.getJSONArray("api");

                for (int i = 0; i < jsonarray.length(); i++) {

                    HashMap<String, String> map = new HashMap<String, String>();
                    jsonobject = jsonarray.getJSONObject(i);

                    String title = jsonobject.getString("Title");
                    String subtitle = jsonobject.getString("Subtitle");
                    String image = jsonobject.getString("image");

                    map.put("title",jsonobject.getString("Title"));
                    map.put("sub",jsonobject.getString("Subtitle"));
                    map.put("image",link+jsonobject.getString("image"));

                    arraylist.add(map);

                }

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


            return null;
        }


        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);


            for (int i=0; i<arraylist.size();i++){
                final String tit =   arraylist.get(i).get("title");
                final String subtit =   arraylist.get(i).get("sub");
                String img =   arraylist.get(i).get("image");

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                       while (true){
                           try{

                               Thread.sleep(5000);
                               mHandler.post(new Runnable() {
                                   @Override
                                   public void run() {
                                         t1.setText(tit);//t1,t2 is textview
                                         t2.setText(subtit);
                                   }
                               });

                           }catch (Exception e){

                           }
                       }

                    }
                }).start();

            }
        }
    }

实际上,上面的代码部分工作,这意味着它第一次工作,但 5 秒后它正在刷新,但数据在一段时间后没有更新每个项目每 5 秒一次,它应该在项目执行完成后重新启动 onpostexecute,然后像往常一样,依此类推

【问题讨论】:

  • t1.setText(tit);//t1,t2 is textview t2.setText(subtit);将在调用 onPostExecute 后 5 秒后仅执行一次。您需要设置警报管理器以每 5 秒启动一次异步任务
  • 有很多事情是错误的,比如你在 for 循环中创建一个线程等等。请检查您的代码。我建议使用 Alarm Manager 或简单地使用 timertask。
  • @Dhina 你的意思是我必须使用警报管理器而不是处理程序?
  • @IntelliJAmiya 我只使用处理程序,你能告诉我在我的要求中我们必须如何使用处理程序
  • @Dhina 我不想启动整个 asyntask 我只想启动 onpostexecute 因为我已经从 url 获取并将其存储到 arraylist 我想执行 arraylist 中的每个项目应该来自 5秒的

标签: android arrays json


【解决方案1】:

试试这个:

全局声明:

private TimerTask NoticeTimerTask;
  private final Handler handler = new Handler();
  Timer timer = new Timer();

从 onPostExecute() 调用函数

        setViews(arraylist);

setViews()

 private void setViews(final ArrayList<HashMap<String, String>> arraylist) {
        final int max = arraylist.size();
        final int[] current = {0};
        NoticeTimerTask = new TimerTask() {
            public void run() {
                handler.post(new Runnable() {
                    public void run() {
                        if(current[0] <max) {
                            Log.d("NoticeTimerTask", String.valueOf(current[0]));
                            t1.setText(arraylist.get(current[0]).get("title"));
                            t2.setText(arraylist.get(current[0]).get("sub"));
                            current[0]++;
                        }
                        else {
                            Log.d("NoticeTimerTask", String.valueOf(current[0]) + " timer.cancel();");
                           // current[0] = 0; // do this if yu want to loop back from first item
                            timer.cancel(); // do this if you want to stop
                        }
                    }
                });
            }
        };
        if (timer!=null) {
            timer.schedule(NoticeTimerTask, 0, 5000);
        }
    }

【讨论】:

  • 是的,它工作正常,但如果我给 t1 的 onclick 列表器,如 public void onClick(View v) { String str= arraylist.get(current[0]).get("title"); Toast.makeText(getApplicationContext(),""+arraylist.get(current[0]).get("title"),Toast.LENGTH_SHORT).show();},如果我点击第一项,我的数组列表中有三个 3 项,如果我点击第二项,则 toast 显示为第二项显示第三,你能告诉我如何获得正确的位置
  • 可能在 toast 启动时已经过了 5 秒,因此获取下一个项目?
  • 尝试增加计时器值并检查是否是确切原因。
  • 我已经将计时器值从 5000 增加到 10000,我遇到了同样的问题,我已经说过我的数组列表中有三个项目。如果我单击第一个,则显示第二个,如果单击第二个,则显示第三个,如果单击第三个,则索引越界异常
  • 它非常适合我..t1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getApplicationContext(),t1.getText().toString(),Toast.LENGTH_LONG).show(); } });
【解决方案2】:

你不需要为每个循环创建新的TimerTask,只需将定时器安排5s,获取并更新TimerTask的run方法上的值

//declare index variable
private int index =0;

// 在你的 postExecute 方法上调用这个:

timer = new Timer();

timerTask = new TimerTask() {

        public void run() {



            //use a handler to run a toast that shows the current timestamp

            handler.post(new Runnable() {

                public void run() {
                final String tit =   arraylist.get(index).get("title");
                final String subtit =   arraylist.get(index).get("sub");
                String img =   arraylist.get(index).get("image");
                t1.setText(tit);//t1,t2 is textview
                t2.setText(subtit);
               index ++;

                }

            });

        }

    };
    timer.schedule(timerTask, 0, 5000); //

【讨论】:

    猜你喜欢
    • 2019-05-06
    • 2023-03-07
    • 1970-01-01
    • 2020-10-18
    • 1970-01-01
    • 2013-06-03
    • 1970-01-01
    • 2021-09-21
    • 2012-08-24
    相关资源
    最近更新 更多