我剛剛開始編寫我的第一個Android應用程序,並面臨一個問題。我不知道如何正確處理HTTP響應。我已經找到了創建GET請求(使用okhttp)的方法,並找到了處理Callable響應的方法。我得到了我的對象數組,然後需要爲RecycleView(使用此數組)創建新的適配器,但我無法從主線程設置適配器。我不知道如何從Callable獲取數據。Android處理HTTP響應
製作要求
public static void getDonerPoints() {
try {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://192.168.2.64:9000/donerPoint/get?count=100&orderBy=rating&orderDirection=asc")
.build();
client.newCall(request).enqueue(
new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.d("mLog", "request error");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
try {
final ArrayList<DonerPoint> points = new ArrayList<>();
if (response.code() == HttpURLConnection.HTTP_OK) {
JSONArray jsonArray = new JSONArray(response.body().string());
ObjectMapper mapper = new ObjectMapper();
for (int i = 0; i < jsonArray.length(); i++)
points.add(mapper.readValue(jsonArray.getString(i), DonerPoint.class));
ListFragment.setNewContentForAdapter(points);
Log.d("mLog", "ok");
}
} catch (Exception exc) {
Log.d("mLog", exc.toString());
}
}
});
} catch (Exception exc) {
}
}
設置適配器
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.list_tab, container, false);
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.rv);
mLayoutManager = new LinearLayoutManager(getContext());
mRecyclerView.setLayoutManager(mLayoutManager);
return rootView;
}
public static void setNewContentForAdapter(List<DonerPoint> points){
mAdapter=new PointAdapter(points);
mRecyclerView.setAdapter(mAdapter);
}
而且Excexption
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
也許我需要做的是不能在靜態情況下?
請張貼一些代碼來說明你有什麼至今。 –