我想在RecyclerView上实时更改数据。

huangapple go评论76阅读模式
英文:

i want to make realtime changing data On RecyclerView

问题

I'm trying to refresh the data every 1 second in my RecyclerView. I'm using an API, and when there's a change in the API data, I want to update my RecyclerView without using the swiper. Alternatively, I want to simulate a swiper swipe every 1 second. Here's my code:

public class InformationNow extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {
    private RequestQueue requestQueue;
    private SwipeRefreshLayout refresh;
    private ArrayList<TrashCanModel> trashCanModels = new ArrayList<>();
    private JsonArrayRequest arrayRequest;
    private Dialog dialog;
    private RecyclerView recyclerView;
    private InformationNowAdapter informationNowAdapter;
    private String url = "http://192.168.1.34:9090/TrashCanData/lastrow";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_information_now);
        refresh = (SwipeRefreshLayout) findViewById(R.id.Swiper);
        recyclerView = (RecyclerView) findViewById(R.id.Now);

        dialog = new Dialog(this);

        refresh.setOnRefreshListener(this);
        refresh.post(new Runnable() {
            @Override
            public void run() {
                trashCanModels.clear();
                getData();
            }
        });

        // ... (other code)
    }

    private void getData() {
        // ... (getData implementation)
    }

    private void adapterPush(ArrayList<TrashCanModel> trashCanModels) {
        // ... (adapterPush implementation)
    }

    @Override
    public void onRefresh() {
        trashCanModels.clear();
        getData();
    }
}

public class InformationNowAdapter extends RecyclerView.Adapter<InformationNowAdapter.MyViewHolder> {
    // ... (InformationNowAdapter implementation)
}

If you want to refresh the data every 1 second, you can use a Handler to achieve this. Here's how you can modify your InformationNow class to achieve the desired behavior:

public class InformationNow extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {
    // ... (other member variables)

    private Handler handler = new Handler();
    private Runnable refreshRunnable = new Runnable() {
        @Override
        public void run() {
            trashCanModels.clear();
            getData();
            handler.postDelayed(this, 1000); // Refresh every 1 second
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // ... (onCreate implementation)

        handler.postDelayed(refreshRunnable, 1000); // Start refreshing
    }

    // ... (other methods)
}

This code will refresh the data every 1 second by calling the getData() method and updating the RecyclerView. The refresh cycle will continue until you stop it manually.

英文:

I'am trying to make refresh every 1 sec in my RecyclerView but i don't know how can i do it iam using my API , when something changed in my api i want to make that change in my RecylerView whitout the swiper or i want to make the swiper swipe every 1 sec .. so this is my Code :

public class InformationNow extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {
private RequestQueue requestQueue;
private SwipeRefreshLayout refresh;
private ArrayList&lt;TrashCanModel&gt; trashCanModels = new ArrayList&lt;&gt;();
private JsonArrayRequest arrayRequest;
private Dialog dialog;
private RecyclerView recyclerView;
private  InformationNowAdapter informationNowAdapter ;
private String url = &quot;http://192.168.1.34:9090/TrashCanData/lastrow&quot;;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_information_now);
refresh = (SwipeRefreshLayout) findViewById(R.id.Swiper);
recyclerView = (RecyclerView) findViewById(R.id.Now);
dialog = new Dialog(this);
refresh.setOnRefreshListener(this);
refresh.post(new Runnable() {
@Override
public void run() {
trashCanModels.clear();
getData();
}
});
}
private void getData() {
refresh.setRefreshing(true);
arrayRequest = new JsonArrayRequest(url, new Response.Listener&lt;JSONArray&gt;() {
@Override
public void onResponse(JSONArray response) {
JSONObject jsonObject = null;
for (int i = 0; i &lt; response.length(); i++) {
try {
//JSONArray jsonArray = response.getJSONArray(&quot;users&quot;);
jsonObject = response.getJSONObject(i);
TrashCanModel cat = new TrashCanModel();
cat.setDistance(jsonObject.getInt(&quot;distance&quot;));
cat.setTemperature(jsonObject.getInt(&quot;temperature&quot;));
cat.setHumidity(jsonObject.getInt(&quot;humidity&quot;));
Log.e(&quot;*********&quot;, cat.getDistance().toString());
Log.e(&quot;*********&quot;, cat.getTemperature().toString());
Log.e(&quot;*********&quot;, cat.getHumidity().toString());
trashCanModels.add(cat);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapterPush(trashCanModels);
refresh.setRefreshing(false);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(InformationNow.this);
requestQueue.add(arrayRequest);
}
private void adapterPush(ArrayList&lt;TrashCanModel&gt; trashCanModels) {
informationNowAdapter = new InformationNowAdapter(this, trashCanModels);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(informationNowAdapter);
}
@Override
public void onRefresh() {
trashCanModels.clear();
getData();
}
}

and my adapter :

public class InformationNowAdapter extends RecyclerView.Adapter&lt;InformationNowAdapter.MyViewHolder&gt;{
private Context context ;
private ArrayList&lt;TrashCanModel&gt; trashCanModels;
private String url = &quot;&quot;;
//
public InformationNowAdapter (Context context , ArrayList&lt;TrashCanModel&gt; trashCanModels) {
this.context = context;
this.trashCanModels=trashCanModels;
}
@NonNull
@Override
public InformationNowAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view ;
LayoutInflater layoutInflater = LayoutInflater.from(context);
view = layoutInflater.inflate(R.layout.trashcan_list , parent , false);
return new InformationNowAdapter.MyViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull InformationNowAdapter.MyViewHolder holder, int position) {
//holder.id.setText(&quot;#&quot;+String.valueOf(position+1));
holder.distance.setText(trashCanModels.get(position).getDistance().toString());
holder.temperature.setText(trashCanModels.get(position).getTemperature().toString());
holder.humidity.setText(trashCanModels.get(position).getHumidity().toString());
}
@Override
public int getItemCount() {
return trashCanModels.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private TextView  distance , temperature , humidity ;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
distance = (TextView) itemView.findViewById(R.id.distance);
temperature = (TextView) itemView.findViewById(R.id.temperature);
humidity = (TextView) itemView.findViewById(R.id.humidity);
//
}
}
}

so how can i make refresh data every 1 sec !

答案1

得分: 1

可以使用 Timer 来实现这个功能。

Timer repeatTask = new Timer();
repeatTask.scheduleAtFixedRate(new TimerTask() {
    @Override
    public void run() {
        trashCanModels.clear();
        getData();
    }
}, 0, 1000);

当你想要停止时,调用 repeatTask.cancel()

但我认为在 API 发生变化时,你应该使用推送通知,或者使用 Firebase 或 Socket.io 来替代。

英文:

You can use Timer to do that

Timer repeatTask = new Timer();
repeatTask.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
trashCanModels.clear();
getData();
}
}, 0, 1000);

call repeatTask.cancel() when you want to stop
But I think you should use push notification when your api change or use firebase or socket.io instead

huangapple
  • 本文由 发表于 2020年9月5日 09:51:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/63749773.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定