获取图像

获取图像

问题描述:

感谢您对谁回复我在以前的帖子的朋友(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); 
    } 
} 
+0

安置自己的JSON格式太 – Jas

+0

这里的JSON链接https://api.themoviedb.org/3/discover/movie?sort_by=popularity.desc&api_key=aa614f2b0675d4c84319292b3c7f794b –

使用此代码从服务器

DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams()); 
HttpPost httppost = new HttpPost(your URL); 
// Depends on your web service 
httppost.setHeader("Content-type", "application/json"); 

InputStream inputStream = null; 
String result = null; 
try { 
    HttpResponse response = httpclient.execute(httppost);   
    HttpEntity entity = response.getEntity(); 

    inputStream = entity.getContent(); 
    // json is UTF-8 by default 
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8); 
    StringBuilder sb = new StringBuilder(); 

    String line = null; 
    while ((line = reader.readLine()) != null) 
    { 
     sb.append(line + "\n"); 
    } 
    result = sb.toString(); 
} catch (Exception e) { 
    // Oops 
} 
finally { 
    try{if(inputStream != null)inputStream.close();}catch(Exception squish){} 
} 

检索您的JSON字符串创建JSON对象,如:

JSONObject jObject = new JSONObject(result); 

从jObject像检索您的URL字符串

String aJsonString = jObject.getString("STRINGNAME"); 

参考this answer更多细节

+0

对不起,它不为我工作 –