2012-10-18 1 views
0

Я следую за этим toturial Android Lazy Loading images and text in listview from http json data, и теперь я меняю listview на gridview.Gridview - щелкните элемент gridview, чтобы показать изображение в образе просмотра

Мой вопрос

Я хочу нажать GridView элемент и показать изображение в ImageView

MainActivity

public class MainActivity extends Activity { 

GridView gridView; 

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

    String strUrl = "http://ta.wptrafficanalyzer.in/demo1/first.php/countries/"; 
    DownloadTask downloadTask = new DownloadTask(); 
    downloadTask.execute(strUrl); 

    gridView = (GridView) findViewById(R.id.lv_countries); 
    gridView.setOnItemClickListener(new OnItemClickListener() { 

     public void onItemClick(AdapterView<?> parent, View v, int positon, 
       long id) { 
      Toast.makeText(getApplicationContext(), "welcome to hello gridview", Toast.LENGTH_SHORT).show(); 
     } 
    }); 

} 

private String downloadUrl(String strUrl) throws IOException{ 
    String data = ""; 
    InputStream iStream = null; 
    try{ 
     URL url = new URL(strUrl); 
     HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); 
     urlConnection.connect(); 
     iStream = urlConnection.getInputStream(); 
     BufferedReader br = new BufferedReader(new InputStreamReader(iStream)); 
     StringBuffer sb = new StringBuffer(); 
     String line = ""; 
     while((line = br.readLine()) != null){ 
      sb.append(line); 
     } 

     data = sb.toString(); 
     br.close(); 

    }catch(Exception e){ 
     Log.d("Exception while downloading url", e.toString()); 
    }finally{ 
     iStream.close(); 
    } 

    return data; 
} 

private class DownloadTask extends AsyncTask<String, Integer, String>{ 
    String data = null; 
    @Override 
    protected String doInBackground(String... url) { 
     try{ 
      data = downloadUrl(url[0]); 
     }catch(Exception e){ 
      Log.d("Background Task",e.toString()); 
     } 
     return data; 
    } 

    @Override 
    protected void onPostExecute(String result) { 
     ListViewLoaderTask listViewLoaderTask = new ListViewLoaderTask(); 
     listViewLoaderTask.execute(result); 
    } 
} 

private class ListViewLoaderTask extends AsyncTask<String, Void, SimpleAdapter>{ 

    JSONObject jObject; 
    @Override 
    protected SimpleAdapter doInBackground(String... strJson) { 
     try{ 
      jObject = new JSONObject(strJson[0]); 
      CountryJSONParser countryJsonParser = new CountryJSONParser(); 
      countryJsonParser.parse(jObject); 
     }catch(Exception e){ 
      Log.d("JSON Exception1",e.toString()); 
     } 

     CountryJSONParser countryJsonParser = new CountryJSONParser(); 
     List<HashMap<String, Object>> countries = null; 

     try{ 
      countries = countryJsonParser.parse(jObject); 
     }catch(Exception e){ 
      Log.d("Exception",e.toString()); 
     } 

     String[] from = { "country","flag","details"}; 
     int[] to = { R.id.tv_country,R.id.iv_flag,R.id.tv_country_details}; 
     SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), countries, R.layout.lv_layout, from, to); 

     return adapter; 
    } 

    @Override 
    protected void onPostExecute(SimpleAdapter adapter) { 

     gridView.setAdapter(adapter); 

     for(int i=0;i<adapter.getCount();i++){ 
      HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(i); 
      String imgUrl = (String) hm.get("flag_path"); 
      ImageLoaderTask imageLoaderTask = new ImageLoaderTask(); 

      HashMap<String, Object> hmDownload = new HashMap<String, Object>(); 
      hm.put("flag_path",imgUrl); 
      hm.put("position", i); 

      imageLoaderTask.execute(hm); 
     } 
    } 
} 

private class ImageLoaderTask extends AsyncTask<HashMap<String, Object>, Void, HashMap<String, Object>>{ 

    @Override 
    protected HashMap<String, Object> doInBackground(HashMap<String, Object>... hm) { 

     InputStream iStream=null; 
     String imgUrl; 
     imgUrl = (String) hm[0].get("flag_path"); 
     int position = (Integer) hm[0].get("position"); 

     URL url; 
     try { 
      url = new URL(imgUrl); 
      HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); 
      urlConnection.connect(); 
      iStream = urlConnection.getInputStream(); 

      File cacheDirectory = getBaseContext().getCacheDir(); 
      File tmpFile = new File(cacheDirectory.getPath() + "/wpta_"+position+".png"); 
      FileOutputStream fOutStream = new FileOutputStream(tmpFile); 

      Bitmap b = BitmapFactory.decodeStream(iStream); 
      b.compress(Bitmap.CompressFormat.PNG,100, fOutStream); 

      fOutStream.flush(); 
      fOutStream.close(); 
      HashMap<String, Object> hmBitmap = new HashMap<String, Object>(); 

      hmBitmap.put("flag",tmpFile.getPath()); 
      hmBitmap.put("position",position); 

      return hmBitmap; 

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

    @Override 
    protected void onPostExecute(HashMap<String, Object> result) { 
     String path = (String) result.get("flag"); 
     int position = (Integer) result.get("position"); 

     SimpleAdapter adapter = (SimpleAdapter) gridView.getAdapter(); 
     HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(position); 
     hm.put("flag",path); 

     adapter.notifyDataSetChanged(); 
    } 
} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    getMenuInflater().inflate(R.menu.activity_main, menu); 
    return true; 
} 

} CountryJSONParser.java

public class CountryJSONParser { 

public List<HashMap<String,Object>> parse(JSONObject jObject){ 

    JSONArray jCountries = null; 
    try { 
     jCountries = jObject.getJSONArray("countries"); 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 

    return getCountries(jCountries); 
} 

private List<HashMap<String, Object>> getCountries(JSONArray jCountries){ 
    int countryCount = jCountries.length(); 
    List<HashMap<String, Object>> countryList = new ArrayList<HashMap<String,Object>>(); 
    HashMap<String, Object> country = null; 

    for(int i=0; i<countryCount;i++){ 
     try { 
      country = getCountry((JSONObject)jCountries.get(i)); 
      countryList.add(country); 

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

    return countryList; 
} 

private HashMap<String, Object> getCountry(JSONObject jCountry){ 

    HashMap<String, Object> country = new HashMap<String, Object>(); 
    String countryName = ""; 
    String flag=""; 
    String language = ""; 
    String capital = ""; 
    String currencyCode = ""; 
    String currencyName = ""; 

    try { 
     countryName = jCountry.getString("countryname"); 
     flag = jCountry.getString("flag"); 
     language = jCountry.getString("language"); 
     capital = jCountry.getString("capital"); 
     currencyCode = jCountry.getJSONObject("currency").getString("code"); 
     currencyName = jCountry.getJSONObject("currency").getString("currencyname"); 

     String details =  "Language : " + language + "\n" + 
          "Capital : " + capital + "\n" + 
          "Currency : " + currencyName + "(" + currencyCode + ")"; 

     country.put("country", countryName); 
     country.put("flag", R.drawable.blank); 
     country.put("flag_path", flag); 
     country.put("details", details); 

    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 
    return country; 
} 

} 

Когда Done, но Изображение gridview не отображается правильно

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent" 
android:layout_height="match_parent" > 

activity_man.xml

<GridView 
    android:id="@+id/lv_countries" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:columnWidth="90dp" 
    android:numColumns="auto_fit" 
    android:verticalSpacing="10dp" 
    android:horizontalSpacing="10dp" 
    android:stretchMode="columnWidth" 
    android:gravity="center" 
    tools:context=".MainActivity" /> 

ly_layout.xml

<?xml version="1.0" encoding="utf-8"?> 

<ImageView 
    android:id="@+id/iv_flag" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:contentDescription="@string/str_iv_flag" /> 

enter image description here

+0

Где находится изображение 'imageview', чтобы отобразить изображение элемента 'gridview'. Вы можете запустить новое действие, которое имеет «образное изображение» и загрузить изображение из URL-адреса и установить его в «imageview» –

+0

Да, я хочу сделать это, но я не могу. вы можете заполнить его для меня. заранее спасибо – kongkea

ответ

1

В GridView onClickListener получить данные щелкнули пункта

gridView.setOnItemClickListener(new OnItemClickListener() { 

     public void onItemClick(AdapterView<?> parent, View v, int positon, 
       long id) { 
HashMap<String, Object> hm = gridView.getAdapter().getPosition(positon); 

    String imgPath = (String) hm.get("flag"); //get downloaded image path 
Intent i = new Intent(yourActivityContext, NewActivityToDisplayImage.class); //start new Intent to another Activity. 
i.putExtra("ClickedImagePath", imgPath); //put image link in intent. 
startActivity(i); 

     } 
    }); 

В NewActivityToDisplayImage получить путь к изображению и установите ImageView.

public class NewActivityToDisplayImage extends Activity { 

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

     String imagePath = getIntent().getStringExtra("ClickedImagePath"); //get image path from post activity 
     if (imagePath != null && !imagePath.isEmpty) { 
      File imgFile = new File(imagePath); 
      if (imgFile.exists()) { 

       Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath()); 

       ImageView myImage = (ImageView) findViewById(R.id.imageviewTest); 
       myImage.setImageBitmap(myBitmap); 

      } 

     } 

    }} 
+0

Можете ли вы посмотреть мой код. в 'HashMap hm = yourAdapter.getItem (positon);' я использую SimpleAdapter и адаптер, но это ошибка yourAdapter. поэтому я не знаю, чтобы заполнить эту позицию. не могли бы вы найти его в моем коде – kongkea

+0

Измените свой «адаптер простого адаптера» в глобальном поле «PostExecute» и измените «yourAdapter» на «adapter». Или просто вызовите 'gridView.getAdapter(). GetItem (positon)'. –

+0

Я использую 'gridView.getAdapter(). GetItem (postion)' это работа. но «адаптер простого адаптера» в 'PostExecute' изменился на что ?. Спасибо большое. – kongkea