2016-07-15 5 views
-1

Vielen Dank für die Freunde, die mich auf frühere Post antworten (Get Image from Urls with AsyncTask)Get Bild von TMDB statt voreingestellten Daten

ich, wie endlich gefunden auf Gridview das Bild zu zeigen, hier ist der Code

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); 
    } 
} 

Hier ist die Einstellung Grid

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"> 

ich jetzt planen Sie den Code aus voreingestellten Link zu ändern Link von Json zu bekommen. Es ist jedoch keine Arbeit. Könnten Sie mir bitte vorschlagen, wie ich mich ändern kann?

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

Post json-Format auch hier – Jas

+0

die Verbindung von Json ist https://api.themoviedb.org/3/discover/movie?sort_by=popularity.desc&api_key=aa614f2b0675d4c84319292b3c7f794b –

Antwort

0

Verwenden Sie diesen Code für das JSON-String vom Server abrufen

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){} 
} 

Erstellen Sie Ihr JSON-Objekt wie:

JSONObject jObject = new JSONObject(result); 

Ihre URL-Zeichenfolge abrufen von jObject wie:

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

Siehe this answer für weitere Details

+0

Sorry, es nicht arbeite für mich –