我使用Retrofit处理GitHub api的数据。在一个活动中,我需要2个引用Retrofit Builder,因此 - 2个回调。到目前为止,calss的定义是:
public class UserScreen extends Activity implements Callback<GitHubUser>, Callback<GitHubRepos>
如何避免重复的课程?我对User调用方法的定义如下:
public void loadData(View view) {
Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
.create();
retrofit = new Retrofit.Builder()
.baseUrl(GitHubUserAPI.ENDPOINT)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
// prepare call in Retrofit 2.0
GitHubUserAPI githubUserAPI = retrofit.create(GitHubUserAPI.class);
Call<GitHubUser> callUser = githubUserAPI.getUser(newString);
callUser.enqueue(this);
Call<GitHubUser> callAvatar = githubUserAPI.getAvatar(newString);
callAvatar.enqueue(this);
Call<GitHubUser> callFollowers = githubUserAPI.getFollowers(newString);
callFollowers.enqueue(this);
}
@Override
public void onResponse(Call<GitHubUser> call, final Response<GitHubUser> response) {
final int code = response.code();
if (code == 200) {
final GitHubUser user = response.body();
userNameTV.setText(user.getName());
followersTV.setText("Followers: " + user.getFollowers());
followingTV.setText("Following: " + user.getFollowing());
ImageDownloader task = new ImageDownloader();
Bitmap myImage;
try {
myImage = task.execute(user.getAvatar()).get();
avatarImg.setImageBitmap(myImage);
avatarImg.getLayoutParams().height=150;
avatarImg.getLayoutParams().width=150;
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class ImageDownloader extends AsyncTask<String, Void, Bitmap> {
@Override
protected Bitmap doInBackground(String... urls) {
try {
URL url = new URL(urls[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream inputStream = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(inputStream);
return myBitmap;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
@Override
public void onFailure(Call<GitHubUser> call, Throwable t) {
Toast.makeText(this, "Nope", Toast.LENGTH_LONG).show();
}
谢谢!