I have some images in gridview. when i click on the image , the image will open in another activity. In that activity i had a save button. When the save button is clicked the image should download and save in sd card. Now my question how to download and save the image.
this is my code
Main activity.java
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.beaches);
GridView gridView = (GridView) findViewById(R.id.gridView1);
// Instance of ImageAdapter Class
gridView.setAdapter(new ImageAdapter(this));
/**
* On Click event for Single Gridview Item
* */
gridView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
// Sending image id to FullScreenActivity
Intent i = new Intent(getApplicationContext(), FullImageActivity.class);
// passing array index
i.putExtra("id", position);
startActivity(i);
}
});
Button home=(Button)findViewById(R.id.button1);
home.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
startActivity(new Intent(getApplicationContext(),MainActivity.class));
}
});
}
Fullimageactivity.java
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.beachfull);
// get intent data
Intent i = getIntent();
// Selected image id
int position = i.getExtras().getInt("id");
ImageAdapter imageAdapter = new ImageAdapter(this);
ImageView imageView = (ImageView) findViewById(R.id.full_image_view);
imageView.setImageResource(imageAdapter.images[position]);
Button dwnld = (Button)findViewById(R.id.download);
dwnld.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
}
}
The code below is to save ImageFile from a URL
private String path;
private Bitmap bmImg;
void downloadFile(String fileUrl, String fileName) {
// here you can add folder in which you want the image to be stored
path = sdCard.getAbsolutePath() ;
URL myFileUrl = null;
try {
myFileUrl = new URL(fileUrl);
HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
if (bmImg != null) {
bmImg.recycle();
}
bmImg = BitmapFactory.decodeStream(is);
FileOutputStream out = new FileOutputStream(path + "/" + fileName + ".jpg");
bmImg.compress(Bitmap.CompressFormat.JPEG, 50, out);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
// Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
Remember you also need permission for it in AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />