im beginner in android.
i have 2 class in 2 .java file. first:Mainacivity and second:ImageDownloader.
imagedownloader downloads bitmap with it's function getBitmapFromURL(String url), i give string to this function and it works well, but i wanna download more than 1 bitmap one after another.
my main activity:
public class MainActivity extends Activity implements View.OnClickListener
{
private Button download, downloadBG, save;
private ImageView img;
private ProgressBar pb;
private EditText etUrl;
private TextView percent;
private ImageDownloader mDownloader;
private static Bitmap bmp;
private FileOutputStream fos;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
/*--- initialize layout compinents ---*/
private void initViews() {
download = (Button) findViewById(R.id.btnDownload);
downloadBG = (Button) findViewById(R.id.btnDownloadBackground);
save = (Button) findViewById(R.id.btnSave);
/*--- we are using 'this' because our class implements the OnClickListener ---*/
download.setOnClickListener(this);
downloadBG.setOnClickListener(this);
save.setOnClickListener(this);
save.setEnabled(false);
img = (ImageView) findViewById(R.id.image);
img.setScaleType(ScaleType.CENTER_CROP);
pb = (ProgressBar) findViewById(R.id.pbDownload);
pb.setVisibility(View.INVISIBLE);
etUrl = (EditText) findViewById(R.id.etUrl);
percent = (TextView) findViewById(R.id.tvPercent);
percent.setVisibility(View.INVISIBLE);
}
#Override
public void onClick(View v) {
/*--- determine which button was clicked ---*/
switch (v.getId())
{
case R.id.btnDownload:
{
/*--- we use trim() to remove whitespaces which could be entered ---*/
bmp = ImageDownloader.getBitmapFromURL(URLbuilder(0, 0, 0));
img.setImageBitmap(bmp);
save.setEnabled(true);
break;
}
case R.id.btnDownloadBackground:
for(int a = 0 ; a < 4 ; a++)
{
/*--- check whether there is some Text entered ---*/
/*--- instantiate our downloader passing it required components ---*/
mDownloader = new ImageDownloader(URLbuilder(a, a, a), a,pb, save, img, percent, MainActivity.this, bmp, new ImageLoaderListener() {
#Override
public void onImageDownloaded(Bitmap bmp) {
MainActivity.bmp = bmp;
/*--- here we assign the value of bmp field in our Loader class
* to the bmp field of the current class ---*/
}
});
/*--- we need to call execute() since nothing will happen otherwise ---*/
mDownloader.execute();
}
break;
}
}
public String URLbuilder(int x , int y , int z)
{
String myurl = "http://khm0.google.com/kh/v=132&hl=EN&x={0}&y={1}&z={2}&s=";
String.format(myurl, x,y,z);
return String.format(myurl, x,y,z);
}
}
if i click on DownloadBackground button it should download 4 bitmap from it's url.
i know that each download take some time but i cannot stop this function untill first bitmap download.
my imagedownloader:
public class ImageDownloader extends AsyncTask<Void, Integer, Void>
{
private ProgressBar pb;
private String url;
private Button save;
private Context c;
private int progress;
private ImageView img;
private Bitmap bmp;
private TextView percent;
private ImageLoaderListener listener;
FileOutputStream fos;
int Counter = 0;
/*--- constructor ---*/
public ImageDownloader(String url,int counter, ProgressBar pb, Button save,
ImageView img, TextView percent, Context c, Bitmap bmp, ImageLoaderListener listener) {
/*--- we need to pass some objects we are going to work with ---*/
this.url = url;
this.pb = pb;
this.save = save;
this.c = c;
this.img = img;
this.percent = percent;
this.bmp = bmp;
this.listener = listener;
//this.Counter = Integer.toString(counter);
}
/*--- we need this interface for keeping the reference to our Bitmap from the MainActivity.
* Otherwise, bmp would be null in our MainActivity*/
public interface ImageLoaderListener {
void onImageDownloaded(Bitmap bmp);
}
#Override
protected void onPreExecute() {
progress = 0;
pb.setVisibility(View.VISIBLE);
percent.setVisibility(View.VISIBLE);
Toast.makeText(c, "starting download", Toast.LENGTH_SHORT).show();
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
bmp = getBitmapFromURL(url);
while (progress < 100) {
progress += 1;
publishProgress(progress);
/*--- an image download usually happens very fast so you would not notice
* how the ProgressBar jumps from 0 to 100 percent. You can use the method below
* to visually "slow down" the download and see the progress bein updated ---*/
//SystemClock.sleep(200);
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
/*--- show download progress on main UI thread---*/
pb.setProgress(values[0]);
percent.setText(values[0] + "%");
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(Void result) {
if (listener != null) {
listener.onImageDownloaded(bmp);
}
img.setImageBitmap(bmp);
saveImageToSD();
save.setEnabled(true);
Toast.makeText(c, "download complete", Toast.LENGTH_SHORT).show();
super.onPostExecute(result);
}
public static Bitmap getBitmapFromURL(String link)
{
/*--- this method downloads an Image from the given URL,
* then decodes and returns a Bitmap object
---*/
try {
URL url = new URL(link);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
Log.e("getBmpFromUrl error: ", e.getMessage().toString());
return null;
}
}
private void saveImageToSD()
{
/*--- this method will save your downloaded image to SD card ---*/
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
/*--- you can select your preferred CompressFormat and quality.
* I'm going to use JPEG and 100% quality ---*/
bmp.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
/*--- create a new file on SD card ---*/
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator + "myDownloadedImage" + Integer.toString(Counter) + ".jpg");
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
/*--- create a new FileOutputStream and write bytes to file ---*/
try {
fos = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
fos.write(bytes.toByteArray());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
Counter++;
}
i need to stop for loop in onclick method in main activity until each image download. i did every things that i knew but every time it crashed.
later i have to put image downloader in a thread but i dont know how to stop thread for a while.
pls help me. ty
You can use Handler
new Handler().postDelayed(new Runnable(){
public void run() {
//some job to do delayed 3s
}}, 3000);
Hope it helps!
Related
I want to save imageView into sd card but I get the following exception (some times not always) when I try to get bitmap from imageView. Can somebody please help me? Thanks in advance
Caused by: java.lang.IllegalArgumentException: width and height must be > 0 at android.graphics.Bitmap.createBitmap(Bitmap.java:922)
public static class SaveImageToSD extends AsyncTask<String, Void, String> {
Context context;
ImageView mImageView;
ProgressDialog progressDialog;
public SaveImageToSD(Context context, ImageView iv, String name) {
this.context = context;
this.mImageView = iv;
}
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(context, "", context.getResources().getString(R.string.please_wait), true);
}
#Override
protected void onPostExecute(String result) {
}
#Override
protected String doInBackground(String... x) {
File projectFolder = new File(Environment.getExternalStorageDirectory() + File.separator + Settings.projectFolder + File.separator);
boolean folderCreateSuccess = true;
if (!projectFolder.exists()) {
folderCreateSuccess = projectFolder.mkdir();
}
if (folderCreateSuccess) {
Bitmap bitmap;
// Exception in if statement
if (mImageView.getDrawable() instanceof BitmapDrawable) {
bitmap = ((BitmapDrawable) mImageView.getDrawable()).getBitmap();
} else {
Drawable d = mImageView.getDrawable();
bitmap = Bitmap.createBitmap(d.getIntrinsicWidth(), d.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
d.draw(canvas);
}
File image = new File(projectFolder, "GE_" + System.currentTimeMillis() + ".jpg");
boolean success = false;
// Encode the file as a PNG image.
FileOutputStream outStream;
try {
outStream = new FileOutputStream(image);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
/* 100 to keep full quality of the image */
outStream.flush();
outStream.close();
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "title");
values.put(MediaStore.Images.Media.DESCRIPTION, "description");
values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(MediaStore.Images.ImageColumns.BUCKET_ID, image.toString().toLowerCase(Locale.US).hashCode());
values.put(MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME, image.getName().toLowerCase(Locale.US));
values.put("_data", image.getAbsolutePath());
ContentResolver cr = context.getContentResolver();
cr.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
success = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
progressDialog.dismiss();
if (success) {
((ActionBarActivity)context).runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(context, context.getResources().getString(R.string.image_successfully_saved), Toast.LENGTH_SHORT).show();
}
});
} else {
((ActionBarActivity)context).runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(context, context.getResources().getString(R.string.image_successfully_saved), Toast.LENGTH_SHORT).show();
}
});
}
} else {
Log.i("Create Folder", "Error during create folder");
}
return "";
}
}
to set image I use following code, I'm using transparentDrawable because of Picasso wrap content problem
transparentDrawable.setBounds(new Rect(0, 0, 1000, 1000));
Picasso.with(mContext).load(((FBPhotoCard) mImageCards.get(position)).getThumbnail()).placeholder(transparentDrawable).noFade().into(holder.imageView);
I think the exception is of because d.getIntrinsicWidth(), d.getIntrinsicHeight() at line bitmap = Bitmap.createBitmap(d.getIntrinsicWidth(), d.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
According to Android docs drawable.getIntrinsicWidth() Return the intrinsic width of the underlying drawable object. Returns -1 if it has no intrinsic width, such as with a solid color. So make sure to pass values greater than 1 to Bitmap.createBitmap() method
This error you are getting because d.getIntrinsicWidth(), d.getIntrinsicHeight() returning 0 try to put some constant value and then check like 100.
I'm making an application that implements the Camera, and I was wondering why does the image get saved to a tiny bitmap when I take a picture?
When I press the capture button, for some reason the image gets scaled down (I need to save the image to INTERNAL memory, not external/sd card) and I end up having to scale it back up to display it in the ImageView, which obviously makes the photo a little bit more grainy than the camera preview is. Is there a better way to do this?
I want it to be similar to SnapChat, where the picture you take is displayed exactly how it looked when you took it...
Here's the main Activity:
public class MainActivity extends FragmentActivity {
private static final String TAG = "CameraActivity";
public static final int MEDIA_TYPE_IMAGE = 1;
private Camera mCamera;
private CameraPreview mPreview;
private Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
if(checkCameraHardware(mContext)){
// Create an instance of Camera
mCamera = getCameraInstance();
// Create our Preview view and set it as the content of our activity.
mPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mPreview);
// Add a listener to the Capture button
Button captureButton = (Button) findViewById(R.id.button_capture);
captureButton.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
// get an image from the camera
mCamera.takePicture(null, null, mPicture);
}
}
);
}
}
private Camera.PictureCallback mPicture = new Camera.PictureCallback() {
#Override
public void onPictureTaken(final byte[] data, Camera camera) {
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
try {
FileOutputStream fos = openFileOutput("img.jpg", Context.MODE_PRIVATE);
fos.write(data);
fos.close();
return "img.jpg";
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
return null;
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
return null;
}
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(result != null){
Intent intent = new Intent(mContext, ImageDisplayActivity.class);
intent.putExtra(ImageDisplayActivity.KEY_PATH, "img.jpg");
startActivity(intent);
}
}
}.execute();
}
};
private boolean checkCameraHardware(Context context) {
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
public static Camera getCameraInstance(){
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance
}
catch (Exception e){
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
}
/** Create a File for saving an image or video */
}
And here's the Image Display Activity:
public class ImageDisplayActivity extends FragmentActivity {
public static final String KEY_PATH = "img.jpg";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_display);
Intent intent = getIntent();
String path = getIntent().getStringExtra(ImageDisplayActivity.KEY_PATH);
try {
java.io.FileInputStream in = this.openFileInput(path);
Bitmap bitmap = BitmapFactory.decodeStream(in);
ZoomInZoomOut touch = (ZoomInZoomOut)findViewById(R.id.IMAGEID);
touch = arrangeImageView(touch);
touch.setImageBitmap(bitmap);
in.close();
Canvas c = new Canvas(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
}
private ZoomInZoomOut arrangeImageView(ZoomInZoomOut img){
try {
img.setRotation(90);
img.setScaleX(2f);
img.setScaleY(2f);
} catch (Exception e) {
e.printStackTrace();
}
return img;
}
}
My application has a "start download" and a "pause" button. Once I start the download through "Start Download" button my download starts and stop upon clicking "pause" now when I press back or home button the onPause() function works as intended it pauses my download and when I open the app again and click start it resumes from that progress,
what I want is that upon switching back(not the first time load of app) to the application once I have pressed back or home I want the download to resume automatically by onResume without clicking start button again. Right now in below code my download automatically starts without doing anything which is due to my onResume(), is it possible that I can resume with onResume but not start the download automatically upon first time loading of the app thorugh it? I know the below code is not as efficient as it could have been. Apologies for that.
Again, I want my onResume to only resume my previously downloaded file not start the download unless download was once initiated through the button.
public class MainActivity extends Activity implements OnClickListener{
String url = "http://upload.wikimedia.org/wikipedia/commons/1/11/HUP_10MB_1946_obverse.jpg";
boolean mStopped=false;
private ProgressBar progressBar2;
private String filepath = "MyFileStorage";
private File directory;
private TextView finished;
#Override
protected void onPause() {
super.onPause();
mStopped=true;
}
#Override
protected void onResume() {
super.onResume();
mStopped=false;
grabURL(url);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext());
directory = contextWrapper.getDir(filepath, Context.MODE_PRIVATE);
progressBar2 = (ProgressBar) findViewById(R.id.progressBar2);
progressBar2.setVisibility(View.GONE);
finished = (TextView) findViewById(R.id.textView1);
finished.setVisibility(View.GONE);
Button stop = (Button) findViewById(R.id.stop);
stop.setOnClickListener(this);
Button download = (Button) findViewById(R.id.download);
download.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.stop:
mStopped=true;
break;
case R.id.download:
mStopped=false;
grabURL(url);
break;
}
}
public void grabURL(String url) {
new GrabURL().execute(url);
}
private class GrabURL extends AsyncTask<String, Integer, String> {
protected void onPreExecute() {
progressBar2.setVisibility(View.VISIBLE);
progressBar2.setProgress(0);
finished.setVisibility(View.GONE);
}
protected String doInBackground(String... urls) {
String filename = "MySampleFile.png";
File myFile = new File(directory , filename);
try {
URL url = new URL(urls[0]);
URLConnection connection = url.openConnection();
if (myFile.exists())
{
connection.setAllowUserInteraction(true);
connection.setRequestProperty("Range", "bytes=" + myFile.length() + "-");
}
connection.connect();
int fileLength = connection.getContentLength();
fileLength += myFile.length();
InputStream is = new BufferedInputStream(connection.getInputStream());
RandomAccessFile os = new RandomAccessFile(myFile, "rw");
os.seek(myFile.length());
byte data[] = new byte[1024];
int count;
int __progress = 0;
while ((count = is.read(data)) != -1 && __progress != 100) {
if (mStopped) {
throw new IOException();
}
else{
__progress = (int) ((myFile.length() * 100) / fileLength);
publishProgress((int) (myFile.length() * 100 / fileLength));
os.write(data, 0, count);}
}
os.close();
is.close();
} catch (Exception e) {
e.printStackTrace();
}
return filename;
}
protected void onProgressUpdate(Integer... progress) {
finished.setVisibility(View.VISIBLE);
finished.setText(String.valueOf(progress[0]) + "%");
progressBar2.setProgress(progress[0]);
}
protected void onCancelled() {
Toast toast = Toast.makeText(getBaseContext(),
"Error connecting to Server", Toast.LENGTH_LONG);
toast.setGravity(Gravity.TOP, 25, 400);
toast.show();
}
protected void onPostExecute(String filename) {
progressBar2.setProgress(100);
finished.setVisibility(View.VISIBLE);
finished.setText("Download in progress..");
File myFile = new File(directory , filename);
ImageView myImage = (ImageView) findViewById(R.id.imageView1);
myImage.setImageBitmap(BitmapFactory.decodeFile(myFile.getAbsolutePath()));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
You seem to already have most of the code in place for the functionality. In onResume you can call your ASyncTask and it should start download if the file exists (paused download in onPause(), file exists). I have written similar code, you can find it here: https://github.com/hiemanshu/ContentDownloader/blob/master/src/com/example/contentdownloader/MainActivity.java
In my code you can find that instead of using onPause and onResume, I just have a wakelock for that period of time.
I am using an AsyncTask class to download images for my quiz application. This is the class:
public class DownloadImagesTask extends AsyncTask<ImageView, Void, Bitmap>{
ImageView imageView = null;
#Override
protected Bitmap doInBackground(ImageView... imageViews) {
this.imageView = imageViews[0];
return download_Image((String)imageView.getTag());
}
#Override
protected void onPostExecute(Bitmap result) {
// imageView.setImageBitmap(result);
downloaded_image = new BitmapDrawable(result);
//setting question image
question_view.setCompoundDrawablesWithIntrinsicBounds(null, null, null, downloaded_image);
}
private Bitmap download_Image(String url) {
//---------------------------------------------------
Bitmap bm = null;
try {
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
} catch (IOException e) {
Log.e("Hub","Error getting the image from server : " + e.getMessage().toString());
}
return bm;
//--------------------------------------------------
}
}
The image is getting downloaded and I am putting the image inside my Question TextView like this:
downloaded_image = new BitmapDrawable(result);
//setting question image
question_view.setCompoundDrawablesWithIntrinsicBounds(null, null, null, downloaded_image);
I am giving a call to this class from my activity like this:
//image download
String imageURL = "http://cache.daylife.com/imageserve/074efG3gPV4oK/50x50.jpg";
image_downloadView.setTag(imageURL);
new DownloadImagesTask().execute(image_downloadView);
I want to pass some extra parameters in order to identify whether I am downloading the image for the question or answer TextViews.
How do I achieve this?
Thanks in advance!
P.S.: I have one question and four options in the application for every set of question.
You can pass parameters to your AsyncTask Constructor.
DownLoadImagesTask dt= new DownLoadImagesTask("hello",1); //passing string and integer value
dt.execute(image_downloadView);
In asynctask
String s;
int value;
public DownLoadImagesTask(String string, int i) {
// TODO Auto-generated constructor stub
s=string;
value=1;
}
You can change the type of your first param to an Object (Or create a custom parameter class/hash - the best option) and pass multiple items to it.
ImageView imgView = (ImageView) findViewById(R.id.imageView1);
String param = "parameter";
MyAsyncTask task = new MyAsyncTask();
task.execute(param, imgView);
private class MyAsyncTask extends AsyncTask<Object, Void, Void> {
private String parameter;
private ImageView imgView;
#Override
protected Void doInBackground(Object... params) {
//Looping option
for (Object object : params) {
if (object instanceof String) {
this.parameter = (String) object;
//do_something
} else if (object instanceof ImageView) {
//do_something_else
}
}
//Direct access option
this.parameter = (String) params[0];
this.imgView = (ImageView) params[1];
return null;
}
}
In your case, you can pass a View
new DownloadImagesTask().execute(image_downloadView, question_resultView);
private class DownloadImagesTask extends AsyncTask<View, Void, Bitmap> {
TextView questionView = null;
ImageView imageView = null;
#Override
protected Bitmap doInBackground(View... views) {
for (View view : views) {
if (view instanceof ImageView) {
this.imageView = (ImageView) view;
} else if (view instanceof TextView) {
this.questionView = (TextView) view;
}
}
return download_Image((String)imageView.getTag());
}
#Override
protected void onPostExecute(Bitmap result) {
// imageView.setImageBitmap(result);
downloaded_image = new BitmapDrawable(result);
//setting question image
questionView.setCompoundDrawablesWithIntrinsicBounds(null, null, null, downloaded_image);
}
}
I am new to Android and trying to create my first app. It should have an ImageView along with two buttons (Back and Next). When the user clicks on the Next button, the image in the ImageView should be replaced with the next image (hosted on my server). The names of the files are 1.jpg, 2.jpg, 3.jpg... I am using the following code, but something is not working. When the Activity starts the first image is loaded properly, but when I click the Next button nothing happens (nothing in LogCat also).
public class slidesActivity extends Activity {
private ImageView imageView;
private int imageNumber = 1;
private String plakatiUrl = "http://plakati.bg/" +
Integer.toString(imageNumber) + ".jpg";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.slides);
final Drawable image = LoadImageFromWeb(plakatiUrl);
imageView = new ImageView(getBaseContext());
imageView = (ImageView) findViewById(R.id.imageView1);
imageView.setImageDrawable(image);
Button nextButton = (Button) findViewById(R.id.nextBtn);
nextButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
imageNumber++;
// Have to find why
imageView.setImageDrawable(image);
// is not working here
}
});
private Drawable LoadImageFromWeb(String url) {
try {
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
} catch (Exception e) {
System.out.println("Exc=" + e);
return null;
}
}
}
I know that I have to make this in a different thread, so I don't get a ANR, but still I am missing something here.
Could anyone help me with this, please !
This works for me. You can clean it up, though.
public class TestAppActivity extends Activity {
private ImageView imageView;
private int imageNumber = 1;
private String plakatiUrl = "http://plakati.bg/";
private Drawable image = null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.slides);
image = LoadImageFromWeb(generateUrlString(plakatiUrl, imageNumber));
imageView = new ImageView(getBaseContext());
imageView = (ImageView) findViewById(R.id.imageView1);
imageView.setImageDrawable(image);
Button nextButton = (Button) findViewById(R.id.nextBtn);
nextButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
imageNumber++;
image = LoadImageFromWeb(generateUrlString(plakatiUrl, imageNumber));
imageView.setImageDrawable(image);
}
});
}
private Drawable LoadImageFromWeb(String url) {
Drawable d = null;
InputStream is;
try {
is = (InputStream) new URL(url).getContent();
d = Drawable.createFromStream(is, "src name");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return d;
}
private String generateUrlString(String str, int n) {
return str + Integer.toString(n) + ".jpg";
}
}
Also, I recommend using Bitmap instead of Drawable. And, I've noticed you put the LoadImageFromWeb() method inside onCreate().
Your onClick() method reloads the same image every time it's tapped. You need to modify your image and its link. Change the LoadImageFromWeb(String) to
LoadImageFromWeb(String url, int imageNumber)
{
String plakatiUrl = url + Integer.toString(imageNumber) + ".jpg";
//...
}
And call it from the onClick() method.