2015-10-15 120 views
0

我試圖把我從一個Web服務進入一個自定義適配器在我的表格顯示的數據,問題是,下載需要一些時間在一個異步調用來完成,所以當我嘗試設置數據的Array(這種情況下的電影)適配器爲空。更改自定義適配器內容

我的繼承人活動:

package com.movieposter; 

import android.os.Bundle; 
import android.support.v7.app.AppCompatActivity; 
import android.util.Log; 
import android.widget.GridView; 

import com.squareup.okhttp.Call; 
import com.squareup.okhttp.Callback; 
import com.squareup.okhttp.OkHttpClient; 
import com.squareup.okhttp.Request; 
import com.squareup.okhttp.Response; 

import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

import java.io.IOException; 

public class MainActivity extends AppCompatActivity { 

    private final String API = "***"; 
    private Movie[] movies; 
    private GridView grid; 
    private ImageAdapter adapter; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     grid = (GridView) findViewById(R.id.grid_view); 
     getMovies(); 
     ImageAdapter adapter = new ImageAdapter(this, movies); 
     grid.setAdapter(adapter); 


    } 

    public void getMovies(){ 
     OkHttpClient client = new OkHttpClient(); 
     Request request = new Request.Builder() 
       .url("http://api.themoviedb.org/3/discover/movie?sort_by=popularity.desc&api_key=**") 
       .build(); 
     Call call = client.newCall(request); 
     call.enqueue(new Callback() { 
      @Override 
      public void onFailure(Request request, IOException e) { 

      } 

      @Override 
      public void onResponse(Response response) throws IOException { 
       String json = response.body().string(); 
       if (response.isSuccessful()) { 
        try { 
         Log.i("teste", response.body().string()); 
         movies = parseMovie(json); 



        } catch (Exception e) { 
         e.printStackTrace(); 
        } 
       } 
      } 
     }); 
    } 

    private Movie[] parseMovie(String json) throws JSONException { 
     JSONObject jsonMovie = new JSONObject(json); 
     JSONArray data = jsonMovie.getJSONArray("results"); 
     Movie[] movies = new Movie[data.length()]; 

     for(int i = 0; i < data.length(); i++){ 
      JSONObject jsonObject = data.getJSONObject(i); 
      Movie movie = new Movie(); 
      movie.setOverview(jsonObject.getString("overview")); 
      movie.setRating(jsonObject.getDouble("vote_average")); 
      movie.setReleaseDate(jsonObject.getString("release_date")); 
      movie.setTitle(jsonObject.getString("title")); 
      movie.setThumbnail("http://image.tmdb.org/t/p/w185/" + jsonObject.getString("poster_path")); 
      movies[i] = movie; 
     } 
     return movies; 
    } 



} 

而且我的適配器

package com.movieposter; 

import android.content.Context; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.BaseAdapter; 
import android.widget.GridView; 
import android.widget.ImageView; 

import com.squareup.picasso.Picasso; 

public class ImageAdapter extends BaseAdapter { 
    private Context mContext; 
    Movie[] movies; 

    public ImageAdapter(Context c, Movie[] movies) { 
     mContext = c; 
     this.movies = movies; 
    } 

    public int getCount() { 
     return movies.length; 
    } 

    public Object getItem(int position) { 
     return movies[position]; 
    } 

    public long getItemId(int position) { 
     return 0; 
    } 

    // create a new ImageView for each item referenced by the Adapter 
    public View getView(int position, View convertView, ViewGroup parent) { 
     ImageView imageView; 
     if (convertView == null) { 
      // if it's not recycled, initialize some attributes 
      imageView = new ImageView(mContext); 
      imageView.setLayoutParams(new GridView.LayoutParams(85, 85)); 
      imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); 
      imageView.setPadding(8, 8, 8, 8); 
     } else { 
      imageView = (ImageView) convertView; 
     } 

     Picasso.with(mContext).load(movies[position].getThumbnail()).into(imageView); 
     return imageView; 
    } 

} 

我試圖設置onResponse方法裏面的適配器,但沒有工作,什麼從web服務加載數據的最佳方法如果你不知道數據何時完成,那麼進入你的apater?是否可以設置一個空的適配器,然後在數據準備好後更換內容?是這樣,怎麼樣?

回答

1

是否有可能設置一個空的適配器,然後替換內容,一旦數據準備好了?是這樣,怎麼樣?

你自己回答了你的問題。對的,這是可能的。首先,你應該考慮使用List<Movie>而不是數組Movie[],因爲你可能不知道你會得到的電影數量。

有兩種方法可供

  1. 您可以用空的List<Movies> movies初始化適配並只顯示列表和onResponse你追加到List<Movies> movies,你得到新的數據,然後將所有notifyDataSetChanged()在你的適配器上。

  2. 如果你只需要調用服務,一旦你可以先保持ListView隱藏在onResponse可以初始化adaptor的數據,將其連接到適配器和榜上無名可見。在此之前,您可以顯示加載微調器或其他東西。

對於一個快速測試只是嘗試這個onResponse內:

if (response.isSuccessful()) { 
    try { 
     Log.i("teste", response.body().string()); 
     movies = parseMovie(json); 
     adapter.notifyDataSetChanged(); //add this 

    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 
+0

它的工作,我必須包括runOnUi調用,因爲該適配器更新UI的內容,謝謝 –

1

你必須使用一個列表,而不是一個數組的存儲對象。因爲數據結構應該是動態的(你永遠不知道有多少電影在那裏)。

List<Movie> movies = new ArrayList<Movie>();// First keep this empty. 

然後,

if (response.isSuccessful()) { 
    try { 
     Log.i("teste", response.body().string()); 
     movies.clear();// Do not re assign 
     movies.addAll(parseMovie(json)); // just clear and add new movies 
     adapter.notifyDataSetChanged(); //add this 

    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
}