-1
感謝您對誰回覆我在以前的帖子的朋友(Get Image from Urls with AsyncTask)獲取圖像
我終於找到了如何顯示在GridView中的形象,這裏是代碼
public class MainActivity extends AppCompatActivity {
private MyAdapter mMovieAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] imgUrllink = new String[]{
"http://image.tmdb.org/t/p/w342/sM33SANp9z6rXW8Itn7NnG1GOEs.jpg",
"http://image.tmdb.org/t/p/w342/5JU9ytZJyR3zmClGmVm9q4Geqbd.jpg",
"http://image.tmdb.org/t/p/w342/y31QB9kn3XSudA15tV7UWQ9XLuW.jpg",
"http://image.tmdb.org/t/p/w342/zSouWWrySXshPCT4t3UKCQGayyo.jpg",
"http://image.tmdb.org/t/p/w342/weUSwMdQIa3NaXVzwUoIIcAi85d.jpg",
"http://image.tmdb.org/t/p/w342/bIXbMvEKhlLnhdXttTf2ZKvLZEP.jpg",
"http://image.tmdb.org/t/p/w342/hGRfWcy1HRGbsjK6jF7NILmqmFT.jpg",
"http://image.tmdb.org/t/p/w342/cGOPbv9wA5gEejkUN892JrveARt.jpg",
"http://image.tmdb.org/t/p/w342/6FxOPJ9Ysilpq0IgkrMJ7PubFhq.jpg",
"http://image.tmdb.org/t/p/w342/kqjL17yufvn9OVLyXYpvtyrFfak.jpg"};
mMovieAdapter = new MyAdapter(this, imgUrllink);
GridView gridview = (GridView) findViewById(R.id.gridView);
gridview.setAdapter(mMovieAdapter);
ImageView img = (ImageView) findViewById(R.id.imageItem);
new DownloadImageTask(img);
}
}
public class MyAdapter extends ArrayAdapter<String>{
private final Activity context;
public MyAdapter(Activity context, String[] imgUrlList){
super(context,0, imgUrlList);
this.context = context;
}
public View getView (int position, View convertview, ViewGroup parent){
ImageView view = (ImageView) convertview;
if (view == null){
view = new ImageView(context);
}
String url = getItem(position);
Picasso.with(context).load(url).into(view);
return view;
}
}
public class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
String LOG_TAG = DownloadImageTask.class.getSimpleName();
ImageView poster;
public DownloadImageTask(ImageView img) {
this.poster = img;
}
protected Bitmap doInBackground(String... urls){
String imageUrls = urls[0];
Bitmap moviePoster = null;
try {
InputStream in = new java.net.URL(imageUrls).openStream();
moviePoster = BitmapFactory.decodeStream(in);
} catch (Exception r) {
Log.e("Error", r.getMessage());
r.printStackTrace();
}
return moviePoster;
}
@Override
protected void onPostExecute(Bitmap result) {
poster.setImageBitmap(result);
}
}
這裏是GridView控件設置
android:id="@+id/gridView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="8dp"
android:verticalSpacing="8dp"
android:numColumns="auto_fit"
android:scrollbarStyle="insideOverlay"
android:scrollbars="none"
android:listSelector="@null"
android:stretchMode="columnWidth"
android:background="#000000">
我現在打算將代碼從預先設定的鏈路改變爲從Json的獲取鏈接。但是,這不是工作。你能否建議我如何改變?
public class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
String LOG_TAG = DownloadImageTask.class.getSimpleName();
ImageView poster;
String[] posterPath;
public DownloadImageTask(ImageView img, String[] imgUrllink) {
this.poster = img;
this.posterPath = imgUrllink;
}
private String[] getPosterPathFromJson (String forecastJsonStr) throws JSONException{
final String MOVIE_LIST = "results";
final String MOVIE_POSTER = "poster_path";
JSONObject forecastJson = new JSONObject(forecastJsonStr);
JSONArray posterArray = forecastJson.getJSONArray(MOVIE_LIST);
String[] resultStrs = new String[16];
for(int i = 0; i < posterArray.length(); i++) {
JSONObject movieShow = posterArray.getJSONObject(i);
String posterPath = movieShow.getString(MOVIE_POSTER);
resultStrs[i] = posterPath;
}
for (String s : resultStrs) {
Log.v(LOG_TAG, "Forecast entry: " + s);
}
return resultStrs;
}
protected Bitmap doInBackground(String... urls){
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String forecastJsonStr = null;
String sort_by = "popularity.desc";
String api_key = "aa614f2b0675d4c84319292b3c7f794b";
try {
final String JSON_LINK = "https://api.themoviedb.org/3/discover/movie?";
final String SORT_BY = "sort_by";
final String API_KEY = "api_key";
Uri buildUri = Uri.parse(JSON_LINK).buildUpon()
.appendQueryParameter(SORT_BY, sort_by)
.appendQueryParameter(API_KEY, api_key)
.build();
URL url = new URL(buildUri.toString());
// Create the request to OpenWeatherMap, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuilder buffer = new StringBuilder();
if (inputStream == null){
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
forecastJsonStr = buffer.toString();
Log.v(LOG_TAG, "Forecast string: " + forecastJsonStr);
}catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attempting
// to parse it.
forecastJsonStr = null;
}finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
try {
return getPosterPathFromJson (forecastJsonStr);
}catch (JSONException t){
Log.e(LOG_TAG, t.getMessage(), t);
t.printStackTrace();
}
String imageUrls = urls[0];
Bitmap moviePoster = null;
try {
InputStream in = new java.net.URL(imageUrls).openStream();
moviePoster = BitmapFactory.decodeStream(in);
} catch (Exception r) {
Log.e("Error", r.getMessage());
r.printStackTrace();
}
return moviePoster;
}
@Override
protected void onPostExecute(Bitmap result) {
poster.setImageBitmap(result);
}
}
安置自己的JSON格式太 – Jas
這裏的JSON鏈接https://api.themoviedb.org/3/discover/movie?sort_by=popularity.desc&api_key=aa614f2b0675d4c84319292b3c7f794b –