I am getting image from server and display it in my application,and I download that image and downloading is working fine,but when I check my gallery image is not showing there,then in dev tools-Media Scanner I scan my SD card and again check my gallery and then image is showing..so how can I solve it..even I tried it Samsung phone,but with device i need to reboot my device...following is my snippet code...
public class bBusinessCardDL extends Activity{
String[] NAMES = new String[1];
String[] CurID = new String[1];
String[] Detail = new String[1];
String[] Photo = new String[1];
ListView listview;
String BCard;
ImageView image;
Button btnDownload;
ProgressDialog mProgressDialog;
private String Id;
private ImageView bcks;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_bu_dl);
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + "/mnt/sdcard/")));
bcks=(ImageView)findViewById(R.id.bck_from_bcard);
bcks.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intss=new Intent(bBusinessCardDL.this,FirstPage.class);
startActivity(intss);
}
});
Id=this.getIntent().getStringExtra("userids");
System.out.println("checkd advertisement "+Id);
FillData();
btnDownload = (Button) findViewById(R.id.btnDownload);
btnDownload.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mDownloadAndSave();
Toast msgd = Toast.makeText(getBaseContext(),
"Business card Downloaded..!", Toast.LENGTH_LONG);
msgd.show();
}
});
}
public void mDownloadAndSave() {
File f = new File("/mnt/sdcard/" + Id
+ ".jpg");
//"/mnt/sdcard/"
InputStream is;
try {
is = new URL(BCard).openStream();
// Set up OutputStream to write data into image file.
OutputStream os = new FileOutputStream(f);
CopyStream(is, os);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
MediaScannerConnection.scanFile(this, new String[] { "ur_file_path" },
null,
new MediaScannerConnection.OnScanCompletedListener() {
#Override
public void onScanCompleted(String path, Uri uri) {
}
});
}
public static void CopyStream(InputStream is, OutputStream os) {
final int buffer_size = 2048;
try {
byte[] bytes = new byte[buffer_size];
for (;;) {
int count = is.read(bytes, 0, buffer_size);
if (count == -1)
break;
os.write(bytes, 0, count);
}
} catch (Exception ex) {
}
}
public static String getJsonFromServer(String url) throws IOException {
BufferedReader inputStream = null;
URL jsonUrl = new URL(url);
URLConnection dc = jsonUrl.openConnection();
dc.setConnectTimeout(5000);
dc.setReadTimeout(5000);
inputStream = new BufferedReader(new InputStreamReader(
dc.getInputStream()));
// read the JSON results into a string
String jsonResult = inputStream.readLine();
return jsonResult;
}
static class ViewHolder {
TextView VHName;
ImageView VHPhoto;
int position;
}
public void FillData() {
String url = "";
url = "http://www.asdffsfd.com/web-service/b_card.php?user_id="
+ Id;
String jsonString;
jsonString = "";
try {
jsonString = getJsonFromServer(url);
} catch (IOException e) {
}
BCard = "";
try {
JSONArray earthquakes = new JSONArray(jsonString);
NAMES = new String[earthquakes.length()];
Photo = new String[earthquakes.length()];
for (int i = 0; i < earthquakes.length(); i++) {
JSONObject e = earthquakes.getJSONObject(i);
NAMES[i] = e.getString("b_card");
BCard = "http://" + e.getString("b_card");
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
BCard = BCard.replace("\\", "");
BCard = BCard.replace(" ", "%20");
ImageView i = (ImageView) findViewById(R.id.BUCARD);
Log.d("Bcard", BCard);
try {
Bitmap bitmap = BitmapFactory.decodeStream((InputStream) new URL(
BCard).getContent());
i.setImageBitmap(bitmap);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
after save the image, use below code for scanning file:
MediaScannerConnection.scanFile(this, new String[] { f.getAbsolutePath()},
null,
new MediaScannerConnection.OnScanCompletedListener() {
#Override
public void onScanCompleted(String path, Uri uri) {
}
});
I'm having some troubles displaying an image I am fetching from a URL into an ImageView. With the code I have at the moment, I am getting absolutely nothing. Is there a problem with this code?
Drawable img = image.LoadImageFromWeb(icon);
imageView.setImageDrawable(img);
public static Drawable LoadImageFromWeb(String iconId) {
try {
String url = "http://ddragon.leagueoflegends.com/cdn/4.3.12/img/profileicon/" + iconId + ".png";
InputStream is = (InputStream) new URL(url).getContent();
Drawable icon = Drawable.createFromStream(is, "src name");
return icon;
} catch (Exception e) {
return null;
}
}
try this function
private void downloadImage()
{
Bitmap bitmap = null;
try {
URL urlImage = new
URL("http://ddragon.leagueoflegends.com/cdn/4.3.12/img/profileicon/" + iconId +
".png");
HttpURLConnection connection = (HttpURLConnection)
urlImage.openConnection();
InputStream inputStream = connection.getInputStream();
//****bitmap is your image*****
bitmap = BitmapFactory.decodeStream(inputStream);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
and use asyncTask to wait until downloading the image like this
private class Asyn_SaveData extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
//get the random string from prefs
if (context != null)
downloadImage();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
//do what you want after the image downloaded
}
}
Note: AsyncTask must be subClassed, and after the doInBackground finish its job it calls automatically the onPostExecute
i almost finished my app, im working on menu items now,
The problem is to set a bitmap as wallpaper and save it on sdcard from menu item.
i tried to things, 1st was to create a second intent which was taking -again- same data from previous activity , -I have failed-
2nd was using the same intent -i ve failed-
here is my code.
thank you
public class Fullpic extends Activity {
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// menu
getMenuInflater().inflate(R.layout.menu_pics, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.menu_set:
// setting as wallpaper
return true;
case R.id.menu_save:
// save the image on sdcard
return true;
case R.id.menu_back:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
//menu end
// XML node keys
static final String KEY_THUMB_URL = "source";
static final String HEIGHT_MAX = "600";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_pic);
// getting intent data
Intent in = getIntent();
// Get XML values from previous intent dude
String bid = in.getStringExtra(KEY_THUMB_URL);
int hoppa= Integer.parseInt(in.getStringExtra(HEIGHT_MAX));
// Displaying all values on the screen
ImageView balls = (ImageView) findViewById(R.id.bals_label);
balls.getLayoutParams().height = hoppa-30;
URL url = null;
try {
url = new URL(bid);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Bitmap bmp = null;
try {
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
balls.setImageBitmap(bmp);
}
public Object fetch(String address) throws MalformedURLException,
IOException {
URL url = new URL(address);
Object content = url.getContent();
return content;
}
private Drawable ImageOperations(Context ctx, String url) {
try {
InputStream is = (InputStream) this.fetch(url);
Drawable d = Drawable.createFromStream(is, "source");
return d;
} catch (MalformedURLException e) {
return null;
} catch (IOException e) {
return null;
}
}
}
new Thread(new Runnable(){
#Override
public void run(){
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/blabla");
myDir.mkdirs();
String fname = "name_here.jpg";
File file = new File (myDir, fname);
if (file.exists ())
file.delete ();
try {
FileOutputStream out = new FileOutputStream(file); //create stream to output the contents of the image
bmp.compress(Bitmap.CompressFormat.JPEG, 90, out); //compress and write bitmap data to output file stream
out.flush();
out.close(); //closes stream important to avoid memory leaks
} catch (Exception e) {
//exception handling
}
}}).start();
This should help you write the bitmap file to where you need it to be on the SD card of the device, and done in a thread to keep heavy actions off the main UI Thread. Cheers.
When i am scrolling the GridView the images disappear in it. In log Cat its also showing outofmemory i dont know what i am doing wrong here.! It takes long time to display the images also. Thanks in Advance.
BaseActivity.java
public class BaseActivity extends Activity{
private Context context = this;
boolean server_connection = false;
static final Comparator<HashMap<String, String>> byDate = new Comparator<HashMap<String, String>>() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public int compare(HashMap<String, String> ord1, HashMap<String, String> ord2) {
Date d1 = null;
Date d2 = null;
try {
if(ord1.get("datetime")!=null){
d1 = sdf.parse(ord1.get("datetime"));
}
else{
d1 = sdf.parse("1970-01-01 00:00:00");
}
if(ord2.get("datetime")!=null){
d2 = sdf.parse(ord2.get("datetime"));
}
else{
d2 = sdf.parse("1970-01-01 00:00:00");
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Log.d("Date", ""+d1+"..........."+d2);
return (d1.getTime() > d2.getTime() ? -1 : 1); //descending
// return (d1.getTime() > d2.getTime() ? 1 : -1); //ascending
}
};
static final Comparator<HashMap<String, String>> byCount = new Comparator<HashMap<String, String>>() {
public int compare(HashMap<String, String> ord1, HashMap<String, String> ord2) {
int c1,c2;
if(ord1.get("download_count")!=null && !ord1.get("download_count").equals("null")){
c1=Integer.parseInt(ord1.get("download_count"));
}
else{c1=0;}
if(ord2.get("download_count")!=null && !ord2.get("download_count").equals("null")){
c2=Integer.parseInt(ord2.get("download_count"));
}
else{c2=0;}
return (c1>c2 ? -1 : 1); //descending
}
};
public boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
public String prepareWebserviceRequest(String methodname, String[] keys, String[] values) throws JSONException{
String retStr = null;
String strParams = null;
JSONObject json = new JSONObject();
for(int i=0;i<keys.length;i++){
json.put(keys[i],values[i]);
}
JSONObject fJson = new JSONObject();
fJson.put("method_name", methodname);
fJson.put("body", json);
retStr = fJson.toString();
return retStr;
}
public String prepareWebserviceRequestOnlyMethod(String methodname) throws JSONException{
String retStr = null;
String strParams = null;
JSONObject json = new JSONObject();
JSONObject fJson = new JSONObject();
fJson.put("method_name", methodname);
// fJson.put("body", json);
retStr = fJson.toString();
return retStr;
}
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
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();
return null;
}
}
public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// CREATE A MATRIX FOR THE MANIPULATION
Matrix matrix = new Matrix();
// RESIZE THE BIT MAP
matrix.postScale(scaleWidth, scaleHeight);
// RECREATE THE NEW BITMAP
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
return resizedBitmap;
}
class Download extends AsyncTask<String, Void, Bitmap>{
#Override
protected Bitmap doInBackground(String... params) {
// TODO Auto-generated method stub
Bitmap bmp=null;
bmp = getBitmapFromURL(params[0]);
return bmp;
}
}
public void WriteFile(String path,String filename,String data) {
try{
File direct = new File(path);
if(!direct.exists())
{
direct.mkdir();//directory is created;
}
String fpath= path +filename;
File txtfile=new File(fpath);
txtfile.createNewFile();
FileOutputStream fout=new FileOutputStream(txtfile);
OutputStreamWriter myoutwriter=new OutputStreamWriter(fout);
myoutwriter.write(data);
myoutwriter.close();
fout.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public String ReadFile(String path,String filename)
{ File myFile = new File(path + filename);
if(!myFile.exists())
{
return null;
}
FileInputStream fIn = null;
try {
fIn = new FileInputStream(myFile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
String aDataRow = "";
String aBuffer = "";
try {
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return aBuffer;
}
public boolean FileExist(String filename)
{
String PATH2 = Environment.getExternalStorageDirectory() + "/"+Constant.Alert_Name+filename;
Log.v("log_tag initial path", "PATH: " + PATH2);
File file2 = new File(PATH2);
if(file2.exists()==true)
{
return true;
}
return false;
}
public String callAPI(String strRequest) {
String result = null;
String new_params;
int ResponseCode;
// TODO Auto-generated method stub
try {
JSONObject json = new JSONObject();
HttpParams httpParams = new BasicHttpParams();
httpParams.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
httpParams.setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, HTTP.UTF_8);
httpParams.setParameter(CoreProtocolPNames.USER_AGENT, "Apache-HttpClient/Android");
//httpParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 15000);
httpParams.setParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false);
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);
HttpClient client = new DefaultHttpClient(cm,httpParams);
String url = Constant.WebService_URL;
//String url = "http://192.168.1.3/messages_app/main.php";
URL url1 = new URL(Constant.WebService_URL);
// URL url1 = new URL("http://192.168.1.3/messages_app/main.php");
HttpPost request = new HttpPost(url);
request.setHeader("Content-Type", "application/x-www-form-urlencoded");
new_params =strRequest;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
//nameValuePairs.add(new BasicNameValuePair("json","{\"method_name\":\"get_all_category\"}"));
nameValuePairs.add(new BasicNameValuePair("json",new_params));
request.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// request.setEntity(new ByteArrayEntity(json.toString().getBytes("UTF8")));
request.setHeader("json", json.toString());
HttpResponse response = client.execute(request);
ResponseCode = response.getStatusLine().getStatusCode();
//Log.d("ResponseCode", ""+ResponseCode);
if(ResponseCode==200){
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
if (entity != null) {
InputStream instream = entity.getContent();
result = RestClient.convertStreamToString(instream);
// Log.i("Read from server", result);
}
}
else if(ResponseCode!=200){
return "Server down";
}
} catch (Throwable t) {
return null;
}
return result;
}
}
LazyAdapter.java
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private String data[];
private LayoutInflater inflater=null;
public ImageLoader imageLoader;
DisplayImageOptions options;
ArrayList<HashMap<String, String>> list;
public LazyAdapter(Activity a,ArrayList<HashMap<String, String>> list) {
this.list=list;
activity = a;
inflater = (LayoutInflater)LayoutInflater.from(a);
File cacheDir = StorageUtils.getOwnCacheDirectory(a, "Download");
// Get singletone instance of ImageLoader
imageLoader = ImageLoader.getInstance();
// Create configuration for ImageLoader (all options are optional)
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(a)
// You can pass your own memory cache implementation
.memoryCacheExtraOptions(480,800)
.denyCacheImageMultipleSizesInMemory()
.discCacheExtraOptions(480, 480, CompressFormat.PNG, 100)
.discCache(new UnlimitedDiscCache(cacheDir)) // You can pass your own disc cache
.discCacheFileNameGenerator(new HashCodeFileNameGenerator())
.enableLogging()
.build();
// Initialize ImageLoader with created configuration. Do it once.
imageLoader.init(config);
//imageLoader.init(ImageLoaderConfiguration.createDefault(a));
// imageLoader=new ImageLoader(activity.getApplicationContext());
options = new DisplayImageOptions.Builder()
.showStubImage(R.drawable.stub_image)
.cacheInMemory()
// .cacheOnDisc()
.displayer(new RoundedBitmapDisplayer(20))
.build();
}
public int getCount() {
return list.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder vh;
if(convertView==null)
{
vh = new ViewHolder();
convertView= inflater.inflate(R.layout.other, parent,false);
vh.iv=(ImageView)convertView.findViewById(R.id.picture);
vh.pb= (ProgressBar)convertView.findViewById(R.id.pb);
vh.tv = (TextView)convertView.findViewById(R.id.text);
convertView.setTag(vh);
} else {
vh = (ViewHolder) convertView.getTag();
}
// vh.tv.setText("Image in postion ="+position);
if(Global.getCurrent_tab()==1){
vh.tv.setText(""+list.get(position).get("download_count"));
}
display(vh.iv, Constant.img_URL+list.get(position).get("photo_name"), vh.pb);
return convertView;
}
public void display(ImageView img, String url, final ProgressBar pb)
{
imageLoader.displayImage(url, img, options, new ImageLoadingListener() {
#Override
public void onLoadingCancelled() {
// TODO Auto-generated method stub
}
#Override
public void onLoadingComplete(Bitmap arg0) {
// TODO Auto-generated method stub
pb.setVisibility(View.GONE);
}
#Override
public void onLoadingFailed(FailReason arg0) {
// TODO Auto-generated method stub
pb.setVisibility(View.GONE);
}
#Override
public void onLoadingStarted() {
// TODO Auto-generated method stub
pb.setVisibility(View.VISIBLE);
}
});
}
static class ViewHolder
{
ImageView iv;
TextView tv;
ProgressBar pb;
}
}
DefaultGridView.java
public class DefaultGridView extends Activity {
GridView gridView;
Context context=this;
DisplayImageOptions options;
protected ImageLoader imageLoader = ImageLoader.getInstance();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.latestphotos);
gridView = (GridView) findViewById(R.id.grid_view);
gridView.setAdapter(new LazyAdapter(DefaultGridView.this,Global.getPhotos_list()));
gridView.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
String url =Constant.img_URL+Global.getPhotos_list().get(position).get("photo_name");
Intent i = new Intent(DefaultGridView.this, FullImageActivity.class);
i.putExtra("idkey", url); // pass the id
startActivity(i);
}
});
}
}
FullImageActivity.java
public class FullImageActivity extends Activity {
Button download, setaswallpaper, reportissue;
String url1;
Bitmap myBitmap;
ImageDownloader mDownloader;
FileOutputStream fos;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.full_image);
setaswallpaper = (Button) findViewById(R.id.setaswallpaper);
download = (Button)findViewById(R.id.download);
reportissue = (Button)findViewById(R.id.reportissue);
final ImageView imageView = (ImageView) findViewById(R.id.full_image_view);
url1 = getIntent().getStringExtra("idkey"); //get id
Log.i(".............",""+url1);
//imageView.setImageResource(id);
new Thread( new Runnable()
{
#Override
public void run() {
// TODO Auto-generated method stub
try
{
URL url = new URL(url1.toString());
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
myBitmap = BitmapFactory.decodeStream(input);
}
catch(Exception e)
{
e.printStackTrace();
}
runOnUiThread( new Runnable()
{
#Override
public void run() {
// TODO Auto-generated method stub
imageView.setImageBitmap(myBitmap);
}
});
}
}).start();
setaswallpaper.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
WallpaperManager myWallpaperManager
= WallpaperManager.getInstance(getApplicationContext());
try {
myWallpaperManager.setBitmap(myBitmap);
Toast.makeText(getApplicationContext(), "Wallpaper has been set...!!", Toast.LENGTH_LONG).show();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
download.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
saveImageToSD();
// Toast.makeText(getApplicationContext(), "Wallpaper has been Downloaded...!!", Toast.LENGTH_LONG).show();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
reportissue.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_SENDTO); // it's not ACTION_SEND
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, "Report Issue");
intent.putExtra(Intent.EXTRA_TEXT, "Body of email");
intent.setData(Uri.parse("mailto:reportissue#gmail.com")); // or just "mailto:" for blank
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // this will make such that when user returns to your app, your app is displayed, instead of the email app.
startActivity(intent);
}
});
}
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 ---*/
myBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
/*--- create a new file on SD card ---*/
long current = System.currentTimeMillis();
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator + (current / 1000) + "wallpaper.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();
Toast.makeText(this, "Image saved", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
}
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().