My wallpaper manager uses a Async Task to set as wallpaper. But after changing to AsyncTask from non-Async I got the error "The method getBaseContext() is undefined for the type SetWallpaperTask" Please correct my codes. Thank you very much.
Old Non-AsyncTask
public void SetWallpaper(String image_url)
{
URL myFileUrl = null;
try
{
myFileUrl = new URL(image_url);
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
Bitmap bmImg = null;
try {
HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
//int length = conn.getContentLength();
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
}
catch (IOException e)
{
e.printStackTrace();
}
try {
String path = myFileUrl.getPath();
String idStr = path.substring(path.lastIndexOf('/') + 1);
File filepath = Environment.getExternalStorageDirectory();
File dir = new File (filepath.getAbsolutePath() + "/Wallpaper/");
dir.mkdirs();
String fileName = idStr;
File file = new File(dir, fileName);
FileOutputStream fos = new FileOutputStream(file);
bmImg.compress(CompressFormat.JPEG, 75, fos);
fos.flush();
fos.close();
WallpaperManager wpm = WallpaperManager.getInstance(getBaseContext());
wpm.setBitmap(bmImg);
}
catch (Exception e){
e.printStackTrace();
}
}
New AsyncTask
public class SetWallpaperTask extends AsyncTask<String , String , String>
{
private Context context;
private ProgressDialog pDialog;
String image_url;
URL myFileUrl;
String myFileUrl1;
Bitmap bmImg = null;
public SetWallpaperTask(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setMessage("Downloading Image ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
try {
myFileUrl = new URL(args[0]);
//myFileUrl1 = args[0];
HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
}
catch (IOException e)
{
e.printStackTrace();
}
try {
String path = myFileUrl.getPath();
String idStr = path.substring(path.lastIndexOf('/') + 1);
File filepath = Environment.getExternalStorageDirectory();
File dir = new File (filepath.getAbsolutePath() + "/Wallpaper/");
dir.mkdirs();
String fileName = idStr;
File file = new File(dir, fileName);
FileOutputStream fos = new FileOutputStream(file);
bmImg.compress(CompressFormat.JPEG, 75, fos);
fos.flush();
fos.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String args) {
// TODO Auto-generated method stub
WallpaperManager wpm = WallpaperManager.getInstance(context()); // --The method context() is undefined for the type SetWallpaperTask
wpm.setBitmap(bmImg);
pDialog.dismiss();
}
}
This is because you cannot get a Context inside an AsyncTask using getBaseContext().
I see that you're already receiving a Context in your constructor and storing it in the class variable context. So you can simply change
WallpaperManager wpm = WallpaperManager.getInstance(getBaseContext());
to
WallpaperManager wpm = WallpaperManager.getInstance(context);
Pass your activity context to this AsynTask, and use that context in your onPostExecute().
Related
I am working on an app in which I save image(s) to a directory but the Images wont show up in gallery until I restart the phone.
Here's My Code Snippet
public class SaveTask extends AsyncTask<String , String , String>
{
private Context context;
private ProgressDialog pDialog;
String image_url;
URL myFileUrl;
String myFileUrl1;
Bitmap bmImg = null;
File file ;
public SaveTask(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setMessage("Downloading Image ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
try {
myFileUrl = new URL(args[0]);
//myFileUrl1 = args[0];
HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
}
catch (IOException e)
{
e.printStackTrace();
}
try {
String path = myFileUrl.getPath();
String idStr = path.substring(path.lastIndexOf('/') + 1);
File filepath = Environment.getExternalStorageDirectory();
File dir = new File (filepath.getAbsolutePath() + "/mydownloaddir/");
dir.mkdirs();
String fileName = idStr;
file = new File(dir, fileName);
FileOutputStream fos = new FileOutputStream(file);
bmImg.compress(CompressFormat.JPEG, 75, fos);
fos.flush();
fos.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String args) {
// TODO Auto-generated method stub
Toast.makeText(SlideImageActivity.this, "Image Saved Succesfully to Folder 'mydownloaddir'", Toast.LENGTH_SHORT).show();
pDialog.dismiss();
}
}
What code should I use next to make the Images showup in gallery using medisscanner
I got something like this on here But unable to use it properly:
MediaScannerConnection.scanFile(ApplicationContext.context, new String[] { imageFile.getPath() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
#Override
public void onScanCompleted(String path, Uri uri) {
Log.i(TAG, "Scanned " + path);
}
});
Please Help
Use
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"
+ Environment.getExternalStorageDirectory())));
//but it only works on API <19
Second Method
private void scanFile(String path) {
MediaScannerConnection.scanFile(MainActivity.this,
new String[] { path }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("TAG", "Finished scanning " + path);
}
});
}
Call it like
scanFile(yourFile.getAbsolutePath());
Also see this Answer
this is my code to download a file and save it in the internal storage:
public class getResults extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params){
String fileName = "results"+month+year+".pdf";
URLConnection conn;
try {
URL url = new URL(params[0]);
conn = url.openConnection();
int contentLength = conn.getContentLength();
DataInputStream in = new DataInputStream(conn.getInputStream());
byte[] buffer = new byte[contentLength];
in.readFully(buffer);
in.close();
if (buffer.length > 0) {
DataOutputStream out;
FileOutputStream fos = openFileOutput(fileName,Context.MODE_PRIVATE);
out = new DataOutputStream(fos);
out.write(buffer);
out.flush();
out.close();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "true";
}
protected void onPostExecute(String result){
}
}
but how I have to change the code, so that I save the file on External Storage and app-private?
Use FileOutputStream fos = new FileOutputStream(getExternalFilesDir() + "/" + fileName); But this is not private memory.
How do you implement Progress Download Dialog based on the codes below? My codes downloads images from a specific URL then it saves the image file into SD Card and set the image as wallpaper. I want to show a Progress Download Dialog when the user touches the options menu button setwallpaper().
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.set_wallpaper:
SetWallpaper(image_url);
return true;
default:
return false;
}
}
public void SetWallpaper(String image_url)
{
URL myFileUrl = null;
try
{
myFileUrl = new URL(image_url);
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
Bitmap bmImg = null;
try {
HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
//int length = conn.getContentLength();
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
}
catch (IOException e)
{
e.printStackTrace();
}
try {
String path = myFileUrl.getPath();
String idStr = path.substring(path.lastIndexOf('/') + 1);
File filepath = Environment.getExternalStorageDirectory();
File dir = new File (filepath.getAbsolutePath() + "/Wallpaper/");
dir.mkdirs();
String fileName = idStr;
File file = new File(dir, fileName);
FileOutputStream fos = new FileOutputStream(file);
bmImg.compress(CompressFormat.JPEG, 75, fos);
fos.flush();
fos.close();
WallpaperManager wpm = WallpaperManager.getInstance(getBaseContext());
wpm.setBitmap(bmImg);
}
catch (Exception e){
e.printStackTrace();
}
}
My attempt : Caught Exception . Please refer below codes
public class SingleMenuItemActivity extends Activity {
// XML node keys
static final String KEY_TITLE = "title";
static final String KEY_ARTIST = "artist";
static final String KEY_THUMB_URL = "thumb_url";
ProgressBar progressbar;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single_list_item);
ImageView image = (ImageView) findViewById(R.id.single_image);
Intent in = getIntent();
String image_url = in.getStringExtra(KEY_THUMB_URL);
ImageLoader imgLoader = new ImageLoader(getApplicationContext());
imgLoader.DisplayImage(image_url, image);
String title = in.getStringExtra(KEY_TITLE);
String artist = in.getStringExtra(KEY_ARTIST);
TextView lblName = (TextView) findViewById(R.id.name_title);
TextView lblCost = (TextView) findViewById(R.id.name_artist);
progressbar = (ProgressBar) findViewById(R.id.loadingBar);
lblName.setText(title);
lblCost.setText(artist);
}
public class loadImageTask extends AsyncTask<String, Void, Void>
{
//Drawable imgLoad;
URL myFileUrl = null;
Bitmap bmImg = null;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
Intent in = getIntent();
String image_url = in.getStringExtra(KEY_THUMB_URL);
try {
myFileUrl = new URL(image_url);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
super.onPreExecute();
progressbar.setVisibility(View.VISIBLE);
}
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
try {
HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
}
catch (IOException e)
{
e.printStackTrace();
}
try {
String path = myFileUrl.getPath();
String idStr = path.substring(path.lastIndexOf('/') + 1);
File filepath = Environment.getExternalStorageDirectory();
File dir = new File (filepath.getAbsolutePath() + "/Wallpaper/");
dir.mkdirs();
String fileName = idStr;
File file = new File(dir, fileName);
FileOutputStream fos = new FileOutputStream(file);
bmImg.compress(CompressFormat.JPEG, 75, fos);
fos.flush();
fos.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if(progressbar.isShown())
{
progressbar.setVisibility(View.GONE);
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent in = getIntent();
String image_url = in.getStringExtra(KEY_THUMB_URL);
switch (item.getItemId()) {
case R.id.save_image:
new loadImageTask().execute(image_url);
return true;
default:
return false;
}
Here you can use the AsyncTask for the show the progressbar/dialogbox .
Show the progress bar visible inside the onPreExecute() method. And performs the image loading operations inside the doInBackground() method. Once this operation is done, we will make progress bar invisible and make imageview visible with that loaded image inside the onPostExecute() method.
For more information check this LINK
Try using this
final ProgressDialog dialog = ProgressDialog.show(
YourACtivity.this, "", "Loading...please wait");
new Thread(new Runnable() {
#Override
public void run() {
SetWallpaper(image_url);
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
}
}).start();
}
instead of
SetWallpaper(image_url);
in the onOptionsItemSelected(MenuItem item)
and next use Handlers to handle http://developer.android.com/reference/android/os/Handler.html
In my activity, I am downloading images from url. I want these images to be downloaded only for the first time. Later on when I visit this page, it should take the image from the sdcard. How can I do that? Can anyone help?
In manifest I have set permission:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
The method which I use for downloading is:
public static Bitmap downloadFileFromUrl(String fileUrl){
URL myFileUrl =null;
Bitmap imageBitmap = null;
try {
myFileUrl= new URL(fileUrl);
}
catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection connection= (HttpURLConnection)myFileUrl.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream is = connection.getInputStream();
imageBitmap = BitmapFactory.decodeStream(is);
//Below two lines I just tried out for saving to sd card.
FileOutputStream out = new FileOutputStream(fileUrl);
imageBitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
}
catch (IOException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
return imageBitmap;
}
Try this method
public void DownloadImage(String imageUrl)
{
InputStream is = null;
if((imageUrl == null) || (imageUrl.length() == 0) || (imageUrl == " "))
{
System.out.println("No need to download images now");
}
else
{
System.gc();
String[] items;
String ImageName = null;
URL myFileUrl =null;
Bitmap bmImg = null;
String path = IMAGE_DOWNLOAD_PATH;
FileOutputStream outStream = null;
File file = new File(path);
if(!file.exists())
{
file.mkdirs();
}
File outputFile;
BufferedOutputStream bos;
try {
myFileUrl= new URL(imageUrl.trim());
HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection();
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setConnectTimeout(20000);
conn.connect();
is = conn.getInputStream();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ImageName = getImageName(imageUrl);
try {
outputFile = new File(file, ImageName);
if(outputFile.exists())
{
System.out.println("No need to download image it already exist");
outputFile.delete();
}
outputFile.createNewFile();
outStream = new FileOutputStream(outputFile);
//bos = new BufferedOutputStream(outStream);
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1)
{
baf.append((byte) current);
}
outStream.write(baf.toByteArray());
outStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
and then to retrieve image from sdcard,
File extStore = Environment.getExternalStorageDirectory();
String file_path = "/(folder name)/"+"(image name)".trim()+".extension".trim();
String mypath = extStore + file_path;
Bitmap bmp=BitmapFactory.decodeFile(mypath);
ImageView image = (ImageView) v.findViewById(R.id.image);
image.setImageBitmap(bmp);
You should store somewhere what you've got in cache.
Or if your filename are unique you've to check than the file exist or not.
You have to write the data got from InputStream to specified SD card location ..
This question already has answers here:
Write to /res/drawable/ on the fly?
(3 answers)
Closed 9 years ago.
I want to save image into my local drive folder or to res/drawable folder in my application. I'm right now saving img into sd card but I've to save it in res/drawable folder.
My code is:
String image_URL = "http://chart.apis.google.com/chart?chs=200x200&cht=qr&chl=http%3A%2F%2Fandroid-er.blogspot.com%2F";
String extStorageDirectory;
Bitmap bm;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button buttonSave = (Button) findViewById(R.id.save);
ImageView bmImage = (ImageView) findViewById(R.id.image);
BitmapFactory.Options bmOptions;
bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
bm = LoadImage(image_URL, bmOptions);
bmImage.setImageBitmap(bm);
extStorageDirectory = Environment.getExternalStorageState().toString();
extStorageDirectory = Environment.getExternalStorageDirectory()
.toString();
buttonSave.setText("Save to " + extStorageDirectory + "/qr.PNG");
buttonSave.setOnClickListener(buttonSaveOnClickListener);
}
private Bitmap LoadImage(String URL, BitmapFactory.Options options) {
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in, null, options);
in.close();
} catch (IOException e1) {
}
return bitmap;
}
private InputStream OpenHttpConnection(String strURL) throws IOException {
InputStream inputStream = null;
URL url = new URL(strURL);
URLConnection conn = url.openConnection();
try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setRequestMethod("GET");
httpConn.connect();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputStream = httpConn.getInputStream();
}
} catch (Exception ex) {
}
return inputStream;
}
Button.OnClickListener buttonSaveOnClickListener = new Button.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
OutputStream outStream = null;
File file = new File(extStorageDirectory, "er.PNG");
try {
outStream = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
Toast.makeText(LoadSaveImgActivity.this, "Saved",
Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(LoadSaveImgActivity.this, e.toString(),
Toast.LENGTH_LONG).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(LoadSaveImgActivity.this, e.toString(),
Toast.LENGTH_LONG).show();
}
}
};
Its not possible.
The following link can be helpful
Write to /res/drawable/ on the fly?
It is not possible to save anything into res/drawable at runtime, sorry.
You can't modify neither res/drawable, nor any other folder of your apk at runtime. It is build at compile-time and nothing can modify it from inside the application after.