Blindsurfer Blindsurfer - 6 months ago 30
Android Question

Android RecyclerView not updating TextView

I want to change asynchronous data in a recycler View.

When method

SetText()
is called, nothing happens until I scroll.

class MainAdapter extends RecyclerView.Adapter<MainAdapter.MyViewHolder> {
private Context context;
private SortedList<City> items;

public MainAdapter(Context context) {
this.context = context;
}

public void add(City item){
items.add(item);
}

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View row = LayoutInflater.from(context).inflate(R.layout.row, parent, false);
return new MyViewHolder(row);
}

@Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
holder.tvTitle.setText(String.format("%d %s", items.get(position).getId(), items.get(position).getName()));

Observable<String> observable = Observable.create(new Observable.OnSubscribe<String>() {
@Override
public void call(Subscriber<? super String> subscriber) {
try {
//Do somethin in Background
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
subscriber.onNext(items.get(position).name);
subscriber.onCompleted();
}
}).subscribeOn(Schedulers.computation());

observable.subscribe(new Subscriber<String>() {
@Override
public void onCompleted() {
}

@Override
public void onError(Throwable e) {
}

@Override
public void onNext(String text) {
holder.tvRowText.setText(text);
}
});
}

@Override
public int getItemCount() {
return items.size();
}

@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}

static class MyViewHolder extends RecyclerView.ViewHolder {

@BindView(R.id.row_title)
public TextView tvTitle;

@BindView(R.id.row_text)
public TextView tvRowText;

MyViewHolder(View row) {
super(row);
ButterKnife.bind(this, row);
}
}
}


What am I doing wrong?

Calling
notifyDatachanged(i)
in
onNext()
is not working.

Answer

try using below code:

holder.tvRowText.setText(text);

inside a post call (which will run it on UI thread) like this:

holder.tvRowText.post(new runnable... emitted for brevity){
holder.tvRowText.setText(text);
}