Camera API. Not saving image [duplicate] - java

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);
}
}
});
}
}

Related

Unable to download Image through url into my phone in android 10

I m trying to download image into phone storage through its url using glide its working fine in android 9 or below buts its not working in case of android 10,
Here is my adapter code where i added download funtion, can some One help with the code
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {
Context context;
ArrayList<Model> modelArrayList;
public Adapter(Context context, ArrayList<Model> modelArrayList) {
this.context = context;
this.modelArrayList = modelArrayList;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.item_layout, parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
String url = modelArrayList.get(position).getUrl();
holder.setImage(url);
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent sharing = new Intent (Intent.ACTION_SEND);
sharing.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
sharing.setType("text/plain");
String subject = "Hey Man just look at this coll meme click the link " +url;
sharing.putExtra(Intent.EXTRA_TEXT,subject);
context.startActivity(Intent.createChooser(sharing,"Shring using"));
}
});
holder.buttonDownload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
downloadImage(url);
}
});
}
#Override
public int getItemCount() {
return modelArrayList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
ImageView imageView;
Button button,buttonDownload;
public ViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.imageView);
button = itemView.findViewById(R.id.button);
buttonDownload = itemView.findViewById(R.id.btn_download);
}
void setImage(String link){
Glide.with(context).load(link).into(imageView);
}
}
void downloadImage(String imageURL){
String dirPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + "memebook" + "/";
final File dir = new File(dirPath);
final String fileName = imageURL.substring(imageURL.lastIndexOf('/') + 1);
Glide.with(context)
.load(imageURL)
.into(new CustomTarget<Drawable>() {
#Override
public void onResourceReady(#NonNull Drawable resource, #Nullable Transition<? super Drawable> transition) {
Bitmap bitmap = ((BitmapDrawable)resource).getBitmap();
Toast.makeText(context, "Saving Image...", Toast.LENGTH_SHORT).show();
saveImage(bitmap, dir, fileName);
}
#Override
public void onLoadCleared(#Nullable Drawable placeholder) {
}
#Override
public void onLoadFailed(#Nullable Drawable errorDrawable) {
super.onLoadFailed(errorDrawable);
Toast.makeText(context, "Failed to Download Image! Please try again later.", Toast.LENGTH_SHORT).show();
}
});
}
private void saveImage(Bitmap image, File storageDir, String imageFileName) {
boolean successDirCreated = false;
if (!storageDir.exists()) {
successDirCreated = storageDir.mkdir();
}
successDirCreated = true;
if (successDirCreated) {
File imageFile = new File(storageDir, imageFileName);
String savedImagePath = imageFile.getAbsolutePath();
try {
OutputStream fOut = new FileOutputStream(imageFile);
image.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
fOut.close();
Toast.makeText(context, "Image Saved!", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(context, "Error while saving image!", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}else{
Toast.makeText(context, "Error", Toast.LENGTH_SHORT).show();
}
}
}

Set imageview bitmap in callback listener

So I have a CameraFragment which is called from MainFragment.The problem is I am using a custom Listener to pass the image Data to MainFragment.java.Here is how I call the CameraFragment.java
In MainFragment.java:
public static class MainFragment extends Fragment implements CameraFragment.CameraFragmentHolder.CameraListener {
ImageView mImageView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
mImageView = (ImageView) rootView.findViewById(R.id.image_view);
return rootView;
}
private OnClickListener onCameraFragmentClicked = new OnClickListener() {
#Override
public void onClick(View v) {
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.container, CameraFragment.CameraFragmentHolder.newInstance(MainFragmentHolder.this, 0, false));
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
};
#Override
public void onImageSaved(byte[] data) {
if (data != null) {
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
mImageView.setImageBitmap(bitmap);
}
} else {
Log.v(TAG, "Didn't get any result");
}
}
}
Then in CameraFragment.java I implement the following:
CameraFragment.java
private byte[] mCameraData;
private CameraListener mListener;
public interface CameraListener {
public void onImageSaved(byte[] data);
}
private OnClickListener mDoneButtonClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
if (mCameraData != null) {
removeCameraView();
sendImageDataToListener();
} else {
mCamera = null;
removeCameraView();
}
}
};
//Send image back to Listener
private void sendImageDataToListener() {
if (mCameraData != null) {
mListener.onImageSaved(mCameraData);
} else {
Log.v("CAMERA IMAGE ERROR:", "NO IMAGE DATA");
}
}
private void removeCameraView() {
getActivity().getSupportFragmentManager().popBackStack();
}
My problem is in MainFragment in the CallBackListener when I try to setImageBitmap nothing happens.
So #Selvin it 's actually possible. What I did was onViewStateRestored. I read over the android API a bit. This shouldn't give any problems but I 'm still skeptical about it since I' ve not fully tested it.i modified the MainFragment.java as follows.
In the MainFragment.java:
Bitmap cameraImage;
#Override
public void onViewStateRestored(Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
if (cameraImage != null) {
mImageView.setImageBitmap(cameraImage);
}
}
#Override
public void onImageSaved(byte[] data) {
if (data != null) {
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
cameraImage = bitmap;
}
} else {
Log.v(TAG, "Didn't get any result");
}

Fragment having a GridView to show images from url path

I'm trying to make a gridview that shows images and So it shows the gridview but no images, if clicked it boxes the gridview pops out the link. i got no idea why my images is missing on the gridview...
heres my fragment class
public class FragmentD extends Fragment {
public FragmentD(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_d, container, false);
try {
EditText main_searchField = (EditText) rootView.findViewById(R.id.editText_search_d);
String main_search = main_searchField.getText().toString();
Spinner main_categoryField = (Spinner) rootView.findViewById(R.id.spinner_d);
String category = main_categoryField.getSelectedItem().toString();
GridView main_gridviewField = (GridView) rootView.findViewById(R.id.gridView_main);
main_gridviewField.setAdapter(new MyGridViewAdapter(getActivity()));
main_gridviewField.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View view, int position,long arg3) {
Toast.makeText(getActivity(), MyGridViewConfig.getResim_list().
get(position), Toast.LENGTH_SHORT).show();
}
});
if(main_gridviewField.isActivated()){
ImageView sad_face = (ImageView)getActivity().findViewById(R.id.imageView_main_sadface);
sad_face.setVisibility(View.INVISIBLE);
TextView nosuchdata = (TextView)getActivity().findViewById(R.id.textView_main_nodatafound);
nosuchdata.setVisibility(View.INVISIBLE);
}
} catch (Exception e){
Toast.makeText(getActivity(), "EPIC FAIL", Toast.LENGTH_LONG).show();
}
//new search_mainActivity(getActivity()).execute(main_search, category);
return rootView;
}
}
heres my adapter
public class MyGridViewAdapter extends BaseAdapter implements ListAdapter {
private Context context;
public MyGridViewAdapter(Context context) {
super();
this.context = context;
MyGridViewConfig.addImageUrls();
}
public int getCount() {
return MyGridViewConfig.getResim_list().size();
}
public Object getItem(int position) {
return MyGridViewConfig.getResim_list().get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if(convertView==null)
{
imageView=new ImageView(context);
imageView.setLayoutParams(new GridView.LayoutParams(100,100));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(5,5,5,5);
}else{
imageView=(ImageView)convertView;
}
imageView.setImageDrawable(LoadImageFromURL(MyGridViewConfig.
getResim_list().get(position)));
return imageView;
}
private Drawable LoadImageFromURL(String url)
{
try
{
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src");
return d;
}catch (Exception e) {
System.out.println(e);
return null;
}
}
}
heres my config java
public class MyGridViewConfig {
private static ArrayList<String> resim_list=new ArrayList<String>();
public static ArrayList<String> getResim_list() {
return resim_list;
}
public static void setResim_list(ArrayList<String> resim_list) {
MyGridViewConfig.resim_list = resim_list;
}
public static void addImageUrls(){
// Here you have to specify your image url path
resim_list.add("http://fc08.deviantart.net/fs71/f/2010/319/d/6/neko_chibi__s_by_alykun17-d32y2v5.jpg");
resim_list.add("http://fc08.deviantart.net/fs71/f/2010/319/d/6/neko_chibi__s_by_alykun17-d32y2v5.jpg");
resim_list.add("http://fc08.deviantart.net/fs71/f/2010/319/d/6/neko_chibi__s_by_alykun17-d32y2v5.jpg");
resim_list.add("http://fc08.deviantart.net/fs71/f/2010/319/d/6/neko_chibi__s_by_alykun17-d32y2v5.jpg");
resim_list.add("http://fc08.deviantart.net/fs71/f/2010/319/d/6/neko_chibi__s_by_alykun17-d32y2v5.jpg");
resim_list.add("http://fc08.deviantart.net/fs71/f/2010/319/d/6/neko_chibi__s_by_alykun17-d32y2v5.jpg");
}
}
You can't download the images on your main UI thread, so do it in an AsyncTask. Create this class:
class LoadImageTask extends AsyncTask<String, Void, Drawable > {
public LoadImageTask(ImageView iv)
{
imageView = iv;
}
ImageView imageView;
protected Drawable doInBackground(String... urls) {
try {
URLConnection connection = new URL(urls[0]).openConnection();
connection.connect();
InputStream is = (InputStream) connection.getContent();
Drawable d = Drawable.createFromStream(is, "src");
return d;
} catch (Exception e) {
// e.printStackTrace();
return null;
}
}
protected void onPostExecute(Drawable drawable) {
if(drawable != null)
imageView.setImageDrawable(drawable);
}
}
Then change your getView() function to use the AsyncTask instead of LoadImageFromURL:
// imageView.setImageDrawable(LoadImageFromURL(MyGridViewConfig.
// getResim_list().get(position)));
new LoadImageTask(imageView).execute(MyGridViewConfig.getResim_list().get(position));
are you set android.permission.INTERNET permission?

How to set parsed image as background instead of src

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);
}
}

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