How to set parsed image as background instead of src - java

I have a customized list view which parses images for the lists but it reads them in as src
<ImageView
android:id="#+id/list_image"
android:layout_height="420dp"
android:layout_width="fill_parent"
android:src="#drawable/posty"
android:clickable="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"/>
is there anyway to set it so that android:src="#drawable/posty" can be android:background="#drawable/posty" but with the parsed image thanks.
the adapter:
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.list_row, null);
TextView title = (TextView)vi.findViewById(R.id.title); // title
TextView artist = (TextView)vi.findViewById(R.id.author); // name
TextView duration = (TextView)vi.findViewById(R.id.duration); // description
TextView id = (TextView)vi.findViewById(R.id.id); // Section
ImageView thumb_image=(ImageView)vi.findViewById(R.id.list_image); // thumb image
HashMap<String, String> song = new HashMap<String, String>();
song = data.get(position);
// Setting all values in listview
id.setText(song.get(CustomizedListView.KEY_ID));
artist.setText(song.get(CustomizedListView.KEY_ARTIST));
duration.setText(song.get(CustomizedListView.KEY_DURATION));
imageLoader.DisplayImage(song.get(CustomizedListView.KEY_THUMB_URL), thumb_image);
return vi;
}
}
and the image loader:
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.no_image;
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 (Exception ex){
ex.printStackTrace();
return null;
}
}
//decodes image and scales it to reduce memory consumption
//decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f){
try {
return BitmapFactory.decodeStream(new FileInputStream(f));
} 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();
}

you can use setBackgroundDrawable. Create a BitmapDrawable from your bitmap :
BitmapDrawable bd = new BitmapDrawable(yourBitamp);
imageView.setBackgroundDrawable(bd);
Edit:
public void DisplayImage(String url, ImageView imageView)
{
imageViews.put(imageView, url);
Bitmap bitmap=memoryCache.get(url);
if(bitmap!=null) {
BitmapDrawable bd = new BitmapDrawable(bitmap);
imageView.setBackgroundDrawable(bd);
}
else
{
queuePhoto(url, imageView);
imageView.setImageResource(stub_id);
}
}

Get BitmapDrawable from image Bitmap then use ImageView.setBackgroundDrawable for setting image as background instead of src. change DisplayImage method as:
public void DisplayImage(String url, ImageView imageView)
{
imageViews.put(imageView, url);
Bitmap bitmap=memoryCache.get(url);
if(bitmap!=null){
BitmapDrawable bd = new BitmapDrawable(bitmap);
imageView.setBackgroundDrawable(bd);
}
else
{
queuePhoto(url, imageView);
imageView.setImageResource(stub_id);
}
}

Related

Camera API. Not saving image [duplicate]

I'm creating camera app. I'm doing that in fragment. I have FrameLayout where I add the camera, and one button for capture. There are 2 problems.
Camera not saves the image.
When I click second time on capture image, drops exception java.lang.RuntimeException: takePicture failed
I don't know where's the problem, I'm using camera API first time.
Camera I'm using only in portrait mode. And in manifests I added the permissions for camera and write external storage.
I have one class where I'm extending SurfaceView. Let me show you the code.
public class ShowCamera extends SurfaceView implements SurfaceHolder.Callback{
Camera camera;
SurfaceHolder holder;
public ShowCamera(Context context, Camera camera) {
super(context);
this.camera = camera;
holder = getHolder();
holder.addCallback(this);
}
#Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
Camera.Parameters params = camera.getParameters();
List<Camera.Size> sizes = params.getSupportedPictureSizes();
Camera.Size mSize = null;
for (Camera.Size size : sizes){
mSize = size;
}
camera.setDisplayOrientation(90);
params.setRotation(90);
params.setPictureSize(mSize.width, mSize.height);
camera.setParameters(params);
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
}
#Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
camera.stopPreview();
camera.release();
}
}
Ok and here's the fragment for camera.
public class CameraActivity extends BaseFragment{
View mainView;
FrameLayout cameraLayout;
Camera camera;
ShowCamera showCamera;
ImageButton captureImage;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mainView = inflater.inflate(R.layout.camera_fragment, container, false);
cameraLayout = (FrameLayout) mainView.findViewById(R.id.cameraContainer);
captureImage = (ImageButton) mainView.findViewById(R.id.imageButton);
camera = Camera.open();
showCamera = new ShowCamera(getActivity(), camera);
cameraLayout.addView(showCamera);
capture();
return mainView;
}
Camera.PictureCallback mPictureCallback = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] bytes, Camera camera) {
if(bytes != null){
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
if(bitmap != null){
File file = new File(String.valueOf(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)));
if(!file.isDirectory()){
file.mkdir();
}
file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
System.currentTimeMillis() + ".jpg");
try {
FileOutputStream fileOutputStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
} catch (Exception e){
e.printStackTrace();
}
}
}
}
};
public void capture(){
captureImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(camera != null){
camera.takePicture(null, null, mPictureCallback);
}
}
});
}
}

Error in getting images from server

This is my Main Activity class.I am new in android development and I'm stuck here. Having a problem in getting images from the server.
I have an image loader class to which loads an image in imageView and memory cache and utils etc.
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, SearchView.OnQueryTextListener {
ListView list;
SearchView mSearchView;
LazyAdapter adapter;
JSONArray jarray;
String data = "", line = null, strresponse, txt, myjson;
BufferedReader reader;
String dataparseurl = "https://ndroid.000webhostapp.com/Php2/getListofrestaurant.php";
public String Id;
public String SName;
public String ShortAdd;
public String imagesserver;
public String hour;
public String address;
ArrayList<HashMap<String, String>> arraylist;
private String Name[] = {"Sagar Gaire Fast Food", "Sharma and Vishnu Fast Food", "Sharma FastFood",
"Domino's Pizza", "Manohar Dairy", "Greek Food & Beyond"};
private int images[] = {R.drawable.img5, R.drawable.img6, R.drawable.img9, R.drawable.img8,
R.drawable.img7, R.drawable.img11};
private String hours[] = {"10AM TO 11PM", "8AM To 10PM", "11AM To 10:30PM", "8AM To 11PM", "8AM To 9PM", "11AM To 11PM"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
DataFromServer();
mSearchView = (SearchView) findViewById(R.id.searcview1);
list = (ListView) findViewById(R.id.lv1);
}
#Override
public void onDestroy() {
list.setAdapter(null);
super.onDestroy();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
finish();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_order) {
// Handle the order action
Intent yourorder = new Intent(MainActivity.this, YourOrder_Layout.class);
startActivity(yourorder);
finish();
} else if (id == R.id.nav_cart) {
Intent cart = new Intent(MainActivity.this, Cart_Layout.class);
startActivity(cart);
finish();
} else if (id == R.id.nav_profiledit) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void DataFromServer() {
class ServerData extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String[] params) {
arraylist = new ArrayList<HashMap<String, String>>();
try {
URL url = new URL(dataparseurl);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream());
osw.write(data);
osw.flush();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
while (((line = reader.readLine()) != null)) {
sb.append(line);
strresponse = sb.toString();
}
txt = strresponse;
} catch (Exception e) {
try {
reader.close();
} catch (IOException e1) {
e1.printStackTrace();
}
Toast.makeText(getApplicationContext(), "OOPs Something went wrong Check Your Connection", Toast.LENGTH_SHORT).show();
}
return txt;
}
#Override
protected void onPostExecute(String result) {
if (result == null && txt == null) {
Toast.makeText(getApplicationContext(), "can't be saved", Toast.LENGTH_SHORT).show();
} else {
myjson = result;
showlist();
}
}
}
ServerData sd = new ServerData();
sd.execute();
}
private void showlist() {
try {
JSONObject jsonObject = new JSONObject(myjson);
jarray = jsonObject.getJSONArray("result");
for (int i = 0; i < jarray.length(); i++) {
JSONObject c = jarray.getJSONObject(i);
Id = c.getString("Id");
SName = c.getString("RestName");
ShortAdd = c.getString("RestAddressshort");
imagesserver = c.getString("RestPic");
hour = c.getString("Resthours");
address = c.getString("RestAddress");
HashMap<String, String> map = new HashMap<String, String>();
map.put("ID",Id);
map.put("RestName",SName);
map.put("ShortAddres",ShortAdd);
map.put("RestPic",imagesserver);
map.put("Hour",hour);
map.put("Address",address);
arraylist.add(map);
}
Toast.makeText(getApplicationContext(), arraylist.get(0)+""+arraylist.get(1)+"",Toast.LENGTH_LONG).show();
adapter = new LazyAdapter(this,arraylist);
list.setAdapter(adapter);
list.setTextFilterEnabled(true);
mSearchView.setOnQueryTextListener(this);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent info = new Intent(MainActivity.this, Info_Layout.class);
startActivity(info);
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
}
Adapter Class
This is my Adapter Class getting data in array list but images are not getting.
It's working where saw its code but it's not working in my case.
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
private HashMap<String, String> resultp = new HashMap<String, String>();
public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> arraylist) {
activity = a;
data = arraylist;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.listitem_1, parent,false);
resultp = data.get(position);
TextView text=(TextView)vi.findViewById(R.id.textviewitemname);
TextView texttime = (TextView) vi.findViewById(R.id.textviewitemhours);
ImageView image=(ImageView)vi.findViewById(R.id.imageviewitem);
text.setText(resultp.get("RestName"));
texttime.setText(resultp.get("Hour"));
// image.setImageResource(data[position]);
imageLoader.DisplayImage(resultp.get("RestPic"),image);
return vi;
}
}
$ here is the image loader class
public class ImageLoader {
private MemoryCache memoryCache=new MemoryCache();
private FileCache fileCache;
private Map<ImageView, String> imageViews= Collections.synchronizedMap(new WeakHashMap<ImageView, String>());
private ExecutorService executorService;
public ImageLoader(Context context){
fileCache=new FileCache(context);
executorService= Executors.newFixedThreadPool(5);
}
private final int stub_id = R.drawable.image1;
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 the web
try {
Bitmap bitmap;
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;
BitmapFactory.decodeStream(new FileInputStream(f),null,o);
//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;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {e.printStackTrace();}
return null;
}
//Task for the queue
private class PhotoToLoad
{
String url;
ImageView imageView;
PhotoToLoad(String u, ImageView i){
url=u;
imageView=i;
}
}
private 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);
}
}
private boolean imageViewReused(PhotoToLoad photoToLoad){
String tag=imageViews.get(photoToLoad.imageView);
return tag == null || !tag.equals(photoToLoad.url);
}
//Used to display bitmap in the UI thread
private class BitmapDisplayer implements Runnable
{
Bitmap bitmap;
PhotoToLoad photoToLoad;
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);
}
}
}
Alternative solution using Glide
If I understand, through your link you get a list of images. Right?
To make requests to the server use the okhttp or volley library and return the result in JSON format. Then load the images using the glide library.
See this tutorial for volley https://www.simplifiedcoding.net/android-volley-tutorial-to-get-json-from-server/
This is glide library https://inthecheesefactory.com/blog/get-to-know-glide-recommended-by-google/en
So, add glide in your gradle
dependencies {
compile 'com.github.bumptech.glide:glide:3.5.2'
compile 'com.android.support:support-v4:22.0.0'
}
and instead of using ImageLoader, use this
Glide.with(context)
.load(resultp.get("RestPic"))
.into(imageView);

App works on WIFI but not on 3G

There are two activities: Main and Detail Activity.
Main Activity is basically a GridView.
Detail Activity is basically shows the clicked item's detail information. I am passing selected item's id (pid) from the Main to the Detail Activity.
I am facing an issue as follows. Initially, I have 3G connection (cellular connection) and clicked on the first item and see the corresponding item detail in the Detail Activity, it works perfectly fine, and go back to the Main Activity, then clicked on the second item, then unfortunately it still shows me the first item in the DetailActivity that I clicked initially.
I switched from 3g to wifi while app is on the active and open. No matter what I click, it still shows me the first item that I clicked initially.
But when I delete the app and reinstall it and get either wifi access only, the app works perfectly fine.
In the following implementation, Connection URL (PRODUCT_DETAIL_URL) is http, not https. I am using Volley library for the network connection.
DetailActivity.java
private void productDetailInit() {
// it is http
StringRequest postRequest = new StringRequest(Request.Method.POST, Config.PRODUCT_DETAIL_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
jsonObject = response;
loadJsonData();
} catch (Exception e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}
) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("id", productID);
return params;
}
};
RetryPolicy policy = new DefaultRetryPolicy(1000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
postRequest.setRetryPolicy(policy);
CustomVolleyRequest.getInstance(this).getRequestQueue().add(postRequest);
}
CustomVolleyRequest.java
public class CustomVolleyRequest {
private static CustomVolleyRequest customVolleyRequest;
private static Context context;
private RequestQueue requestQueue;
private ImageLoader imageLoader;
private CustomVolleyRequest(Context context) {
this.context = context;
this.requestQueue = getRequestQueue();
imageLoader = new ImageLoader(requestQueue,
new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap>
cache = new LruCache<String, Bitmap>(20);
#Override
public Bitmap getBitmap(String url) {
return cache.get(url);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
cache.put(url, bitmap);
}
});
}
private class BitmapCache implements ImageLoader.ImageCache {
private LruCache<String, Bitmap> mCache;
public BitmapCache() {
mCache = new LruCache<>(20);
}
#Override
public Bitmap getBitmap(String url) {
return mCache.get(url);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
// scaling bitmap for avoiding too much big images
Bitmap scaled = ImageUtil.getInstance().scaleBitmap(bitmap);
mCache.put(url, scaled);
}
}
public static synchronized CustomVolleyRequest getInstance(Context context) {
if (customVolleyRequest == null) {
customVolleyRequest = new CustomVolleyRequest(context);
}
return customVolleyRequest;
}
public RequestQueue getRequestQueue() {
if (requestQueue == null) {
Cache cache = new DiskBasedCache(context.getCacheDir(), 10 * 1024 * 1024);
Network network = new BasicNetwork(new HurlStack());
requestQueue = new RequestQueue(cache, network);
requestQueue.start();
}
return requestQueue;
}
public ImageLoader getImageLoader() {
return imageLoader;
}
}
Adapter.java
class ProductMainAdapter extends ArrayAdapter<ImageRecord> {
private ImageLoader mImageLoader;
private String jsonObject;
ProductMainAdapter(Context context) {
super(context, R.layout.grid_item);
mImageLoader = CustomVolleyRequest.getInstance(this.getContext()).getImageLoader();
}
#NonNull
#Override
public View getView(final int position, View convertView, #NonNull ViewGroup parent) {
final ViewHolder holder;
if(convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(getContext()).inflate(R.layout.grid_item, parent, false);
convertView.setBackgroundResource(R.drawable.round_gridview);
holder.priceTagImage = (ImageView) convertView.findViewById(R.id.priceTag_IV);
holder.textView = (TextView) convertView.findViewById(R.id.text);
holder.imageView = (NetworkImageView) convertView.findViewById(R.id.picture);
holder.priceTagRL = (RelativeLayout) convertView.findViewById(R.id.priceTag_RL);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
ImageRecord imageRecord = getItem(position);
holder.imageView.setImageUrl(imageRecord != null ? imageRecord.getUrl() : null, mImageLoader);
holder.imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openProductDetail(position);
}
});
holder.textView.setText(imageRecord != null ? imageRecord.getTitle() : null);
holder.priceTagRL.setRotation(0);
return convertView;
}
private class ViewHolder{
TextView textView;
ImageView priceTagImage;
NetworkImageView imageView;
RelativeLayout priceTagRL;
}
private void openProductDetail(int position) {
try {
ImageRecord imr = getItem(position);
String productID = imr != null ? imr.getId() : "0";
Intent intent = new Intent(getContext(), ProductDetailActivity.class);
intent.putExtra("pid", productID);
getContext().startActivity(intent);
} catch (Exception e) {
Log.e("openProductDetail", "exception", e);
}
}

SkImageDecoder::Factory returned null where downloading image in list adapter

I have a custom ListAdapter. I want to download image for every list item. I try to download them in AsyncTask (I found this solution in other discuss on so), but for some reason I always receive communicate "SkImageDecoder::Factory returned null"
public class MainMenuListAdapter extends BaseAdapter {
private List<Event> _events;
private Context _activityContext;
public MainMenuListAdapter(List<Event> events, Context context) {
this._events = events;
this._activityContext = context;
}
#Override
public int getCount() {
return this._events.size();
}
#Override
public Object getItem(int position) {
return this._events.get(position);
}
#Override
public long getItemId(int position) {
return this._events.get(position).getId();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView==null)
{
LayoutInflater inflater = (LayoutInflater) this._activityContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.mainmenu_list_item, parent,false);
}
Event e = (Event)getItem(position);
new DownloadImageTask((ImageView)convertView.findViewById(R.id.imageView1))
.execute("http://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png");
TextView tvName = (TextView)convertView.findViewById(R.id.name);
tvName.setText(e.getName());
TextView tvDescription = (TextView)convertView.findViewById(R.id.description);
tvDescription.setText(e.getDescription());
TextView tvDate = (TextView)convertView.findViewById(R.id.date);
tvDate.setText(e.getDate());
TextView tvAddress = (TextView)convertView.findViewById(R.id.address);
tvName.setText(e.getAddress());
return convertView;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
String uri = Uri.parse(urldisplay)
.buildUpon()
.appendQueryParameter("key", "val")
.build().toString();
Bitmap mIcon11 = null;
try {
URL url = new URL(uri);
InputStream in = url.openStream();
mIcon11 = BitmapFactory.decodeStream(in);
return mIcon11;
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}

How to display Bitmap / Drawable as centerCrop on tablets and fitXY on phones

I've got the below code from the AOSP wallpaper selector and im trying to simple display my wallpaper preview image as centerCrop on a tablet and FitXY on a phone, simply because the wallpaper image may not be big enough to fill the activity screen on a tablet therefore i want to centerCrop it.
Now the way im loading my center image is via my fragment and i do not have a specific ImageView i could simple change between to xml files (The easy way). Im just looking for some help on the best way to achieve this.
Here is the code - (Full Code)
public class WallpaperChooser extends Activity {
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.wallpaper_chooser_base);
Fragment fragmentView = getFragmentManager().findFragmentById(
R.id.wallpaper_chooser_fragment);
if (fragmentView == null) {
DialogFragment fragment = WallpaperChooserDialogFragment
.newInstance();
fragment.show(getFragmentManager(), "dialog");
}
}
public class WallpaperChooserDialogFragment extends DialogFragment implements
AdapterView.OnItemSelectedListener, AdapterView.OnItemClickListener {
private static final String TAG = "MainActivity.WallpaperChooserDialogFragment";
private static final String EMBEDDED_KEY = "org.app.wallpapers."
+ "WallpaperChooserDialogFragment.EMBEDDED_KEY";
private static final String SD = Environment.getExternalStorageDirectory().getAbsolutePath();
private boolean mEmbedded;
private Bitmap mBitmap = null;
private ImageAdapter mAdapter;
private ImageView image;
private ArrayList<Integer> mThumbs;
private ArrayList<Integer> mImages;
private WallpaperLoader mLoader;
private WallpaperDrawable mWallpaperDrawable = new WallpaperDrawable();
public static WallpaperChooserDialogFragment newInstance() {
WallpaperChooserDialogFragment fragment = new WallpaperChooserDialogFragment();
fragment.setCancelable(true);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null && savedInstanceState.containsKey(EMBEDDED_KEY)) {
mEmbedded = savedInstanceState.getBoolean(EMBEDDED_KEY);
} else {
mEmbedded = isInLayout();
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putBoolean(EMBEDDED_KEY, mEmbedded);
}
private void cancelLoader() {
if (mLoader != null && mLoader.getStatus() != WallpaperLoader.Status.FINISHED) {
mLoader.cancel(true);
mLoader = null;
}
}
#Override
public void onDetach() {
super.onDetach();
cancelLoader();
}
#Override
public void onDestroy() {
super.onDestroy();
cancelLoader();
}
#Override
public void onDismiss(DialogInterface dialog) {
super.onDismiss(dialog);
/* On orientation changes, the dialog is effectively "dismissed" so this is called
* when the activity is no longer associated with this dying dialog fragment. We
* should just safely ignore this case by checking if getActivity() returns null
*/
Activity activity = getActivity();
if (activity != null) {
activity.finish();
}
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
findWallpapers();
return null;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
findWallpapers();
if (mEmbedded) {
View view = inflater.inflate(R.layout.wallpaper_chooser, container, false);
view.setBackgroundDrawable(mWallpaperDrawable);
final Gallery gallery = (Gallery) view.findViewById(R.id.gallery);
gallery.setCallbackDuringFling(false);
gallery.setOnItemSelectedListener(this);
//gallery.setAdapter(new ImageAdapter(getActivity()));
mAdapter = new ImageAdapter(getActivity());
gallery.setAdapter(mAdapter);
return view;
}
return null;
}
private void selectWallpaper(int position) {
try {
WallpaperManager wpm = (WallpaperManager) getActivity().getSystemService(
Context.WALLPAPER_SERVICE);
wpm.setResource(mImages.get(position));
Activity activity = getActivity();
activity.setResult(Activity.RESULT_OK);
activity.finish();
} catch (IOException e) {
Log.e(TAG, "Failed to set wallpaper: " + e);
}
}
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectWallpaper(position);
}
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (mLoader != null && mLoader.getStatus() != WallpaperLoader.Status.FINISHED) {
//image.startAnimation(animFadeOut);
mLoader.cancel();
}
mLoader = (WallpaperLoader) new WallpaperLoader().execute(position);
}
public void onNothingSelected(AdapterView<?> parent) {
}
private void findWallpapers() {
mThumbs = new ArrayList<Integer>(24);
mImages = new ArrayList<Integer>(24);
final Resources resources = getResources();
final String packageName = resources.getResourcePackageName(R.array.all_wallpapers);
addWallpapers(resources, packageName, R.array.all_wallpapers);
}
private void addWallpapers(Resources resources, String packageName, int list) {
final String[] extras = resources.getStringArray(list);
for (String extra : extras) {
int res = resources.getIdentifier(extra, "drawable", packageName);
if (res != 0) {
final int thumbRes = resources.getIdentifier(extra + "_thumb",
"drawable", packageName);
if (thumbRes != 0) {
mThumbs.add(thumbRes);
mImages.add(res);
}
}
}
}
private class ImageAdapter extends BaseAdapter implements ListAdapter, SpinnerAdapter {
private LayoutInflater mLayoutInflater;
ImageAdapter(Activity activity) {
mLayoutInflater = activity.getLayoutInflater();
}
public int getCount() {
return mThumbs.size();
}
public Bitmap getImage(int i)
{
return getBitmap(((Integer)mImages.get(i)).intValue());
}
public Bitmap getItem(int i)
{
return getBitmap(((Integer)mImages.get(i)).intValue());
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
view = mLayoutInflater.inflate(R.layout.wallpaper_item, parent, false);
} else {
//image.startAnimation(animFadeIn);
view = convertView;
}
image = (ImageView) view.findViewById(R.id.wallpaper_image);
int thumbRes = mThumbs.get(position);
image.setImageResource(thumbRes);
Drawable thumbDrawable = image.getDrawable();
if (thumbDrawable != null) {
thumbDrawable.setDither(true);
} else {
Log.e(TAG, "Error decoding thumbnail resId=" + thumbRes + " for wallpaper #"
+ position);
}
return view;
}
}
class WallpaperLoader extends AsyncTask<Integer, Void, Bitmap> {
BitmapFactory.Options mOptions;
WallpaperLoader() {
mOptions = new BitmapFactory.Options();
mOptions.inDither = false;
mOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;
}
#Override
protected Bitmap doInBackground(Integer... params) {
if (isCancelled()) return null;
try {
return BitmapFactory.decodeResource(getResources(),
mImages.get(params[0]), mOptions);
} catch (OutOfMemoryError e) {
return null;
}
}
#Override
protected void onPostExecute(Bitmap b) {
if (b == null) return;
if (!isCancelled() && !mOptions.mCancel) {
// Help the GC
if (mBitmap != null) {
mBitmap.recycle();
}
View v = getView();
if (v != null) {
mBitmap = b;
mWallpaperDrawable.setBitmap(b);
v.postInvalidate();
} else {
mBitmap = null;
mWallpaperDrawable.setBitmap(null);
}
mLoader = null;
} else {
b.recycle();
}
}
void cancel() {
mOptions.requestCancelDecode();
super.cancel(true);
}
}
static class WallpaperDrawable extends Drawable {
Bitmap mBitmap;
int mIntrinsicWidth;
int mIntrinsicHeight;
/* package */void setBitmap(Bitmap bitmap) {
mBitmap = bitmap;
if (mBitmap == null)
return;
mIntrinsicWidth = mBitmap.getWidth();
mIntrinsicHeight = mBitmap.getHeight();
}
#Override
public void draw(Canvas canvas) {
if (mBitmap == null) return;
int width = canvas.getWidth();
int height = canvas.getHeight();
int x = (width - mIntrinsicWidth) / 2;
int y = (height - mIntrinsicHeight) / 2;
canvas.drawBitmap(mBitmap, x, y, null);
}
#Override
public int getOpacity() {
return android.graphics.PixelFormat.OPAQUE;
}
}
private Bitmap getBitmap(int i)
{
System.out.println(i);
if(i != 0)
{
System.out.println("ResourceID != 0");
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), i);
PrintStream printstream = System.out;
StringBuilder stringbuilder = new StringBuilder("Bitmap = null = ");
boolean flag;
if(bitmap == null)
flag = true;
else
flag = false;
printstream.println(stringbuilder.append(flag).toString());
if(bitmap != null)
return bitmap;
}
return null;
}
Test if the device is a tablet or a phone ?
public boolean isTablet(Context context) {
boolean xlarge = ((context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == 4);
boolean large = ((context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE);
return (xlarge || large);
}

Categories