从TMDB获取图像而不是预设数据

时间:2016-07-15 06:18:12

标签: java android json gridview android-asynctask

感谢您在之前的帖子(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);
  }
}

1 个答案:

答案 0 :(得分:0)

使用此代码从服务器

检索json字符串
    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对象,如:

JSONObject jObject = new JSONObject(result);

从jObject中检索你的url字符串,如:

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

有关详细信息,请参阅this answer