2012-12-04 79 views
0

我是新的Android應用程序,我想添加圖像和文本在列表視圖和響應從服務器是JSON響應。現在我在listview中添加了文本,因此我需要爲每個文本添加圖像,其中圖像不是固定的。我使用下面的代碼,但沒有顯示在我的模擬器中。 任何人都可以糾正我在哪裏錯了嗎?從json url加載圖像到列表視圖,圖像不固定

public class CustomizedListView extends Activity { 
JSONArray posts = null; 

// All static variables 
static final String URL = "http://website/?json=get_recent_posts"; 



static final String KEY_POSTS = "posts"; 
static final String KEY_ID = "id"; 
static final String KEY_TITLE = "title"; 
static final String KEY_DATE = "date"; 
static final String KEY_CONTENT = "content"; 
static final String KEY_AUTHOR = "author"; 
static final String KEY_NAME = "name"; 
static final String KEY_THUMB_URL = "thumbnail"; 
static final String KEY_IMAGES = "images"; 

ListView list; 
LazyAdapter adapter; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 


    ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>(); 


    // Creating JSON Parser instance 
      JSONParser jParser = new JSONParser(); 

      // getting JSON string from URL 
      JSONObject json = jParser.getJSONFromUrl(URL); 
      try { 
      posts = json.getJSONArray(KEY_POSTS); 
    // looping through all song nodes <song> 
      for(int i = 0; i < posts.length(); i++){ 
       JSONObject c = posts.getJSONObject(i); 
       // Storing each json item in variable 
       String id = c.getString(KEY_ID); 
       String title = c.getString(KEY_TITLE); 
       String date = c.getString(KEY_DATE); 
       String content = c.getString(KEY_CONTENT); 

       // Phone number is agin JSON Object 
       JSONObject author = c.getJSONObject(KEY_AUTHOR); 
       String name = author.getString(KEY_NAME); 

       JSONObject images = c.getJSONObject(KEY_IMAGES); 
       String thumbnail = images.getString(KEY_THUMB_URL); 

     // creating new HashMap 
     HashMap<String, String> map = new HashMap<String, String>(); 

     // adding each child node to HashMap key => value 
     map.put(KEY_ID, id); 
     map.put(KEY_TITLE, title); 
     map.put(KEY_DATE, date); 
     map.put(KEY_NAME, name); 
     map.put(KEY_CONTENT, content); 
     map.put(KEY_THUMB_URL,thumbnail); 
     // adding HashList to ArrayList 
     songsList.add(map); 
      } 
      } catch (JSONException e) { 
       e.printStackTrace(); 

       } 


    list=(ListView)findViewById(R.id.list); 

    // Getting adapter by passing json data ArrayList 
    adapter=new LazyAdapter(this, songsList);   
    list.setAdapter(adapter); 


    // Click event for single list row 
    list.setOnItemClickListener(new OnItemClickListener() { 

     @Override 
     public void onItemClick(AdapterView<?> parent, View view, 
       int position, long id) { 


     } 
    });  
} 
} 

LazyAdapter.java

public class LazyAdapter extends BaseAdapter { 

private Activity activity; 
private ArrayList<HashMap<String, String>> data; 
private static LayoutInflater inflater=null; 
public ImageLoader imageLoader; 

public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) { 
    activity = a; 
    data=d; 
    inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    imageLoader=new ImageLoader(activity.getApplicationContext()); 
} 

public int getCount() { 
    return data.size(); 
} 

public Object getItem(int position) { 
    return position; 
} 

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

public View getView(int position, View convertView, ViewGroup parent) { 
    View vi=convertView; 
    if(convertView==null) 
     vi = inflater.inflate(R.layout.list_row, null); 

    TextView title = (TextView)vi.findViewById(R.id.title); // title 
    TextView date = (TextView)vi.findViewById(R.id.artist); // artist name 
    TextView content = (TextView)vi.findViewById(R.id.duration); // duration 
    TextView name = (TextView)vi.findViewById(R.id.name); 
    // duration 
    ImageView thumb_image=(ImageView)vi.findViewById(R.id.list_image); // thumb image 

    HashMap<String, String> song = new HashMap<String, String>(); 
    song = data.get(position); 


    ListView list; 
    // Setting all values in listview 
    title.setText(song.get(CustomizedListView.KEY_TITLE)); 
    date.setText(song.get(CustomizedListView.KEY_DATE)); 
    content.setText(song.get(CustomizedListView.KEY_CONTENT)); 
    name.setText(song.get(CustomizedListView.KEY_NAME)); 

    imageLoader.DisplayImage(song.get(CustomizedListView.KEY_THUMB_URL), thumb_image); 
    return vi; 
} 

}

imageloader.java

public class ImageLoader { 

MemoryCache memoryCache=new MemoryCache(); 
FileCache fileCache; 
private Map<ImageView, String> imageViews=Collections.synchronizedMap(new WeakHashMap<ImageView, String>()); 
ExecutorService executorService; 

public ImageLoader(Context context){ 
    fileCache=new FileCache(context); 
    executorService=Executors.newFixedThreadPool(5); 
} 

final int stub_id = R.drawable.no_image; 
public void DisplayImage(String url, ImageView imageView) 
{ 
    imageViews.put(imageView, url); 
    Bitmap bitmap=memoryCache.get(url); 
    if(bitmap!=null) 
     imageView.setImageBitmap(bitmap); 
    else 
    { 
     queuePhoto(url, imageView); 
     imageView.setImageResource(stub_id); 
    } 
} 

private void queuePhoto(String url, ImageView imageView) 
{ 
    PhotoToLoad p=new PhotoToLoad(url, imageView); 
    executorService.submit(new PhotosLoader(p)); 
} 

private Bitmap getBitmap(String url) 
{ 
    File f=fileCache.getFile(url); 

    //from SD cache 
    Bitmap b = decodeFile(f); 
    if(b!=null) 
     return b; 

    //from web 
    try { 
     Bitmap bitmap=null; 
     URL imageUrl = new URL(url); 
     HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection(); 
     conn.setConnectTimeout(30000); 
     conn.setReadTimeout(30000); 
     conn.setInstanceFollowRedirects(true); 
     InputStream is=conn.getInputStream(); 
     OutputStream os = new FileOutputStream(f); 
     Utils.CopyStream(is, os); 
     os.close(); 
     bitmap = decodeFile(f); 
     return bitmap; 
    } catch (Exception ex){ 
     ex.printStackTrace(); 
     return null; 
    } 
} 

//decodes image and scales it to reduce memory consumption 
private Bitmap decodeFile(File f){ 
    try { 
     //decode image size 
     BitmapFactory.Options o = new BitmapFactory.Options(); 
     o.inJustDecodeBounds = true; 
     BitmapFactory.decodeStream(new FileInputStream(f),null,o); 

     //Find the correct scale value. It should be the power of 2. 
     final int REQUIRED_SIZE=70; 
     int width_tmp=o.outWidth, height_tmp=o.outHeight; 
     int scale=1; 
     while(true){ 
      if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE) 
       break; 
      width_tmp/=2; 
      height_tmp/=2; 
      scale*=2; 
     } 

     //decode with inSampleSize 
     BitmapFactory.Options o2 = new BitmapFactory.Options(); 
     o2.inSampleSize=scale; 
     return BitmapFactory.decodeStream(new FileInputStream(f), null, o2); 
    } catch (FileNotFoundException e) {} 
    return null; 
} 

//Task for the queue 
private class PhotoToLoad 
{ 
    public String url; 
    public ImageView imageView; 
    public PhotoToLoad(String u, ImageView i){ 
     url=u; 
     imageView=i; 
    } 
} 

class PhotosLoader implements Runnable { 
    PhotoToLoad photoToLoad; 
    PhotosLoader(PhotoToLoad photoToLoad){ 
     this.photoToLoad=photoToLoad; 
    } 

    @Override 
    public void run() { 
     if(imageViewReused(photoToLoad)) 
      return; 
     Bitmap bmp=getBitmap(photoToLoad.url); 
     memoryCache.put(photoToLoad.url, bmp); 
     if(imageViewReused(photoToLoad)) 
      return; 
     BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad); 
     Activity a=(Activity)photoToLoad.imageView.getContext(); 
     a.runOnUiThread(bd); 
    } 
} 

boolean imageViewReused(PhotoToLoad photoToLoad){ 
    String tag=imageViews.get(photoToLoad.imageView); 
    if(tag==null || !tag.equals(photoToLoad.url)) 
     return true; 
    return false; 
} 

//Used to display bitmap in the UI thread 
class BitmapDisplayer implements Runnable 
{ 
    Bitmap bitmap; 
    PhotoToLoad photoToLoad; 
    public BitmapDisplayer(Bitmap b, PhotoToLoad p){bitmap=b;photoToLoad=p;} 
    public void run() 
    { 
     if(imageViewReused(photoToLoad)) 
      return; 
     if(bitmap!=null) 
      photoToLoad.imageView.setImageBitmap(bitmap); 
     else 
      photoToLoad.imageView.setImageResource(stub_id); 
    } 
} 

public void clearCache() { 
    memoryCache.clear(); 
    fileCache.clear(); 
} 

}

+0

你正確地得到JSON響應在模擬器? – asloob

+0

是@ user603125 – SRY

+0

Logcat中的任何錯誤/異常? – asloob

回答

0

使用Lazylist適配器

例如:

ArrayList<HashMap<String,String>> ar=new ArrayList<HashMap<String,String>>(); 

LazyAdapter adapter=new LazyAdapter(con, ar); 
     list.setAdapter(adapter); 

public class LazyAdapter extends BaseAdapter { 

    private Context activity; 
    private ArrayList<HashMap<String, String>> data; 
    private LayoutInflater inflater=null; 
    //public ImageLoader imageLoader; 
    private URL url; 
    private Bitmap bmp; 

    public LazyAdapter(Context a, ArrayList<HashMap<String, String>> d) { 
     activity = a; 
     data=d; 
     inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     //imageLoader=new ImageLoader(activity.getApplicationContext()); 
    } 

    public int getCount() { 
     return data.size(); 
    } 

    public Object getItem(int position) { 
     return position; 
    } 

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

    public View getView(int position, View convertView, ViewGroup parent) { 
     View vi=convertView; 
     if(convertView==null) 
      vi = inflater.inflate(R.layout.lis, null); 
     TextView title = (TextView)vi.findViewById(R.id.textView11); // title 
     TextView artist = (TextView)vi.findViewById(R.id.textView21); // artist nameduration 
     ImageView im=(ImageView)vi.findViewById(R.id.imageView1); 

     HashMap<String, String> song = new HashMap<String, String>(); 
     song = data.get(position); 

     // Setting all values in listview 
     title.setText(song.get("name")); 
     artist.setText(song.get("adr")); 
     try { 
      url = new URL(song.get("icon")); 
      bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream()); 
       im.setImageBitmap(bmp); 
     } catch (MalformedURLException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 


     return vi; 
    } 
} 
+0

我認爲他發佈的代碼是lazylist – asloob

+0

是的,它是lazylist – GaneshKumar

+0

那麼爲什麼你再次發佈相同的代碼? – asloob