2014-05-21 73 views
0

我正在開發一個應用程序,它將從服務器服務獲取最新消息,然後顯示在列表視圖中。代碼如下:在同一時間下載多個圖像,並更新列表視圖

HomeFragment.java 

@SuppressLint("NewApi") 
public class HomeFragment extends Fragment { 
    private ListView listView; 
    EditText search; 
    ImageButton btn; 
    ProgressDialog mProgressDialog; 
    private NewsHomeAdapter customNewsHomeAdapter; 

    Context homeFragmentContext; 

    final ArrayList<NewsItem> news_home_data = new ArrayList<NewsItem>(); 

    // child categories JSONArray 
    JSONArray newsItems = null; 

    public HomeFragment(){} 

    @Override 
    public View onCreateView(LayoutInflater inflater, final ViewGroup container, 
      Bundle savedInstanceState) { 

     View rootView = inflater.inflate(R.layout.fragment_home, container, false); 

     homeFragmentContext = container.getContext(); 
     listView = (ListView) rootView.findViewById(R.id.news_home_list); 
     search = (EditText) rootView.findViewById(R.id.search); 
     search.setOnKeyListener(new OnKeyListener() { 
      public boolean onKey(View v, int keyCode, KeyEvent event) { 
       if ((event.getAction() == KeyEvent.ACTION_DOWN) 
         && (keyCode == KeyEvent.KEYCODE_ENTER)) { 

        String query_text = search.getText().toString().trim(); 

        try { 
         query_text = URLEncoder.encode(query_text, "utf-8"); 
        } catch (UnsupportedEncodingException e) { 

        } 
        String full_query = query_text; 

        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE); 
        imm.hideSoftInputFromWindow(search.getWindowToken(), 0); 

        Intent bussiness = new Intent(homeFragmentContext, 
          SearchNews.class); 
        Bundle basket_buss_category = new Bundle(); 

        basket_buss_category.putString("SEARCH", full_query); 
        ; 

        bussiness.putExtras(basket_buss_category); 

        startActivity(bussiness); 

        return true; 
       } 
       return false; 
      } 


     }); 

     new GetNewsData().execute(TimeUtils.NEWS_HOME_URL); 

     listView.setOnItemClickListener(new OnItemClickListener() { 

      public void onItemClick(AdapterView<?> a, View v, int position, 
        long id) { 

       Intent cluster = new Intent(homeFragmentContext, NewsCluster.class); 

       Bundle newslist = new Bundle(); 
       newslist.putString("NLIST",news_home_data.get(position).getCluster()); 
       cluster.putExtras(newslist); 
       startActivity(cluster); 


      } 

     }); 

     btn = (ImageButton) rootView.findViewById(R.id.search_button); 
     btn.setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View arg0) { 

       String query_text = search.getText().toString().trim(); 
       if (query_text.equalsIgnoreCase("")) { 

        search.requestFocus(); 
        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE); 
        imm.hideSoftInputFromWindow(search.getWindowToken(), 0); 
       } 

       else { 

        try { 
         query_text = URLEncoder.encode(query_text, "utf-8"); 
        } catch (UnsupportedEncodingException e) { 
         e.printStackTrace(); 
        } 
        String full_query = query_text; 

        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE); 
        imm.hideSoftInputFromWindow(search.getWindowToken(), 0); 

        Intent bussiness = new Intent(homeFragmentContext, SearchNews.class); 
        Bundle basket_buss_category = new Bundle(); 

        basket_buss_category.putString("SEARCH", full_query); 

        bussiness.putExtras(basket_buss_category); 

        startActivity(bussiness); 

       } 

      } 
     }); 

     return rootView; 
    } 

    private class GetNewsData extends 
    AsyncTask<String, Void, ArrayList<NewsItem>> { 

protected void onPreExecute() { 
    super.onPreExecute(); 

    // shfaq Progress Dialogun, deri ne momentin qe te loadohen te 
    // dheant 
    mProgressDialog = new ProgressDialog(homeFragmentContext); 
    mProgressDialog.setMessage("Loading..."); 
    mProgressDialog.setIndeterminate(false); 
    mProgressDialog.show(); 
} 

@Override 
protected ArrayList<NewsItem> doInBackground(String... URL) { 

    String categories_url = URL[0]; 
    // Creating JSON Parser instance 
    JSONParser jParser = new JSONParser(); 
    // getting JSON string from URL 
    newsItems = jParser.getJSONFromUrl(categories_url); 
    Log.e("lsbsfbsfdbsfd", newsItems.toString()); 
    try { 
     for (int i = 0; i < newsItems.length(); i++) { 

      JSONObject c = newsItems.getJSONObject(i); 

      Log.e("po fillo procesimin e ", String.valueOf(i)); 
      String tittle = c.getString(TimeUtils.TAG_TITLE); 
      String desc = c.getString(TimeUtils.TAG_DESC); 
      String source = c.getString(TimeUtils.TAG_SOURCE); 
      String id = c.getString(TimeUtils.TAG_ID); 
      String link = c.getString(TimeUtils.TAG_LINK); 
      String published_time = c.getString(TimeUtils.TAG_PUB_TIME); 
      String image_url = c.getString(TimeUtils.TAG_IMAGE_URL); 
      String newsList = c.getString(TimeUtils.TAG_CLUSTER); 
      // download the image; 
      Bitmap bitmap = null; 


      try { // Download Image from URL 
       InputStream input = new 
       java.net.URL(image_url) .openStream(); // Decode Bitmap 

       bitmap = BitmapFactory.decodeStream(input); } catch 
       (Exception e) { 

       } 


      news_home_data.add(new NewsItem(tittle, desc, source, id, 
        link, published_time, bitmap,newsList)); 
     } 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 
    return news_home_data; 
} 

@SuppressLint("ResourceAsColor") 
@Override 
protected void onPostExecute(ArrayList<NewsItem> news_home_data) { 
    customNewsHomeAdapter = new NewsHomeAdapter(homeFragmentContext, 
      news_home_data); 
    listView.setAdapter(customNewsHomeAdapter); 
    // setting the nav drawer list adapter 
    mProgressDialog.dismiss(); 
} 
} 

該適配器如下所示。

NesHomeAdapter.java 

package com.dev.apk.time.al; 

public class NewsHomeAdapter extends BaseAdapter{ 

    private ArrayList<NewsItem> news_data; 

    private LayoutInflater layoutInflater; 

    public NewsHomeAdapter(Context context, ArrayList<NewsItem> news_data) { 
     this.news_data = news_data; 
     layoutInflater = LayoutInflater.from(context); 
    } 

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

    public Object getItem(int position) { 
     return news_data.get(position); 
    } 

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

    public View getView(int position, View convertView, ViewGroup parent) { 
     ViewHolder holder; 
     if (convertView == null) { 
      convertView = layoutInflater.inflate(R.layout.news_home_row, null); 
      holder = new ViewHolder(); 
      holder.tittle = (TextView) convertView.findViewById(R.id.tittle); 
      holder.source = (TextView) convertView.findViewById(R.id.source); 
      holder.published_time = (TextView) convertView.findViewById(R.id.published_time); 
      holder.news_image = (ImageView) convertView.findViewById(R.id.news_image); 
      convertView.setTag(holder); 
     } else { 
      holder = (ViewHolder) convertView.getTag(); 
     } 

     holder.tittle.setText(((NewsItem) news_data.get(position)).getTittle()); 
     holder.source.setText(((NewsItem) news_data.get(position)).getSource()); 
     holder.published_time.setText(((NewsItem) news_data.get(position)).getPublishedTime()); 
     holder.news_image.setImageBitmap(((NewsItem) news_data.get(position)).getImage()); 


     return convertView; 
    } 

    static class ViewHolder { 
     ImageView news_image; 
     TextView tittle; 
     TextView source; 
     TextView published_time; 

    }  
} 

正如你我有一個自定義列表視圖。對於每一行我都有一個圖像,它是基於來自JSON的URL下載的。但是我第一次至少有40條新聞,這意味着40張圖片。顯示新聞需要太多時間。

任何人都可以幫助我如何在同一時間下載圖像,然後更新listView,還是有辦法顯示新聞,標題,說明等,並在以後更新圖像?

+0

嘗試使用AndroidQuery爲,看到這裏https://code.google.com/p/android-query/ –

回答

0

使用這個庫UrlImageViewHelper

通過調用

UrlImageViewHelper.setUrlDrawable(yourImageView, "http://example.com/image.png", R.drawable.your_loading_image); 
在適配器


它會首先創建列表,後來下載圖像,當圖像被下載,它會顯示your_loading_image,和下載的圖像將被顯示不久

編輯:
準確地說,通過YOUT的getImage返回的圖片()函數中的類NewsI TEM應該是一個字符串URL到你的形象,並替換該行

holder.news_image.setImageBitmap(((NewsItem) news_data.get(position)).getImage()); 

UrlImageViewHelper.setUrlDrawable(holder.news_image, news_data.get(position).getImage(), R.drawable.your_loading_image); 


我已經遇到過這個問題,並UrlImageViewHelper是解決這一最簡單的方法,只需導入庫並使用一行就可以得到你想要的內容,不需要使用AsyncTask加載圖像來自定義自己的AsyncTask

+0

它給了我一個錯誤:java.lang.NoClassDefFoundError。這與我導入它的方式或圖書館本身有關。 – Xhulio

+0

@xhulio koush已經爲UrlImageViewHelper提供了一個jar庫文件(查看github鏈接中的描述,你會發現jar下載鏈接),你只需要在你的項目構建路徑中添加jar – ffyeahh

0

我推薦你使用AsyncTask在Android中。請看http://developer.android.com/reference/android/os/AsyncTask.html

這將幫助您在後臺運行並將您的進度或下載的圖像發佈到imageview上。

new AsyncTask<String,Void,Void>(){ 
@Override 
protected Void doInBackground(String...arg){ 
    //download the image against the url, and run in the background as not on UI thread. 
} 

@Override 
protected void onPostExecute(Void v){ 
    //Load the imageview with the downloaded image. 
} 

}.execute(url1,url2,url3); 
相關問題