2016-12-28 68 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
相關問題