2016-12-28 70 views
-1

我从数据库中提取数据并将其显示为RecyclerView。但我必须更新RecyclerViewx milliseconds/seconds我必须更新我的RecyclerView适配器每x秒

这是我的代码。请帮忙。

@Override 
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { 
    super.onCreateView(inflater, container, savedInstanceState); 

    View view = inflater.inflate(R.layout.fragment_download, container, false); 

    rvLatestTrack = (RecyclerView) view.findViewById(R.id.recyclerview); 
    linearLayoutEmpty = (LinearLayout) view.findViewById(R.id.linearLayoutEmpty); 

    arrayList = new ArrayList<>(); 
    rvLatestTrack.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false)); 
    getData(); 
    return view; 
} 
public void getData() { 
    Database database = new Database(getContext()); 
    SQLiteDatabase sqLiteDatabase = database.getWritableDatabase(); 
    String SELECT_DATA_QUERY = "SELECT * FROM " + DB_Const.TABLE_NAME_SONGS; 
    Cursor cursor = sqLiteDatabase.rawQuery(SELECT_DATA_QUERY, null); 
    if (cursor.getCount() != 0) { 
     if (cursor.moveToFirst()) { 
      DownloadsModel downloadsModel; 
      do { 
       String fileName = cursor.getString(cursor.getColumnIndex(DB_Const.SONG_TITLE)); 
       String Download_percentage = cursor.getString(cursor.getColumnIndex(DB_Const.Completed_percentage)); 
       String SongURL = cursor.getString(cursor.getColumnIndex(DB_Const.URL)); 
       downloadsModel = new DownloadsModel(fileName, Download_percentage, SongURL); 
       arrayList.add(downloadsModel); 
      } while (cursor.moveToNext()); 
      rvLatestTrack.setAdapter(new DownloadsAdaptor(getContext(), arrayList)); 
     } 
     cursor.close(); 
    } else { 
     linearLayoutEmpty.setVisibility(View.VISIBLE); 
    } 
} 

回答

-1

您必须声明你DownloadsAdapter全球:

DownloadsAdapter adapter = new DownloadsAdaptor(getContext(), arrayList) 

然后

private void update() { 
    Handler handler = new Handler(); 
    handler.postDelayed(new Runnable() { 
    @Override 
    public void run() { 
     arrayList = ... 
     adapter.notifyDataSetChanged(); //or notifyItemInserted or notifyItemRemoved as per your need. 
     update(); // recursive call 
    } 
    }, 1000); 
} 

这将更新每1000微秒(×时间)的名单,并通知RecyclerView适配器的数据发生变化。

+0

这只是做一次 – Thinsky

+0

没有得到你吗? –

+0

未解决问题 –

0

在适配器构造函数中添加一个计时器来安排任务

TimerTask task = new TimerTask() { 
      @Override 
      public void run() { 
       runOnUiThread(new Runnable() { 
        @Override 
        public void run() { 
         getData(); 
        } 
       }); 
      } 
     }; 
new Timer().schedule(task, 0, 3000); 
+0

这不是解决了我的问题 –

0

我建议你使用内置AsyncTask

  • 让你做一个昂贵的工作后台线程不会导致UI口吃
  • 有一个onProgressUpdate回调正是为了更新UI
相关问题