android Handler okhttp
原创
©著作权归作者所有:来自51CTO博客作者mb613739c94fb76的原创作品,请联系作者获取转载授权,否则将追究法律责任
package com.example.mepositry.fragment;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import com.example.mepositry.R;
import com.example.mepositry.bean.AdBean;
import com.google.gson.Gson;
import java.io.IOException;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class EntertainmentFragment extends Fragment {
private String mUrl2 = "http://test/api/po/hg";
private OkHttpClient mOkHttpClient;
private Button btn;
final Handler handler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message msg) {
String stringJson = (String) msg.obj;
Gson gson = new Gson();
AdBean mAdBean = gson.fromJson(stringJson, AdBean.class);
List<AdBean.DataBean> list = mAdBean.getData();
System.out.println(list);
}
};
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_entertainment, container, false);
btn = view.findViewById(R.id.btn);
mOkHttpClient = new OkHttpClient();
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
updateWeatherDataCoordinates();
}
});
return view;
}
public void updateWeatherDataCoordinates() {
Request request = new Request.Builder()
.url(mUrl2)
.build();
mOkHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.e("TAG", "onFailure");
}
@Override
public void onResponse(Call call, final Response response) throws IOException {
final String stringJson = response.body().string();
Log.e("TAG", "GetActivity2_onResponse" + stringJson);
Message msg = new Message();
msg.obj = stringJson;
handler.sendMessage(msg);
}
});
}
}
<com.google.android.material.tabs.TabLayout
android:id="@+id/main_tablayout"
android:layout_width="match_parent"
android:layout_height="50dp"
android:textSize="15sp"
app:tabBackground="@color/blue"
app:tabIndicatorColor="@color/orange"
app:tabIndicatorHeight="2dp"
app:tabMode="auto"
app:tabSelectedTextColor="@color/red"
app:tabTextColor="@color/white" />