리스트 뷰의 아이템을 클릭하면 파싱한 데이터를 조합하여 이미지 URL을 생성하고 이미지를 다운로드하여 새로운 액티비티에 보여주는 과정을 설명합니다.
http://webnautes.tistory.com/459
http://webnautes.tistory.com/462
http://webnautes.tistory.com/471
http://webnautes.tistory.com/472
최초 작성 - 2014.07. 7
최종 업데이트 - 2017.12.22
실행 과정
1. 검색할 이미지를 위한 단어를 입력하고 버튼을 클릭합니다.
2. 검색한 단어에 대응하는 이미지를 보여주기 위해 필요한 JSON 데이터 파싱 결과를 보여줍니다.
3. 리스트뷰의 아이템을 선택해주면 아이템에 있는 문자열들을 조합하여 이미지를 다운로드 받을 수 있는 URL을 생성합니다.
그리고 나서 해당 URL로부터 이미지를 다운로드 받고 새로운 액티비티의 ImageView에 보여줍니다.
돌아가기를 누르면 메인 액티비티로 돌아갑니다.
소스코드 설명
1. MainActivity의 onCreate 메소드에 다음 코드를 추가합니다.
ListView의 아이템을 클릭했을 때 해당 사진을 보여주기 위해 필요한 정보들과 함께 ShowImage 액티비티를 실행합니다.
listviewPhtoList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView textviewId = (TextView)view.findViewById(R.id.textview_main_listviewdata1); TextView textviewTitle = (TextView)view.findViewById(R.id.textview_main_listviewdata2); TextView textviewSecret = (TextView)view.findViewById(R.id.textview_main_listviewdata3); TextView textviewServer = (TextView)view.findViewById(R.id.textview_main_listviewdata4); TextView textviewFarm = (TextView)view.findViewById(R.id.textview_main_listviewdata5);
Bundle bundle = new Bundle(); bundle.putString( "id", textviewId.getText().toString()); bundle.putString( "title", textviewTitle.getText().toString()); bundle.putString( "secret", textviewSecret.getText().toString()); bundle.putString( "server", textviewServer.getText().toString()); bundle.putString( "farm", textviewFarm.getText().toString());
Intent intent = new Intent(MainActivity.this, ShowImage.class); intent.putExtras(bundle); startActivity(intent); } }); |
2. ShowImage 액티비티가 실행되려면 매니페스트 파일에 다음처럼 추가해줘야 합니다.
<application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity>
<activity android:name=".ShowImage"> </activity> </application>
</manifest> |
3. ShowImage 액티비티가 실행되면 인자들을 받아서 이미지를 가져오기 위한 주소를 조합합니다.
그리고나서 AsyncTask를 실행합니다.
@Override protected void onCreate( Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_showimage);
imageviewThumbnailPhoto = (ImageView)findViewById(R.id.imageview_showimage_small); imageviewLargePhoto = (ImageView)findViewById(R.id.imageview_showimage_large); Button buttonBack = (Button)findViewById(R.id.button_showimage_back); buttonBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } });
Intent intent = getIntent(); Bundle bundle = intent.getExtras(); String id = bundle.getString("id"); String title = bundle.getString("title"); String secret = bundle.getString("secret"); String server = bundle.getString("server"); String farm = bundle.getString("farm");
String thumbnailPhotoURL = "http://farm"+farm+".staticflickr.com/"+server+"/" +id+"_"+secret+"_t.jpg"; String largePhotoURL = "http://farm"+farm+".staticflickr.com/"+server+"/" +id+"_"+secret+"_b.jpg";
showimageTask task = new showimageTask(); task.execute(thumbnailPhotoURL, largePhotoURL); } |
4. doInBackground에서 getImageFromURL함수를 호출하여 이미지를 가져와서 bitmap에 저장합니다.
그리고 onPostExecute에서 ImageVIew에 보여지도록 해줍니다.
private class showimageTask extends AsyncTask<String, Void, Bitmap[]> {
ProgressDialog progressDialog;
@Override protected void onPreExecute() { super.onPreExecute();
progressDialog = new ProgressDialog( ShowImage.this ); progressDialog.setMessage("Please wait....."); progressDialog.show(); }
@Override protected Bitmap[] doInBackground(String... url) {
String thumbnailPhotoURL = url[0].toString(); String largePhotoURL = url[1].toString();
Bitmap[] bitmap = new Bitmap[2]; bitmap[0] = getImagefromURL(thumbnailPhotoURL); bitmap[1] = getImagefromURL(largePhotoURL);
return bitmap; }
@Override protected void onPostExecute(Bitmap[] bitmap) { super.onPostExecute(bitmap);
imageviewThumbnailPhoto.setImageBitmap(bitmap[0]); imageviewLargePhoto.setImageBitmap(bitmap[1]);
progressDialog.dismiss(); }
} |
전체 소스코드
세번째 포스팅과 중복되는 코드는 제외했습니다.
activity_showimage.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent">
<LinearLayout android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="0.9" android:orientation="vertical">
<ImageView android:id="@+id/imageview_showimage_small" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="0.3"/> <ImageView android:id="@+id/imageview_showimage_large" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="0.7"/>
</LinearLayout>
<Button android:id="@+id/button_showimage_back" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="0.1" android:text="돌아가기" /> </LinearLayout> |
ShowImage.java
package com.tistory.webnautes.imagesearchexample;
import android.app.ProgressDialog; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ImageView;
import java.io.BufferedInputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL;
/** * Created by webnautes on 2017-12-22. */
public class ShowImage extends AppCompatActivity {
private static final String TAG = "imagesearchexample"; private ImageView imageviewThumbnailPhoto; private ImageView imageviewLargePhoto;
@Override protected void onCreate( Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_showimage);
imageviewThumbnailPhoto = (ImageView)findViewById(R.id.imageview_showimage_small); imageviewLargePhoto = (ImageView)findViewById(R.id.imageview_showimage_large); Button buttonBack = (Button)findViewById(R.id.button_showimage_back); buttonBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } });
Intent intent = getIntent(); Bundle bundle = intent.getExtras(); String id = bundle.getString("id"); String title = bundle.getString("title"); String secret = bundle.getString("secret"); String server = bundle.getString("server"); String farm = bundle.getString("farm");
String thumbnailPhotoURL = "http://farm"+farm+".staticflickr.com/"+server+"/" +id+"_"+secret+"_t.jpg"; String largePhotoURL = "http://farm"+farm+".staticflickr.com/"+server+"/" +id+"_"+secret+"_b.jpg";
showimageTask task = new showimageTask(); task.execute(thumbnailPhotoURL, largePhotoURL); }
private class showimageTask extends AsyncTask<String, Void, Bitmap[]> {
ProgressDialog progressDialog;
@Override protected void onPreExecute() { super.onPreExecute();
progressDialog = new ProgressDialog( ShowImage.this ); progressDialog.setMessage("Please wait....."); progressDialog.show(); }
@Override protected Bitmap[] doInBackground(String... url) {
String thumbnailPhotoURL = url[0].toString(); String largePhotoURL = url[1].toString();
Bitmap[] bitmap = new Bitmap[2]; bitmap[0] = getImagefromURL(thumbnailPhotoURL); bitmap[1] = getImagefromURL(largePhotoURL);
return bitmap; }
@Override protected void onPostExecute(Bitmap[] bitmap) { super.onPostExecute(bitmap);
imageviewThumbnailPhoto.setImageBitmap(bitmap[0]); imageviewLargePhoto.setImageBitmap(bitmap[1]);
progressDialog.dismiss(); }
}
public Bitmap getImagefromURL(final String photoURL){
if ( photoURL == null) return null;
try {
URL url = new URL(photoURL); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setReadTimeout(3000); httpURLConnection.setConnectTimeout(3000); httpURLConnection.setDoInput(true); httpURLConnection.setRequestMethod("GET"); httpURLConnection.setUseCaches(false); httpURLConnection.connect();
int responseStatusCode = httpURLConnection.getResponseCode();
InputStream inputStream; if (responseStatusCode == HttpURLConnection.HTTP_OK) {
inputStream = httpURLConnection.getInputStream(); } else return null;
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream); Bitmap bitmap = BitmapFactory.decodeStream(bufferedInputStream);
bufferedInputStream.close(); httpURLConnection.disconnect();
return bitmap;
} catch (Exception e) { Log.d(TAG, e.toString()); }
return null; } }
|