我正在寻找我的问题而无法找到问题的解决方案,因为我很难理解RxAndroid
。
如何从互联网上获取数据并在屏幕上显示?
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button btnLoad;
ListView listView;
public static final String BASE_URL = "http://api.icndb.com/";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnLoad = findViewById(R.id.btnSet);
btnLoad.setOnClickListener(this);
listView = findViewById(R.id.listView);
}
@Override
public void onClick(View v) {
useRxJava();
}
private void setAdapter(ArrayList<String> jokes) {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, jokes);
listView.setAdapter(adapter);
}
private ArrayList<String> sentRequest() {
ArrayList<String> jokes = new ArrayList<>();
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create());
Retrofit retrofit = builder.build();
JokeRetrofitInterface client = retrofit.create(JokeRetrofitInterface.class);
Call<RootObject> call = client.getJokes();
RootObject rootObject = null;
try {
rootObject = call.execute().body();
} catch (IOException e) {
e.printStackTrace();
}
Value[] values = rootObject.getValue();
for (Value value : values) {
String joke = value.getJoke();
jokes.add(joke);
}
return jokes;
}
private void useRxJava() {
Observable observable = Observable.create(new ObservableOnSubscribe<ArrayList<String>>() {
@Override
public void subscribe(ObservableEmitter<ArrayList<String>> emitter) throws Exception {
ArrayList<String> myJokes = new ArrayList<>();
myJokes = sentRequest();
emitter.onNext(myJokes);
}
});
observable.subscribe(new Consumer<ArrayList<String>>() {
@Override
public void accept(ArrayList<String> jokes) throws Exception {
setAdapter(jokes);
}
});
}
}
答案 0 :(得分:0)
更新您的方法。 useRxJava()
private void useRxJava() {
Observable observable = Observable.fromCallable(new
Callable<ArrayList<String>>() {
@Override
public ArrayList<String> call() throws Exception {
return sentRequest()
}
});
observable.subscribeOn(Schedulers.io) // This makes sure that network operation happens in io thread
.observeOn(AndroidSchedulers.mainThread()) // This makes sure that you get response back in main thread
.subscribe(new Consumer<ArrayList<String>>() {
@Override
public void accept(ArrayList<String> jokes) throws Exception {
setAdapter(jokes);
}
});
}
其他一些建议和意见: