I am getting the Image URL and set that URL in GridView.it shows me Successfully in Gridview.But I also want to Store That Images in SDCard Using Service.How to do That.Please Someone Help me for my this Issue.Thank You.
public class MainActivity extends Activity {
ListView list;
GridView gv;
String TAG = "GRIDVIEW";
LazyAdapter adapter;
Bitmap bitmap;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(this, MyService.class));
new loading().execute();
// gv = (GridView) findViewById(R.id.grid_view);
// startService(new Intent(MainActivity.this, MyService.class));
// gv = (GridView) findViewById(R.id.grid_view);
// gv.setAdapter(new LazyAdapter(MainActivity.this, mStrings));
// gv.setHorizontalSpacing(10);
// gv.setVerticalSpacing(40);
// gv.setGravity(200);
}
ProgressDialog mprogress;
private class loading extends AsyncTask<String, Void, String> {
protected void onPreExecute() {
mprogress = new ProgressDialog(MainActivity.this);
mprogress.setMessage("Loading...");
mprogress.show();
super.onPreExecute();
}
protected String doInBackground(String... params) {
// startService(new Intent(MainActivity.this, MyService.class));
return null;
}
protected void onPostExecute(String result) {
getGirdview();
mprogress.dismiss();
super.onPostExecute(result);
}
private void getGirdview() {
gv = (GridView) findViewById(R.id.grid_view);
gv.setAdapter(new LazyAdapter(MainActivity.this, mStrings));
gv.setHorizontalSpacing(10);
gv.setVerticalSpacing(40);
}
}
public String[] mStrings = {
"http://a1.twimg.com/profile_images/97470808/icon_normal.png",
"http://a3.twimg.com/profile_images/511790713/AG.png",
};
}
public class MyService extends Service {
String TAG = "GRIDVIEW";
Bitmap bitmap;
MainActivity mclass = new MainActivity();
public void onStart(Intent intent, int startId) {
for (int i = 0; i < mclass.mStrings.length; i++) {
String str = mclass.mStrings[i];
bitmap = DownloadImage(str);
// Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
// R.drawable.ic_launcher);
// File sd = Environment.getExternalStorageDirectory();
File storagePath = new File(
Environment.getExternalStorageDirectory(), "Wallpaper");
storagePath.mkdirs();
String fileName = "test" + i + ".png";
File dest = new File(storagePath, fileName);
try {
FileOutputStream out;
out = new FileOutputStream(dest);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
super.onStart(intent, startId);
}
public int onStartCommand(Intent intent, int flags, int startId) {
// for (int i = 0; i < mStrings.length; i++) {
//
// String str = mStrings[i];
// bitmap = DownloadImage(str);
// // Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
// // R.drawable.ic_launcher);
// // File sd = Environment.getExternalStorageDirectory();
// File storagePath = new File(
// Environment.getExternalStorageDirectory(), "Wallpaper");
// storagePath.mkdirs();
//
// String fileName = "test" + i + ".png";
// File dest = new File(storagePath, fileName);
// try {
// FileOutputStream out;
// out = new FileOutputStream(dest);
// bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
// out.flush();
// out.close();
// } catch (FileNotFoundException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
return super.onStartCommand(intent, flags, startId);
}
public IBinder onBind(Intent intent) {
return null;
}
// public void onStart(Intent intent, int startId) {
//
// for (int i = 0; i < mStrings.length; i++) {
//
// String str = mStrings[i];
// bitmap = DownloadImage(str);
// // Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
// // R.drawable.ic_launcher);
// // File sd = Environment.getExternalStorageDirectory();
// File storagePath = new File(
// Environment.getExternalStorageDirectory(), "Wallpaper");
// storagePath.mkdirs();
//
// String fileName = "test" + i + ".png";
// File dest = new File(storagePath, fileName);
// try {
// FileOutputStream out;
// out = new FileOutputStream(dest);
// bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
// out.flush();
// out.close();
// } catch (FileNotFoundException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
// super.onStart(intent, startId);
// }
private InputStream OpenHttpConnection(String urlString) throws IOException {
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
} catch (Exception ex) {
throw new IOException("Error connecting");
}
return in;
}
private Bitmap DownloadImage(String URL) {
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in);
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Toast.makeText(MyService.this, "Image is Downloaded",
Toast.LENGTH_SHORT).show();
return bitmap;
}
public class ImageLoader {
MemoryCache memoryCache = new MemoryCache();
FileCache fileCache;
private Map<ImageView, String> imageViews = Collections
.synchronizedMap(new WeakHashMap<ImageView, String>());
ExecutorService executorService;
public ImageLoader(Context context) {
fileCache = new FileCache(context);
executorService = Executors.newFixedThreadPool(5);
}
final int stub_id = R.drawable.ic_launcher;
public void DisplayImage(String url, ImageView imageView) {
imageViews.put(imageView, url);
Bitmap bitmap = memoryCache.get(url);
if (bitmap != null)
imageView.setImageBitmap(bitmap);
else {
queuePhoto(url, imageView);
imageView.setImageResource(stub_id);
}
}
private void queuePhoto(String url, ImageView imageView) {
PhotoToLoad p = new PhotoToLoad(url, imageView);
executorService.submit(new PhotosLoader(p));
}
private Bitmap getBitmap(String url) {
File f = fileCache.getFile(url);
// from SD cache
Bitmap b = decodeFile(f);
if (b != null)
return b;
// from web
try {
Bitmap bitmap = null;
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) imageUrl
.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is = conn.getInputStream();
OutputStream os = new FileOutputStream(f);
Utils.CopyStream(is, os);
os.close();
bitmap = decodeFile(f);
return bitmap;
} catch (Throwable ex) {
ex.printStackTrace();
if (ex instanceof OutOfMemoryError)
memoryCache.clear();
return null;
}
}
// decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f) {
try {
// decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
FileInputStream stream1 = new FileInputStream(f);
BitmapFactory.decodeStream(stream1, null, o);
stream1.close();
// Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE = 70;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE
|| height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
FileInputStream stream2 = new FileInputStream(f);
Bitmap bitmap = BitmapFactory.decodeStream(stream2, null, o2);
stream2.close();
return bitmap;
} catch (FileNotFoundException e) {
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
// Task for the queue
private class PhotoToLoad {
public String url;
public ImageView imageView;
public PhotoToLoad(String u, ImageView i) {
url = u;
imageView = i;
}
}
class PhotosLoader implements Runnable {
PhotoToLoad photoToLoad;
PhotosLoader(PhotoToLoad photoToLoad) {
this.photoToLoad = photoToLoad;
}
#Override
public void run() {
try {
if (imageViewReused(photoToLoad))
return;
Bitmap bmp = getBitmap(photoToLoad.url);
memoryCache.put(photoToLoad.url, bmp);
if (imageViewReused(photoToLoad))
return;
BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
Activity a = (Activity) photoToLoad.imageView.getContext();
a.runOnUiThread(bd);
} catch (Throwable th) {
th.printStackTrace();
}
}
}
boolean imageViewReused(PhotoToLoad photoToLoad) {
String tag = imageViews.get(photoToLoad.imageView);
if (tag == null || !tag.equals(photoToLoad.url))
return true;
return false;
}
// Used to display bitmap in the UI thread
class BitmapDisplayer implements Runnable {
Bitmap bitmap;
PhotoToLoad photoToLoad;
public BitmapDisplayer(Bitmap b, PhotoToLoad p) {
bitmap = b;
photoToLoad = p;
}
public void run() {
if (imageViewReused(photoToLoad))
return;
if (bitmap != null)
photoToLoad.imageView.setImageBitmap(bitmap);
else
photoToLoad.imageView.setImageResource(stub_id);
}
}
public void clearCache() {
memoryCache.clear();
fileCache.clear();
}
}
public class LazyAdapter extends BaseAdapter {
private Context mContext;
String TAG = "GridView";
private Activity activity;
private String[] data;
private static LayoutInflater inflater = null;
public ImageLoader imageLoader;
Bitmap bitmap;
public LazyAdapter(Activity a, String[] d) {
activity = a;
data = d;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return data.length;
}
public Object getItem(int position) {
return data;
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.item, null);
}
// TextView txt_name = (TextView) convertView.findViewById(R.id.text);
// txt_name.setText("item" + position);
ImageView image = (ImageView) convertView.findViewById(R.id.image);
// image.setTag(data[position]);
imageLoader.DisplayImage(data[position], image);
return convertView;
}
}
Environment.getExternalStorage() will return the sd card location. Once you get the location, you can create directories as needed. Looks like you are doing it....so what is the issue that you are running into?
Also, use IntentService rather than a service......it takes care of most of the plumbing work for you.
Related
I have build an app. I use bitmaps to get images from Instagram API and stora them in a GridView.
But I've a problem, when I use bitmaps and memory cache.
My code is:
public void DisplayImage(String urrl, ImageView imageView) {
String url = urrl.replaceAll(" ", "%20");
imageViews.put(imageView, url);
Bitmap bitmap = memoryCache.get(url);
if (bitmap != null)
imageView.setImageBitmap(bitmap);
else {
queuePhoto(url, imageView);
imageView.setImageResource(stub_id);
}
}
The variable bitmap returns null, from method memoryCache.get(url):
public Bitmap get(String id){
try{
if(!cache.containsKey(id)) {
return null; }else {
return cache.get(id); }
}catch(NullPointerException ex){
ex.printStackTrace();
return null;
}
}
I tried some solutions, but with no success.
I saw other solutions for similar problems, but neither can solve mine.
I'm new to bitmaps, and this kind of stuff.
EDIT
public class MemoryCache {
private static final String TAG = "MemoryCache";
private Map<String, Bitmap> cache= Collections.synchronizedMap(
new LinkedHashMap<String, Bitmap>(10,1.5f,true));//Last argument true for LRU ordering
private long size=0;//current allocated size
private long limit=1000000;//max memory in bytes
public MemoryCache(){
//use 25% of available heap size
setLimit(Runtime.getRuntime().maxMemory()/4);
}
public void setLimit(long new_limit){
limit=new_limit;
Log.i(TAG, "MemoryCache will use up to "+limit/1024./1024.+"MB");
}
public Bitmap get(String id){
try{
if(!cache.containsKey(id)) {
return null; }else {
//NullPointerException sometimes happen here http://code.google.com/p/osmdroid/issues/detail?id=78
return cache.get(id); }
}catch(NullPointerException ex){
ex.printStackTrace();
return null;
}
}
public void put(String id, Bitmap bitmap){
try{
if(cache.containsKey(id))
size-=getSizeInBytes(cache.get(id));
cache.put(id, bitmap);
size+=getSizeInBytes(bitmap);
checkSize();
}catch(Throwable th){
th.printStackTrace();
}
}
private void checkSize() {
Log.i(TAG, "cache size="+size+" length="+cache.size());
if(size>limit){
Iterator<Map.Entry<String, Bitmap>> iter=cache.entrySet().iterator();//least recently accessed item will be the first one iterated
while(iter.hasNext()){
Map.Entry<String, Bitmap> entry=iter.next();
size-=getSizeInBytes(entry.getValue());
iter.remove();
if(size<=limit)
break;
}
Log.i(TAG, "Clean cache. New size "+cache.size());
}
}
public void clear() {
try{
//NullPointerException sometimes happen here http://code.google.com/p/osmdroid/issues/detail?id=78
cache.clear();
size=0;
}catch(NullPointerException ex){
ex.printStackTrace();
}
}
long getSizeInBytes(Bitmap bitmap) {
if(bitmap==null)
return 0;
return bitmap.getRowBytes() * bitmap.getHeight();
}
}
ImageLoader:
public class ImageLoader {
MemoryCache memoryCache = new MemoryCache();
FileCache fileCache;
private Map<ImageView, String> imageViews = Collections
.synchronizedMap(new WeakHashMap<ImageView, String>());
ExecutorService executorService;
Handler handler = new Handler();// handler to display images in UI thread
public ImageLoader(Context context) {
fileCache = new FileCache(context);
executorService = Executors.newFixedThreadPool(5);
}
final int stub_id = R.drawable.crayon;
public void DisplayImage(String urrl, ImageView imageView) {
String url = urrl.replaceAll(" ", "%20");
imageViews.put(imageView, url);
Bitmap bitmap = memoryCache.get(url);
if (bitmap != null)
imageView.setImageBitmap(bitmap);
else {
queuePhoto(url, imageView);
imageView.setImageResource(stub_id);
}
}
private void queuePhoto(String url, ImageView imageView) {
PhotoToLoad p = new PhotoToLoad(url, imageView);
executorService.submit(new PhotosLoader(p));
}
private Bitmap getBitmap(String url) {
File f = fileCache.getFile(url);
// from SD cache
Bitmap b = decodeFile(f);
if (b != null)
return b;
// from web
try {
Bitmap bitmap = null;
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) imageUrl
.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is = conn.getInputStream();
OutputStream os = new FileOutputStream(f);
Utils.CopyStream(is, os);
os.close();
conn.disconnect();
bitmap = decodeFile(f);
return bitmap;
} catch (Throwable ex) {
ex.printStackTrace();
if (ex instanceof OutOfMemoryError)
memoryCache.clear();
return null;
}
}
// decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f) {
try {
// decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
FileInputStream stream1 = new FileInputStream(f);
BitmapFactory.decodeStream(stream1, null, o);
stream1.close();
// Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE = 70;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE
|| height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
FileInputStream stream2 = new FileInputStream(f);
Bitmap bitmap = BitmapFactory.decodeStream(stream2, null, o2);
stream2.close();
return bitmap;
} catch (FileNotFoundException e) {
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
// Task for the queue
private class PhotoToLoad {
public String url;
public ImageView imageView;
public PhotoToLoad(String u, ImageView i) {
url = u;
imageView = i;
}
}
class PhotosLoader implements Runnable {
PhotoToLoad photoToLoad;
PhotosLoader(PhotoToLoad photoToLoad) {
this.photoToLoad = photoToLoad;
}
#Override
public void run() {
try {
if (imageViewReused(photoToLoad))
return;
Bitmap bmp = getBitmap(photoToLoad.url);
memoryCache.put(photoToLoad.url, bmp);
if (imageViewReused(photoToLoad))
return;
BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
handler.post(bd);
} catch (Throwable th) {
th.printStackTrace();
}
}
}
boolean imageViewReused(PhotoToLoad photoToLoad) {
String tag = imageViews.get(photoToLoad.imageView);
if (tag == null || !tag.equals(photoToLoad.url))
return true;
return false;
}
// Used to display bitmap in the UI thread
class BitmapDisplayer implements Runnable {
Bitmap bitmap;
PhotoToLoad photoToLoad;
public BitmapDisplayer(Bitmap b, PhotoToLoad p) {
bitmap = b;
photoToLoad = p;
}
public void run() {
if (imageViewReused(photoToLoad))
return;
if (bitmap != null)
photoToLoad.imageView.setImageBitmap(bitmap);
else
photoToLoad.imageView.setImageResource(stub_id);
}
}
public void clearCache() {
memoryCache.clear();
fileCache.clear();
}
}
SOLUTION
In class MyGridView, i used Glide like Shmuel send on link!
View view = inflater.inflate(R.layout.medialist_inflate, null);
imgView = (ImageView) view.findViewById(R.id.ivImage);
Glide.with(context).load(imageThumbList.get(position)).into(imgView);
return view;
For loading images from a web url the best practice approach is the use the Glide image loading library.
https://github.com/bumptech/glide
It is an open source image loading library that is recommend and supported by Google.
The api looks like this -
Glide
.with(context)
.load(url)
.centerCrop()
.placeholder(R.drawable.loading_spinner)
.crossFade()
.into(myImageView);
See how easy that is :D
It automatically handles caching the images (both in memory and to disk).
I'm trying to add a font to a textView. I have the following code-snippet, but I'm not sure how to adapt it to my code below. Can someone help me?
Code snippet I want to integrate into my program:
Typeface myTypeface = Typeface.createFromAsset(getAssets(), "fonts/Xcelsion.ttf"); // getActivity().getAssets()
TextView myTextView = (TextView)findViewById(R.id.text_view);
myTextView.setTypeface(myTypeface); //
Program I want to add the font to:
public class ListRingtonesAdapter extends ArrayAdapter<SongInfo> {
private ArrayList<SongInfo> items;
private Context context;
private ArrayList<ViewHolder> listHolder = new ArrayList<ListRingtonesAdapter.ViewHolder>();
private int curPosition = 0;
private RingtonesSharedPreferences pref;
private boolean inRingtones;
static final String TAG = "LOG";
private static final int DEFAULT_RINGTONE = 1;
private static final int ASSIGN_TO_CONTACT = 2;
private static final int DEFAULT_NOTIFICATION = 3;
private static final int DEFAULT_ALARM = 4;
private static final int DELETE_RINGTONE = 5;
public static final String ALARM_PATH = "/media/audio/alarms/";
public static final String ALARM_TYPE = "Alarm";
public static final String NOTIFICATION_PATH = "/media/audio/notifications/";
public static final String NOTIFICATION_TYPE = "Notification";
public static final String RINGTONE_PATH = "/media/audio/ringtones/";
public static final String RINGTONE_TYPE = "Ringtone";
public ListRingtonesAdapter(Context context, int viewResourceId,
ArrayList<SongInfo> objects, boolean inRingtones) {
super(context, viewResourceId, objects);
// TODO Auto-generated constructor stub
this.context = context;
this.items = objects;
this.pref = new RingtonesSharedPreferences(context);
this.inRingtones = inRingtones;
if(Main.mp.isPlaying()){
Main.mp.stop();
}
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ActionItem defRingtone = new ActionItem(DEFAULT_RINGTONE,
"Default Ringtone", context.getResources().getDrawable(
R.drawable.icon_ringtone));
ActionItem assign = new ActionItem(ASSIGN_TO_CONTACT,
"Contact Ringtone", context.getResources().getDrawable(
R.drawable.icon_contact));
ActionItem defNotifi = new ActionItem(DEFAULT_NOTIFICATION,
"Default Notification", context.getResources().getDrawable(
R.drawable.icon_notify));
ActionItem defAlarm = new ActionItem(DEFAULT_ALARM, "Default Alarm",
context.getResources().getDrawable(R.drawable.icon_alarm));
final QuickAction mQuickAction = new QuickAction(context);
mQuickAction.addActionItem(defRingtone);
mQuickAction.addActionItem(assign);
mQuickAction.addActionItem(defNotifi);
mQuickAction.addActionItem(defAlarm);
// setup the action item click listener
mQuickAction
.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
#Override
public void onItemClick(QuickAction quickAction, int pos,
int actionId) {
switch (actionId) {
case DEFAULT_RINGTONE:
setDefaultRingtone(items.get(curPosition));
Toast.makeText(context,
"Ringtone set successfully",
Toast.LENGTH_LONG).show();
break;
case ASSIGN_TO_CONTACT:
Intent intent = new Intent(context,
SelectContactActivity.class);
intent.putExtra("position", curPosition);
context.startActivity(intent);
break;
case DEFAULT_ALARM:
setDefaultAlarm(items.get(curPosition));
Toast.makeText(context,
"Alarm set successfully",
Toast.LENGTH_LONG).show();
break;
case DEFAULT_NOTIFICATION:
setDefaultNotice(items.get(curPosition));
Toast.makeText(context,
"Notification set successfully",
Toast.LENGTH_LONG).show();
break;
default:
break;
}
}
});
// setup on dismiss listener, set the icon back to normal
mQuickAction.setOnDismissListener(new PopupWindow.OnDismissListener() {
#Override
public void onDismiss() {
}
});
View view = null;
if (convertView == null) {
LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = li.inflate(R.layout.listelement, null);
final ViewHolder holder = new ViewHolder();
holder.txtName = (TextView) view.findViewById(R.id.txtSongName);
holder.btnFavorite = (ImageView) view.findViewById(R.id.btnFavorite);
holder.btnPlayPause = (ImageView) view.findViewById(R.id.btnPlayPause);
view.setTag(holder);
} else {
view = convertView;
// holder = (ViewHolder) view.getTag();
}
final SongInfo item = items.get(position);
if (item != null) {
final ViewHolder holder = (ViewHolder) view.getTag();
holder.txtName.setText(item.getName())
;
if (item.isFavorite()) {
holder.btnFavorite.setBackgroundResource(R.drawable.icon_favorite);
} else {
holder.btnFavorite.setBackgroundResource(R.drawable.icon_favorite_off);
}
if (!item.isPlaying()) {
holder.btnPlayPause.setBackgroundResource(R.drawable.icon_play);
} else {
holder.btnPlayPause.setBackgroundResource(R.drawable.icon_pause);
}
holder.btnPlayPause.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (Main.mp.isPlaying()) {
Main.mp.stop();
}
for(int i = 0; i < items.size(); i++){
if(items.get(i) != item)
items.get(i).setPlaying(false);
}
for(int i = 0; i < listHolder.size(); i++){
listHolder.get(i).btnPlayPause.setBackgroundResource(R.drawable.icon_play);
}
if (item.isPlaying()) {
holder.btnPlayPause.setBackgroundResource(R.drawable.icon_play);
item.setPlaying(false);
items.get(position).setPlaying(false);
if (Main.mp.isPlaying()) {
Main.mp.stop();
}
} else {
curPosition = position;
playAudio(context, item.getAudioResource());
holder.btnPlayPause.setBackgroundResource(R.drawable.icon_pause);
item.setPlaying(true);
items.get(position).setPlaying(true);
}
for (ViewHolder object : listHolder) {
if (object != holder) {
object.btnPlayPause.setBackgroundResource(R.drawable.icon_play);
}
}
}
});
holder.btnFavorite.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (item.isFavorite()) {
holder.btnFavorite
.setBackgroundResource(R.drawable.icon_favorite_off);
item.setFavorite(false);
pref.setString(item.getFileName(), false);
if (!inRingtones) {
Intent broadcast = new Intent();
broadcast.setAction("REMOVE_SONG");
context.sendBroadcast(broadcast);
}
} else {
holder.btnFavorite
.setBackgroundResource(R.drawable.icon_favorite);
item.setFavorite(true);
pref.setString(item.getFileName(), true);
}
}
});
listHolder.add(holder);
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mQuickAction.show(v);
curPosition = position;
}
});
}
return view;
}
private Object getAssets() {
// TODO Auto-generated method stub
return null;
}
private TextView findViewById(int txtsongname)
{
// TODO Auto-generated method stub
return null;
}
static class ViewHolder {
private TextView txtName;
private ImageView btnFavorite;
private ImageView btnPlayPause;
}
private void playAudio(Context context, int id) {
if (Main.mp.isPlaying()) {
Main.mp.stop();
}
Main.mp = MediaPlayer.create(context, id);
Main.mp.setOnCompletionListener(playCompletionListener);
Main.mp.start();
onRingtonePlay.onPlay();
}
private OnCompletionListener playCompletionListener = new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
for(int i = 0; i < items.size(); i++){
items.get(i).setPlaying(false);
}
for(int i = 0; i < listHolder.size(); i++){
listHolder.get(i).btnPlayPause
.setBackgroundResource(R.drawable.icon_play);
}
}
};
private void setRingtone(SongInfo info, boolean ringtone, boolean alarm,
boolean music, boolean notification) {
File dir = null;
String what = null;
if (ringtone) {
what = "Ringtones";
}else if(alarm){
what = "alarms";
}else if(notification){
what = "notifications";
}else{
what = "Ringtones";
}
if (Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
dir = new File(Environment.getExternalStorageDirectory(),what);
} else {
dir = context.getCacheDir();
}
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, info.getFileName());
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
InputStream inputStream = context.getResources()
.openRawResource(info.getAudioResource());
OutputStream outputStream = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
outputStream.flush();
outputStream.close();
inputStream.close();
} catch (Exception e) {
// TODO: handle exception
}
}
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE));
Uri uri = MediaStore.Audio.Media.getContentUriForPath(file.getAbsolutePath());
String[] projection = new String[] { MediaStore.MediaColumns.DATA,
MediaStore.Audio.Media.IS_RINGTONE,
MediaStore.Audio.Media.IS_ALARM,
MediaStore.Audio.Media.IS_MUSIC,
MediaStore.Audio.Media.IS_NOTIFICATION
};
Cursor c = context.getContentResolver().query(uri,projection,MediaStore.MediaColumns.DATA + " = \"" + file.getAbsolutePath()+ "\"", null, null);
String strRingtone = null, strAlarm = null, strNotifi = null, strMusic = null;
while (c.moveToNext()) {
strRingtone = c.getString(c
.getColumnIndex(MediaStore.Audio.Media.IS_RINGTONE));
strAlarm = c.getString(c
.getColumnIndex(MediaStore.Audio.Media.IS_ALARM));
strNotifi = c.getString(c
.getColumnIndex(MediaStore.Audio.Media.IS_NOTIFICATION));
strMusic = c.getString(c
.getColumnIndex(MediaStore.Audio.Media.IS_MUSIC));
}
if (ringtone) {
if ((strAlarm != null) && (strAlarm.equals("1")))
alarm = true;
if ((strNotifi != null) && (strNotifi.equals("1")))
notification = true;
if ((strMusic != null) && (strMusic.equals("1")))
music = true;
} else if (notification) {
if ((strAlarm != null) && (strAlarm.equals("1")))
alarm = true;
if ((strRingtone != null) && (strRingtone.equals("1")))
ringtone = true;
if ((strMusic != null) && (strMusic.equals("1")))
music = true;
} else if (alarm) {
if ((strNotifi != null) && (strNotifi.equals("1")))
notification = true;
if ((strRingtone != null) && (strRingtone.equals("1")))
ringtone = true;
if ((strMusic != null) && (strMusic.equals("1")))
music = true;
} else if (music) {
if ((strNotifi != null) && (strNotifi.equals("1")))
notification = true;
if ((strRingtone != null) && (strRingtone.equals("1")))
ringtone = true;
if ((strAlarm != null) && (strAlarm.equals("1")))
alarm = true;
}
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, info.getName());
values.put(MediaStore.MediaColumns.SIZE, file.length());
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
if (ringtone) {
values.put(MediaStore.Audio.Media.IS_RINGTONE, ringtone);
} else if (notification) {
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, notification);
} else if (alarm) {
values.put(MediaStore.Audio.Media.IS_ALARM, alarm);
} else if (music) {
values.put(MediaStore.Audio.Media.IS_MUSIC, music);
}
context.getContentResolver().delete(uri,MediaStore.MediaColumns.DATA + " = \"" + file.getAbsolutePath() + "\"", null);
Uri newUri = context.getContentResolver().insert(uri, values);
int type = RingtoneManager.TYPE_ALL;
if (ringtone)
type = RingtoneManager.TYPE_RINGTONE;
if (alarm)
type = RingtoneManager.TYPE_ALARM;
if (notification)
type = RingtoneManager.TYPE_NOTIFICATION;
RingtoneManager.setActualDefaultRingtoneUri(context, type, newUri);
}
private void setDefaultRingtone(SongInfo info) {
File dir = null;
String what = "Ringtones";
Uri newUri = null;
ContentValues values = new ContentValues();
boolean isRingTone = false;
if (Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
dir = new File(Environment.getExternalStorageDirectory(),what);
} else {
dir = context.getCacheDir();
}
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, info.getFileName());
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
InputStream inputStream = context.getResources()
.openRawResource(info.getAudioResource());
OutputStream outputStream = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
outputStream.flush();
outputStream.close();
inputStream.close();
} catch (Exception e) {
// TODO: handle exception
}
}
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE));
String[] columns = { MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.IS_RINGTONE
};
Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, columns, MediaStore.Audio.Media.DATA+" = '"+file.getAbsolutePath()+"'",null, null);
if (cursor!=null) {
int idColumn = cursor.getColumnIndex(MediaStore.Audio.Media._ID);
int fileColumn = cursor.getColumnIndex(MediaStore.Audio.Media.DATA);
int ringtoneColumn = cursor.getColumnIndex(MediaStore.Audio.Media.IS_RINGTONE);
while (cursor.moveToNext()) {
String audioFilePath = cursor.getString(fileColumn);
if (cursor.getString(ringtoneColumn)!=null && cursor.getString(ringtoneColumn).equals("1")) {
Uri hasUri = MediaStore.Audio.Media.getContentUriForPath(audioFilePath);
newUri = Uri.withAppendedPath(hasUri, cursor.getString(idColumn));
isRingTone = true;
}
}
cursor.close();
}
if (isRingTone) {
RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_RINGTONE, newUri);
}else{
values.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, info.getName());
values.put(MediaStore.MediaColumns.SIZE, file.length());
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
newUri = context.getContentResolver().insert(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, values);
RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_RINGTONE, newUri);
}
}
private void setDefaultAlarm(SongInfo info) {
File dir = null;
String what = "alarms";
Uri newUri = null;
ContentValues values = new ContentValues();
boolean isRingTone = false;
if (Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
dir = new File(Environment.getExternalStorageDirectory(),what);
} else {
dir = context.getCacheDir();
}
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, info.getFileName());
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
InputStream inputStream = context.getResources()
.openRawResource(info.getAudioResource());
OutputStream outputStream = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
outputStream.flush();
outputStream.close();
inputStream.close();
} catch (Exception e) {
// TODO: handle exception
}
}
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE));
String[] columns = { MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.IS_ALARM
};
Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, columns, MediaStore.Audio.Media.DATA+" = '"+file.getAbsolutePath()+"'",null, null);
if (cursor!=null) {
int idColumn = cursor.getColumnIndex(MediaStore.Audio.Media._ID);
int fileColumn = cursor.getColumnIndex(MediaStore.Audio.Media.DATA);
int ringtoneColumn = cursor.getColumnIndex(MediaStore.Audio.Media.IS_ALARM);
while (cursor.moveToNext()) {
String audioFilePath = cursor.getString(fileColumn);
if (cursor.getString(ringtoneColumn)!=null && cursor.getString(ringtoneColumn).equals("1")) {
Uri hasUri = MediaStore.Audio.Media.getContentUriForPath(audioFilePath);
newUri = Uri.withAppendedPath(hasUri, cursor.getString(idColumn));
isRingTone = true;
}
}
cursor.close();
}
if (isRingTone) {
RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_ALARM, newUri);
}else{
values.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, info.getName());
values.put(MediaStore.MediaColumns.SIZE, file.length());
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
values.put(MediaStore.Audio.Media.IS_ALARM, true);
newUri = context.getContentResolver().insert(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, values);
RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_ALARM, newUri);
}
}
private void setDefaultNotice(SongInfo info) {
File dir = null;
String what = "notifications";
Uri newUri = null;
ContentValues values = new ContentValues();
boolean isRingTone = false;
if (Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
dir = new File(Environment.getExternalStorageDirectory(),what);
} else {
dir = context.getCacheDir();
}
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, info.getFileName());
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
InputStream inputStream = context.getResources()
.openRawResource(info.getAudioResource());
OutputStream outputStream = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
outputStream.flush();
outputStream.close();
inputStream.close();
} catch (Exception e) {
// TODO: handle exception
}
}
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE));
String[] columns = { MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.IS_NOTIFICATION
};
Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, columns, MediaStore.Audio.Media.DATA+" = '"+file.getAbsolutePath()+"'",null, null);
if (cursor!=null) {
int idColumn = cursor.getColumnIndex(MediaStore.Audio.Media._ID);
int fileColumn = cursor.getColumnIndex(MediaStore.Audio.Media.DATA);
int ringtoneColumn = cursor.getColumnIndex(MediaStore.Audio.Media.IS_NOTIFICATION);
while (cursor.moveToNext()) {
String audioFilePath = cursor.getString(fileColumn);
if (cursor.getString(ringtoneColumn)!=null && cursor.getString(ringtoneColumn).equals("1")) {
Uri hasUri = MediaStore.Audio.Media.getContentUriForPath(audioFilePath);
newUri = Uri.withAppendedPath(hasUri, cursor.getString(idColumn));
isRingTone = true;
}
}
cursor.close();
}
if (isRingTone) {
RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_NOTIFICATION, newUri);
}else{
values.put(MediaStore.MediaColumns.DATA, file.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, info.getName());
values.put(MediaStore.MediaColumns.SIZE, file.length());
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
newUri = context.getContentResolver().insert(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, values);
RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_NOTIFICATION, newUri);
}
}
private void deleteRingtone(SongInfo info) {
File dir = null;
if (Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED)) {
dir = new File(Environment.getExternalStorageDirectory(),
"Ringtones");
} else {
dir = context.getCacheDir();
}
if (!dir.exists()) {
dir.mkdirs();
}
Log.d(TAG, "dir:"+dir.getPath());
File file = new File(dir, info.getFileName());
Log.d(TAG, "file name:"+info.getFileName());
Uri uri = MediaStore.Audio.Media.getContentUriForPath(file
.getAbsolutePath());
context.getContentResolver().delete(
uri,
MediaStore.MediaColumns.DATA + " = \"" + file.getAbsolutePath()
+ "\"", null);
if (file.exists()) {
file.delete();
}
}
OnRingtonePlay onRingtonePlay;
/**
* #param onRingtonePlay the onRingtonePlay to set
*/
public void setOnRingtonePlay(OnRingtonePlay onRingtonePlay) {
this.onRingtonePlay = onRingtonePlay;
}
interface OnRingtonePlay{
public void onPlay();
}
}
/* Set Font Method */
public static void overrideFonts(final Context context, final View v) {
try {
if (v instanceof ViewGroup) {
ViewGroup vg = (ViewGroup) v;
for (int i = 0; i < vg.getChildCount(); i++) {
View child = vg.getChildAt(i);
overrideFonts(context, child);
}
} else if (v instanceof TextView) {
((TextView) v).setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts/Xcelsion.ttf"));
}
} catch (Exception ignored) {
}
}
/* And use this method as below */
overrideFonts(context, myTextView);
Put typeface coding in getView(final int position, View convertView, ViewGroup parent) method in this part of your code
View view = null;
if (convertView == null) {
LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = li.inflate(R.layout.listelement, null);
final ViewHolder holder = new ViewHolder();
holder.txtName = (TextView) view.findViewById(R.id.txtSongName);
holder.btnFavorite = (ImageView) view.findViewById(R.id.btnFavorite);
holder.btnPlayPause = (ImageView) view.findViewById(R.id.btnPlayPause);
Typeface myTypeface = Typeface.createFromAsset(context.getAssets(), "fonts/Xcelsion.ttf");
holder.txtName.setTypeface(myTypeface);
view.setTag(holder);
} else {
view = convertView;
// holder = (ViewHolder) view.getTag();
}
I am trying to download the image from url and save it in a file. But it's not getting saved. So as I debug the code I found that bitmap is always null.
code:
public class ImageUserTask extends AsyncTask<Void, Void,String> {
String strURL, imageprofile;
Bitmap mBitmap = null;
Context mContext;
private File profileFile;
public ImageUserTask(Context context, String url) {
this.strURL = url;
this.imageprofile = imageprofile;
this.mContext = context;
}
#Override
protected String doInBackground(Void... params) {
Bitmap bitmap = null;
File directory = null;
try {
URL url = new URL(strURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
// InputStream input = connection.getInputStream();
bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream()); //This bitmap is null always
directory = Environment.getExternalStorageDirectory();
// Create a new folder in SD Card
File dir = new File(Environment.getExternalStorageDirectory().getPath() + "/Profile");
if (!directory.exists() && !directory.isDirectory()) {
directory.mkdirs();
}
File mypath = new File(dir,"ProfileImage");
saveFile(mypath, bitmap);
} catch (MalformedURLException e) {
} catch (IOException e) {
}
return directory.getAbsolutePath();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (result != null) {
imageprofile = result;
}
}
private void saveFile(File fileName, Bitmap bmp) {
FileOutputStream outputStream = null;
try {
outputStream = new FileOutputStream(fileName);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, outputStream); // 100 will be ignored
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (outputStream != null) {
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
EDIT:
public class ImageUserTask extends AsyncTask<Void,Void,Bitmap> {
String strURL, imageprofile;
Bitmap mBitmap = null;
Context mContext;
private File profileFile;
public ImageUserTask(Context context, String url) {
this.strURL = url;
this.imageprofile = imageprofile;
this.mContext = context;
}
#Override
protected Bitmap doInBackground(Void... params) {
getImageFromUrl(strURL);
return mBitmap;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
if (result != null) {
Bitmap bitmap = result;
}
}
public Bitmap getImageFromUrl(String urlString) {
try {
URL url = new URL(urlString);
try {
if(mBitmap!=null) {
mBitmap.recycle();
mBitmap=null;
}
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setDoInput(true);
//Connected to server
connection.connect();
//downloading image
InputStream input = connection.getInputStream();
mBitmap = BitmapFactory.decodeStream(input);
convertBitmapToFile(mBitmap, urlString);
} catch (IOException e) {
e.printStackTrace();
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
return mBitmap;
}
public File convertBitmapToFile(Bitmap bitmap, String fileName) {
ContextWrapper cw = new ContextWrapper(mContext);
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
File mypath = new File(directory, fileName);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
return mypath;
}
}
What can be the reason? I have added Internet permissions too. Please help. Thank you..
class DownloadFile extends AsyncTask<String, Integer, String> {
String strFolderName;
String shareType;
String downloadPath = "";
Activity mContext;
public DownloadFile(Activity mContext) {
this.mContext = mContext;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... aurl) {
int count;
try {
String fileName = "your filename with ext";
Log.d("TAG", fileName);
URL url = new URL("your url");
URLConnection conexion = url.openConnection();
conexion.connect();
String PATH = "your Path you want to store" + "/";
downloadPath = PATH + fileName;
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(downloadPath);
byte data[] = new byte[1024];
while ((count = input.read(data)) != -1) {
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String path) {
super.onPostExecute(path);
}
}
This code is work for me
Use the below methods
public Bitmap getImageFromUrl(String urlString) {
Bitmap bmp = null;
try {
URL url = new URL(urlString);
try {
if(bmp!=null) {
bmp.recycle();
bmp=null;
}
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
convertBitmapToFile(bmp, urlString);
} catch (IOException e) {
e.printStackTrace();
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
return bmp;
}
public File convertBitmapToFile(Bitmap bitmap, String fileName) {
ContextWrapper cw = new ContextWrapper(activityRef.getApplicationContext());
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
File mypath = new File(directory, fileName);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
return mypath;
}
Add android Permissions for internet and Storage
Please try this
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;
}
}
I'm working on uploading multiple images. I can pick an image from my phone's sd card but when I'm trying to upload it to my database, the progress dialog shows "Uploading" only and after that it is being dismissed. Honestly, I'm not sure on my php code. Hope someone can help me :)
Here's my uploadActivity.java:
#SuppressLint("NewApi")
public class MainActivity extends Activity {
private Button upload, pick;
private ProgressDialog dialog;
MultipartEntity entity;
GridView gv;
int count = 0;
public ArrayList<String> map = new ArrayList<String>();
Bundle b;
TextView noImage;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
b = getIntent().getExtras();
noImage = (TextView) findViewById(R.id.noImage);
upload = (Button) findViewById(R.id.btnUpload);
pick = (Button) findViewById(R.id.btnPicture);
gv = (GridView) findViewById(R.id.gridview);
gv.setAdapter(new ImageAdapter(this));
if (b != null) {
ArrayList<String> ImgData = b.getStringArrayList("IMAGE");
for (int i = 0; i < ImgData.size(); i++) {
map.add(ImgData.get(i).toString());
}
} else {
noImage.setVisibility(View.VISIBLE);
}
upload.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new ImageUploadTask()
.execute(count + "", "pk" + count + ".jpg");
}
});
pick.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i3 = new Intent(MainActivity.this, UploadActivity.class);
startActivity(i3);
}
});
}
class ImageUploadTask extends AsyncTask<String, Void, String> {
String sResponse = null;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog = ProgressDialog.show(MainActivity.this, "Uploading",
"Please wait...", true);
dialog.show();
}
#Override
protected String doInBackground(String... params) {
try {
String url = "http://iguideph-001-btempurl.com/uploads.php";
int i = Integer.parseInt(params[0]);
Bitmap bitmap = decodeFile(map.get(i));
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
entity = new MultipartEntity();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
entity.addPart("user_id", new StringBody("199"));
entity.addPart("club_id", new StringBody("10"));
entity.addPart("club_image", new ByteArrayBody(data,
"image/jpeg", params[1]));
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost,
localContext);
sResponse = EntityUtils.getContentCharSet(response.getEntity());
System.out.println("sResponse : " + sResponse);
} catch (Exception e) {
if (dialog.isShowing())
dialog.dismiss();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
return sResponse;
}
#Override
protected void onPostExecute(String sResponse) {
try {
if (dialog.isShowing())
dialog.dismiss();
if (sResponse != null) {
Toast.makeText(getApplicationContext(),
sResponse + " Photo uploaded successfully",
Toast.LENGTH_SHORT).show();
count++;
if (count < map.size()) {
new ImageUploadTask().execute(count + "", "hm" + count
+ ".jpg");
}
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(),
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
}
public Bitmap decodeFile(String filePath) {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 1024;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
Bitmap bitmap = BitmapFactory.decodeFile(filePath, o2);
return bitmap;
}
private class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return map.size();
}
public Object getItem(int position) {
return null;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) { // if it's not recycled, initialize some
// attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85,
Gravity.CENTER));
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setPadding(1, 1, 1, 1);
} else {
imageView = (ImageView) convertView;
}
imageView
.setImageBitmap(BitmapFactory.decodeFile(map.get(position)));
return imageView;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
MainActivity.this.finish();
}
}
and here's my uploads.php:
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$image = $_POST['club_image'];
$userid=$_POST['user_id'];
$clubid=$_POST['club_id'];
require_once('connection.php');
$sql ="SELECT * FROM photos ORDER BY id ASC";
$res = mysqli_query($con,$sql);
$id = 0;
while($row = mysqli_fetch_array($res)){
$id = $row['id'];
}
$path = "uploads/$id.jpg";
$actualpath = "http://iguideph-001-site1.btempurl.com/PhotoUpload/$path";
$sql = "INSERT INTO photos (image) VALUES ('$actualpath')";
if(mysqli_query($con,$sql)){
file_put_contents($path,base64_decode($image));
echo "Successfully Uploaded";
}
mysqli_close($con);
}else{
echo "Error";
}
?>
I pass my view imageview into this imageloader class I have created, but for some reason I am getting this error "SkImageDecoder::Factory returned null" which seems to only happen for some images, that the url's should be fine with. It will only load 3 out of a list of ten. I was wondering if this task wasn't properly thread safe or something else I may have missed. Take a look below
ImageLoader:
public class ImageLoader {
MemoryCache memoryCache = new MemoryCache();
FileCache fileCache;
private Map<ImageView, String> imageViews = Collections
.synchronizedMap(new WeakHashMap<ImageView, String>());
ExecutorService executorService;
public ImageLoader(Context context) {
fileCache = new FileCache(context);
executorService = Executors.newFixedThreadPool(5);
}
final int stub_id = R.drawable.failed_load;
public void displayImage(String url, ImageView imageView) {
System.out.println(url);
imageViews.put(imageView, url);
Bitmap bitmap = memoryCache.get(url);
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
} else {
queuePhoto(url, imageView);
imageView.setImageResource(stub_id);
}
}
private void queuePhoto(String url, ImageView imageView) {
PhotoToLoad p = new PhotoToLoad(url, imageView);
executorService.submit(new PhotosLoader(p));
}
private Bitmap getBitmap(String url) {
File f = fileCache.getFile(url);
// from SD cache
Bitmap b = decodeFile(f);
if (b != null) {
return b;
}
// from web
try {
Bitmap bitmap = null;
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) imageUrl
.openConnection();
conn.setConnectTimeout(3000);
conn.setReadTimeout(3000);
conn.setInstanceFollowRedirects(true);
InputStream is = conn.getInputStream();
OutputStream os = new FileOutputStream(f);
IOUtils.copy(is, os);// Util.CopyStream(is, os); //TODO DELETE
os.close();
bitmap = decodeFile(f);
return bitmap;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
// decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f) {
try {
// decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
// Find the correct scale value. It should be the power of 2.
// TODO Can change image content here.
final int REQUIRED_SIZE = 512;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE
|| height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {
}
return null;
}
// Task for the queue
private class PhotoToLoad {
public String url;
public ImageView imageView;
public PhotoToLoad(String u, ImageView i) {
url = u;
imageView = i;
}
}
class PhotosLoader implements Runnable {
PhotoToLoad photoToLoad;
PhotosLoader(PhotoToLoad photoToLoad) {
this.photoToLoad = photoToLoad;
}
#Override
public void run() {
if (imageViewReused(photoToLoad)) {
return;
}
Bitmap bmp = getBitmap(photoToLoad.url);
memoryCache.put(photoToLoad.url, bmp);
if (imageViewReused(photoToLoad)) {
return;
}
BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
Activity a = (Activity) photoToLoad.imageView.getContext();
a.runOnUiThread(bd);
}
}
boolean imageViewReused(PhotoToLoad photoToLoad) {
String tag = imageViews.get(photoToLoad.imageView);
if (tag == null || !tag.equals(photoToLoad.url)) {
return true;
}
return false;
}
// Used to display bitmap in the UI thread
class BitmapDisplayer implements Runnable {
Bitmap bitmap;
PhotoToLoad photoToLoad;
public BitmapDisplayer(Bitmap b, PhotoToLoad p) {
bitmap = b;
photoToLoad = p;
}
public void run() {
if (imageViewReused(photoToLoad)) {
return;
}
if (bitmap != null) {
photoToLoad.imageView.setImageBitmap(bitmap);
} else {
photoToLoad.imageView.setImageResource(stub_id);
}
}
}
public void clearCache() {
memoryCache.clear();
fileCache.clear();
}
}
Unfortunately the solution was double checking the incoming url's, that were wrong, and everything seems to be fine now. For anyone else having a similar problem, double check what you are loading, and the files that are coming in, from wherever you are trying to load them.