2016-07-20 5 views
1

イメージがロードされていないときにvolleyを使用してjsonデータを解析してリストビューで背景イメージを表示する方法image url jsonに存在しない場合は、デフォルトで背景イメージが表示されます。イメージがロードされていないときにvolleyを使用してjsonデータを解析してリストビューに背景イメージを表示する方法

リストに表示されている画像ist画像urlはjsonに存在しませんので、ist画像は空白の画像として表示されます。 enter image description here

デフォルトの画像として表示する必要がありますが、

空白の画像を1つの画像に置き換える必要があります。画像が読み込まれていない間に1つの背景画像を配置したい場合は、すべての画像のデフォルトとして表示されるはずです。画像がダウンロードされると、画像はデフォルトの画像に置き換えてください。
私はVolley Libraryを使用しました。 画像がロードされていないときに背景画像を設定するにはどうすればいいですか?画像URLが存在しない場合は、デフォルトで背景画像になるはずですか?

主な活動

public class MainActivity extends Activity { 
    // Log tag 
    private static final String TAG = MainActivity.class.getSimpleName(); 
    private static final String url = "http://lztsyhmtyk.localtunnel.me/api/v1/restaurants?per_page=10&page=1&sort_col=average_ratings"; 
    // Movies json url 
    //private static final String url = "http://api.androidhive.info/json/movies.json"; 
    private ProgressDialog pDialog; 
    private List<Movie> movieList = new ArrayList<Movie>(); 
    private ListView listView; 
    private CustomListAdapter adapter; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     listView = (ListView) findViewById(R.id.list); 
     adapter = new CustomListAdapter(this, movieList); 
     listView.setAdapter(adapter); 
     pDialog = new ProgressDialog(this); 
     // Showing progress dialog before making http request 
     pDialog.setMessage("Loading..."); 
     pDialog.show(); 
     // changing action bar color 
     getActionBar().setBackgroundDrawable(
       new ColorDrawable(Color.parseColor("#1b1b1b"))); 
     // Creating volley request obj 
     JsonArrayRequest movieReq = new JsonArrayRequest(url, 
       new Response.Listener<JSONArray>() { 
        @Override 
        public void onResponse(JSONArray response) { 
         Log.d(TAG, response.toString()); 
         hidePDialog(); 
         // Parsing json 
         for (int i = 0; i < response.length(); i++) { 
          try { 
           JSONObject obj = response.getJSONObject(i); 
           Movie movie = new Movie(); 
           //movie.setTitle(obj.getString("title")); 
           movie.setName(obj.getString("name")); 
           //movie.setThumbnailUrl(obj.getString("image")); 
           movie.setThumbnailUrl(obj.getString("image_url")); 
           movie.setAverage_ratings(obj.getString("average_ratings")); 
           movie.setCuisine(obj.getString("cuisine")); 
           movie.setAddress(obj.getJSONObject("address").getString("area")); 
           //movie.setAddress(obj.getString("address")); 
           //movie.setYear(obj.getInt("releaseYear")); 
           // Genre is json array 
           /*JSONArray genreArry = obj.getJSONArray("genre"); 
           ArrayList<String> genre = new ArrayList<String>(); 
           for (int j = 0; j < genreArry.length(); j++) { 
            genre.add((String) genreArry.get(j)); 
           } 
           movie.setGenre(genre);*/ 
           // adding movie to movies array 
           movieList.add(movie); 
          } catch (JSONException e) { 
           e.printStackTrace(); 
          } 
         } 

         // notifying list adapter about data changes 
         // so that it renders the list view with updated data 
         adapter.notifyDataSetChanged(); 
        } 
       }, new Response.ErrorListener() { 
        @Override 
        public void onErrorResponse(VolleyError error) { 
         VolleyLog.d(TAG, "Error: " + error.getMessage()); 
         hidePDialog(); 

        } 
       }); 

     // Adding request to request queue 
     AppController.getInstance().addToRequestQueue(movieReq); 
    } 

    @Override 
    public void onDestroy() { 
     super.onDestroy(); 
     hidePDialog(); 
    } 

    private void hidePDialog() { 
     if (pDialog != null) { 
      pDialog.dismiss(); 
      pDialog = null; 
     } 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.main, menu); 
     return true; 
    } 

} 

listrow.xml

<?xml version="1.0" encoding="utf-8"?> 
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:background="@drawable/list_row_selector" 
     android:padding="8dp" > 

     <!-- Thumbnail Image --> 
     <com.android.volley.toolbox.NetworkImageView 
      android:id="@+id/thumbnail" 
      android:layout_width="120dp" 
      android:layout_height="80dp" 
      android:layout_alignParentLeft="true" 
      android:layout_marginRight="8dp" /> 
     <ImageView 
      android:id="@+id/img" 
      android:layout_width="120dp" 
      android:layout_height="80dp" 
      android:layout_alignParentLeft="true" 
      android:layout_marginRight="8dp" 
      android:src="@drawable/bc" 
      /> 
     <!-- Restaurant name --> 
     <TextView 
      android:id="@+id/name" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 

      android:layout_toRightOf="@+id/thumbnail" 
      android:textSize="@dimen/title" 
      android:textStyle="bold" /> 

     <TextView 
      android:id="@+id/area" 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" 
      android:layout_below="@id/name" 

      android:layout_toRightOf="@+id/thumbnail" 
      android:textSize="@dimen/rating" /> 

     <!-- Rating --> 
     <TextView 
      android:id="@+id/average_ratings" 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" 
      android:layout_below="@id/area" 
      android:layout_toRightOf="@+id/thumbnail" 

      android:textSize="@dimen/rating" /> 

     <TextView 
      android:id="@+id/cuisine" 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" 
      android:layout_below="@id/average_ratings" 

      android:layout_toRightOf="@+id/thumbnail" 
      android:textSize="@dimen/rating" /> 

     <!-- Genre --> 
     <!-- <TextView 
      android:id="@+id/genre" 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" 
      android:layout_below="@id/rating" 
      android:layout_marginTop="5dp" 
      android:layout_toRightOf="@+id/thumbnail" 
      android:textColor="@color/genre" 
      android:textSize="@dimen/genre" />--> 
    <!-- 
     &lt;!&ndash; Release Year &ndash;&gt; 
     <TextView 
      android:id="@+id/releaseYear" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_alignParentBottom="true" 
      android:layout_alignParentRight="true" 
      android:textColor="@color/year" 
      android:textSize="@dimen/year" />--> 

    </RelativeLayout> 

Movie.java

public class Movie { 
    private String name, thumbnailUrl; 
    //private int year; 
    private String average_ratings,area,cuisine,address; 
// private ArrayList<String> genre; 

    public Movie() { 
    } 

    public Movie(String name, String thumbnailUrl, String average_ratings,String area,String cuisine,String address 
      ) { 
     this.name = name; 
     this.thumbnailUrl = thumbnailUrl; 
     //this.year = year; 
     this.average_ratings = average_ratings; 
     this.area=area; 
     this.cuisine=cuisine; 
this.address=address; 
     //this.genre = genre; 
    } 

    public String getName() { 
     return name; 
    } 

    public void setName(String name) { 
     this.name = name; 
    } 

    public String getThumbnailUrl() { 
     return thumbnailUrl; 
    } 

    public void setThumbnailUrl(String thumbnailUrl) { 
     this.thumbnailUrl = thumbnailUrl; 
    } 

    /*public int getYear() { 
     return year; 
    }*/ 

    /*public void setYear(int year) { 
     this.year = year; 
    }*/ 

    public String getAverage_ratings() { 
     return average_ratings; 
    } 

    public void setAverage_ratings(String average_ratings) { 
     this.average_ratings = average_ratings; 
    } 
    public String getAddress() { 
     return address; 
    } 

    public void setAddress(String address) { 
     this.address = address; 
    } 

    public String getCuisine() { 
     return cuisine; 
    } 

    public void setCuisine(String cuisine) { 
     this.cuisine = cuisine; 
    } 
    /*public ArrayList<String> getGenre() { 
     return genre; 
    } 

    public void setGenre(ArrayList<String> genre) { 
     this.genre = genre; 
    } 
*/ 
} 

customlistadapter.java

public class CustomListAdapter extends BaseAdapter { 
     private Activity activity; 
     private LayoutInflater inflater; 
     private List<Movie> movieItems; 
     ImageLoader imageLoader = AppController.getInstance().getImageLoader(); 

     public CustomListAdapter(Activity activity, List<Movie> movieItems) { 
      this.activity = activity; 
      this.movieItems = movieItems; 
     } 

     @Override 
     public int getCount() { 
      return movieItems.size(); 
     } 

     @Override 
     public Object getItem(int location) { 
      return movieItems.get(location); 
     } 

     @Override 
     public long getItemId(int position) { 
      return position; 
     } 

     @Override 
     public View getView(int position, View convertView, ViewGroup parent) { 

      if (inflater == null) 
       inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
      if (convertView == null) 
       convertView = inflater.inflate(R.layout.list_row, null); 

      if (imageLoader == null) 
       imageLoader = AppController.getInstance().getImageLoader(); 
      /*ImageView img; 
      img = (ImageView)convertView 
        .findViewById(R.id.img); 

      img.setImageResource(R.drawable.bc); 
      else {*/ 
      NetworkImageView thumbNail = (NetworkImageView) convertView 
        .findViewById(R.id.thumbnail); 
      TextView name = (TextView) convertView.findViewById(R.id.name); 
      TextView average_ratings = (TextView) convertView.findViewById(R.id.average_ratings); 
      TextView address=(TextView) convertView.findViewById(R.id.area); 
      TextView cuisine =(TextView) convertView.findViewById(R.id.cuisine); 
      //TextView genre = (TextView) convertView.findViewById(R.id.genre); 
      //TextView year = (TextView) convertView.findViewById(R.id.releaseYear); 

      // getting movie data for the row 
      Movie m = movieItems.get(position); 

      // thumbnail image 
      //thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader); 
      //if (TextUtils.isEmpty(m.getThumbnailUrl())) 
       //thumbNail.setImageResource(R.drawable.bc); 



      //else 
       //Log.d("KeyHash:","Neeraj"); 
       thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader); 
      /*if (m.getThumbnailUrl().compareTo("")!=0) 
       thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader); 
      //else{ 
      //thumbNail.setImageResource(R.drawable.bc); 

       else { 

        thumbNail.setDefaultImageResId(R.drawable.bc); 
        //thumbNail.setErrorImageResId(R.drawable.bc); 

      }*/ 


      // title 
      name.setText(m.getName()); 

      // rating 
      average_ratings.setText("Rating: " + String.valueOf(m.getAverage_ratings())); 
      address.setText("Area: " + String.valueOf(m.getAddress())); 
      cuisine.setText("Cusine: " + String.valueOf(m.getCuisine())); 
      /*// genre 
      String genreStr = ""; 
      for (String str : m.getGenre()) { 
       genreStr += str + ", "; 
      } 
      genreStr = genreStr.length() > 0 ? genreStr.substring(0, 
        genreStr.length() - 2) : genreStr; 
      genre.setText(genreStr); 

      // release year 
      year.setText(String.valueOf(m.getYear()));*/ 

      return convertView; 
     } 



    } 

のApp controller.java

public class AppController extends Application { 

    public static final String TAG = AppController.class.getSimpleName(); 

    private RequestQueue mRequestQueue; 
    private ImageLoader mImageLoader; 

    private static AppController mInstance; 

    @Override 
    public void onCreate() { 
     super.onCreate(); 
     mInstance = this; 
    } 

    public static synchronized AppController getInstance() { 
     return mInstance; 
    } 

    public RequestQueue getRequestQueue() { 
     if (mRequestQueue == null) { 
      mRequestQueue = Volley.newRequestQueue(getApplicationContext()); 
     } 

     return mRequestQueue; 
    } 

    public ImageLoader getImageLoader() { 
     getRequestQueue(); 
     if (mImageLoader == null) { 
      mImageLoader = new ImageLoader(this.mRequestQueue, 
        new LruBitmapCache()); 
     } 
     return this.mImageLoader; 
    } 

    public <T> void addToRequestQueue(Request<T> req, String tag) { 
     // set the default tag if tag is empty 
     req.setTag(TextUtils.isEmpty(tag) ? TAG : tag); 
     getRequestQueue().add(req); 
    } 

    public <T> void addToRequestQueue(Request<T> req) { 
     req.setTag(TAG); 
     getRequestQueue().add(req); 
    } 

    public void cancelPendingRequests(Object tag) { 
     if (mRequestQueue != null) { 
      mRequestQueue.cancelAll(tag); 
     } 
    } 

After change it is appearing as

答えて

1

アダプタにこのコードを入れ

// get reference of your imageloader 
    imageLoader = AppController.getInstance().getImageLoader(); 

    NetworkImageView thumbNail = (NetworkImageView) convertView 
        .findViewById(R.id.thumbnail); 
     thumbNail .setDefaultImageResId(R.drawable.yourdrawable); 

     // getting movie data for the row 
      Movie m = movieItems.get(position); 

// now it time to load image 
thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader); 
+0

お返事ありがとうございます。今どこにイメージURLがありますか。それは背景のイメージで来ています。両方が合併している。両方が現れている。最初の背景画像が表示され、画像URLも来ています。それは背景イメージを置き換える必要があります。しかし、それはなぜ起こっていないのですか? 2番目の画像を参照してください。私は何を付けていますか?それは両方のイメージが現れるように来ています。これを行うことで – user6313669

+0

となります。両方の画像が来ています。それは同じ解決策です。 2番目の画像を参照してください。両方の画像が表示されます。 – user6313669

+1

あなたのimageviewを削除して、このメソッドを使用してイメージを読み込んで、デフォルトの背景を渡されたURL(IMAGE_URL)からロードされたイメージに置き換えます。mNetworkImageView.setImageUrl(IMAGE_URL、mImageLoader); –

1

あなたImageViewのを削除し、あなたのNetworkImageViewにandroid:src="@drawable/bc"を設定します。あなたの別のImageViewの削除後

<?xml version="1.0" encoding="utf-8"?> 
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:background="@drawable/list_row_selector" 
     android:padding="8dp" > 

     <!-- Thumbnail Image --> 
     <com.android.volley.toolbox.NetworkImageView 
      android:id="@+id/thumbnail" 
      android:layout_width="120dp" 
      android:layout_height="80dp" 
      android:layout_alignParentLeft="true" 
      android:layout_marginRight="8dp" 
      android:src="@drawable/bc" /> 
     <!-- Restaurant name --> 
     <TextView 
      android:id="@+id/name" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 

      android:layout_toRightOf="@+id/thumbnail" 
      android:textSize="@dimen/title" 
      android:textStyle="bold" /> 

     <TextView 
      android:id="@+id/area" 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" 
      android:layout_below="@id/name" 

      android:layout_toRightOf="@+id/thumbnail" 
      android:textSize="@dimen/rating" /> 

     <!-- Rating --> 
     <TextView 
      android:id="@+id/average_ratings" 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" 
      android:layout_below="@id/area" 
      android:layout_toRightOf="@+id/thumbnail" 

      android:textSize="@dimen/rating" /> 

     <TextView 
      android:id="@+id/cuisine" 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" 
      android:layout_below="@id/average_ratings" 

      android:layout_toRightOf="@+id/thumbnail" 
      android:textSize="@dimen/rating" /> 

     <!-- Genre --> 
     <!-- <TextView 
      android:id="@+id/genre" 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" 
      android:layout_below="@id/rating" 
      android:layout_marginTop="5dp" 
      android:layout_toRightOf="@+id/thumbnail" 
      android:textColor="@color/genre" 
      android:textSize="@dimen/genre" />--> 
    <!-- 
     &lt;!&ndash; Release Year &ndash;&gt; 
     <TextView 
      android:id="@+id/releaseYear" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_alignParentBottom="true" 
      android:layout_alignParentRight="true" 
      android:textColor="@color/year" 
      android:textSize="@dimen/year" />--> 

    </RelativeLayout> 
+0

画像は表示されますが、背景画像は画像URLで表示されています。画像URLが存在すると、両方の画像が表示されます。 whrn image urlが存在しない場合、背景イメージが表示されます。しかし、1つの問題は、画像URL画像に問題があると背景画像が出現していることです。 2番目の画像を参照してください。 – user6313669

+0

答えを編集します。それを今チェックしてください:) –

+0

私は同じことをしましたが、スクロールダウンしているときに、背景画像が表示されない場合は、画像URLが表示されません。画像urlが存在しない現在の背景画像が存在するはずです。最初に現れていますが、消えていくリストでは上下しています。どうして ? – user6313669

0

CustomListAdapterの変更点& list_row.xmlが必要です。

更新:変更の問題が解決された後

CustomListAdapter

public class CustomListAdapter extends BaseAdapter { 
    private Activity activity; 
    private LayoutInflater inflater; 
    private List<Movie> movieItems; 
    ImageLoader imageLoader = AppController.getInstance().getImageLoader(); 

    public CustomListAdapter(Activity activity, List<Movie> movieItems) { 
     this.activity = activity; 
     this.movieItems = movieItems; 
    } 

    @Override 
    public int getCount() { 
     return movieItems.size(); 
    } 

    @Override 
    public Object getItem(int location) { 
     return movieItems.get(location); 
    } 

    @Override 
    public long getItemId(int position) { 
     return position; 
    } 

    @Override 
    public View getView(int position, View convertView, ViewGroup parent) { 

     if (inflater == null) 
      inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     if (convertView == null) 
      convertView = inflater.inflate(R.layout.list_row, null); 

     if (imageLoader == null) 
      imageLoader = AppController.getInstance().getImageLoader(); 
     /*ImageView img; 
     img = (ImageView)convertView 
       .findViewById(R.id.img); 

     img.setImageResource(R.drawable.bc); 
     else {*/ 

     NetworkImageView _ImageView = (NetworkImageView) convertView.findViewById(R.id.thumbnail); 
     _ImageView.setDefaultImageResId(R.drawable.bc); 
     //NetworkImageView.setImageUrl(m.getThumbnailUrl(), ImageLoader); 
     /*NetworkImageView thumbNail = (NetworkImageView) convertView 
       .findViewById(R.id.thumbnail);*/ 
     TextView name = (TextView) convertView.findViewById(R.id.name); 
     TextView average_ratings = (TextView) convertView.findViewById(R.id.average_ratings); 
     TextView address=(TextView) convertView.findViewById(R.id.area); 
     TextView cuisine =(TextView) convertView.findViewById(R.id.cuisine); 
     //TextView genre = (TextView) convertView.findViewById(R.id.genre); 
     //TextView year = (TextView) convertView.findViewById(R.id.releaseYear); 

     // getting movie data for the row 
     Movie m = movieItems.get(position); 

     // thumbnail image 
     //_ImageView.setImageUrl(m.getThumbnailUrl(), imageLoader); 
     /*if (TextUtils.isEmpty(m.getThumbnailUrl())) 
      thumbNail.setImageResource(R.drawable.bc); 



     else 
      //Log.d("KeyHash:","Neeraj");*/ 
     _ImageView.setImageUrl(m.getThumbnailUrl(), imageLoader); 
     /*if (m.getThumbnailUrl().compareTo("")!=0) 
      thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader); 
     //else{ 
     //thumbNail.setImageResource(R.drawable.bc); 

      else { 

       thumbNail.setDefaultImageResId(R.drawable.bc); 
       //thumbNail.setErrorImageResId(R.drawable.bc); 

     }*/ 


     // title 
     name.setText(m.getName()); 

     // rating 
     average_ratings.setText("Rating: " + String.valueOf(m.getAverage_ratings())); 
     address.setText("Area: " + String.valueOf(m.getAddress())); 
     cuisine.setText("Cusine: " + String.valueOf(m.getCuisine())); 
     /*// genre 
     String genreStr = ""; 
     for (String str : m.getGenre()) { 
      genreStr += str + ", "; 
     } 
     genreStr = genreStr.length() > 0 ? genreStr.substring(0, 
       genreStr.length() - 2) : genreStr; 
     genre.setText(genreStr); 

     // release year 
     year.setText(String.valueOf(m.getYear()));*/ 

     return convertView; 
    } 



} 

list_row.xml

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:background="@drawable/list_row_selector" 
    android:padding="8dp" > 

    <!-- Thumbnail Image --> 
    <com.android.volley.toolbox.NetworkImageView 
     android:id="@+id/thumbnail" 
     android:layout_width="120dp" 
     android:layout_height="80dp" 
     android:layout_alignParentLeft="true" 
     android:layout_marginRight="8dp" 

     /> 

    <!-- Restaurant name --> 
    <TextView 
     android:id="@+id/name" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 

     android:layout_toRightOf="@+id/thumbnail" 
     android:textSize="@dimen/title" 
     android:textStyle="bold" /> 

    <TextView 
     android:id="@+id/area" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:layout_below="@id/name" 

     android:layout_toRightOf="@+id/thumbnail" 
     android:textSize="@dimen/rating" /> 

    <!-- Rating --> 
    <TextView 
     android:id="@+id/average_ratings" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:layout_below="@id/area" 
     android:layout_toRightOf="@+id/thumbnail" 

     android:textSize="@dimen/rating" /> 

    <TextView 
     android:id="@+id/cuisine" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:layout_below="@id/average_ratings" 

     android:layout_toRightOf="@+id/thumbnail" 
     android:textSize="@dimen/rating" /> 

    <!-- Genre --> 
    <!-- <TextView 
     android:id="@+id/genre" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:layout_below="@id/rating" 
     android:layout_marginTop="5dp" 
     android:layout_toRightOf="@+id/thumbnail" 
     android:textColor="@color/genre" 
     android:textSize="@dimen/genre" />--> 
<!-- 
    &lt;!&ndash; Release Year &ndash;&gt; 
    <TextView 
     android:id="@+id/releaseYear" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignParentBottom="true" 
     android:layout_alignParentRight="true" 
     android:textColor="@color/year" 
     android:textSize="@dimen/year" />--> 

</RelativeLayout> 

は、画像に表示されます。 enter image description here

関連する問題