Android Gallery option for setting wallpaper - android

This is the project code which is gallery including 4 pictures. I set an option menu which will set picture as a wallpaper. I try to run it works but when i select the "Set as Wallpaper"(menuSet) it is forced to close.
private ImageView foto;
private Gallery gallery;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_naruto_hd_wallpapers);
gallery = (Gallery) findViewById(R.id.gallery);
foto = (ImageView) findViewById(R.id.imageView1);
gallery.setAdapter(new ImageAdapter(this));
gallery.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
switch(position) {
case 0: foto.setImageResource(R.drawable.ornek1); break;
case 1: foto.setImageResource(R.drawable.ornek2); break;
case 2: foto.setImageResource(R.drawable.ornek3); break;
case 3: foto.setImageResource(R.drawable.ornek4); break;
}
}
});
}
public class ImageAdapter extends BaseAdapter {
int mGalleryItemBackground;
private Context mContext;
private Integer[] mImageIds = {
R.drawable.ornek1,
R.drawable.ornek2,
R.drawable.ornek3,
R.drawable.ornek4,
};
public ImageAdapter(Context c) {
mContext = c;
TypedArray attr = mContext.obtainStyledAttributes(R.styleable.GaleriOlusturma);
mGalleryItemBackground = attr.getResourceId(
R.styleable.GaleriOlusturma_android_galleryItemBackground, 0);
attr.recycle();
}
public int getCount() {
return mImageIds.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(mContext);
imageView.setImageResource(mImageIds[position]);
imageView.setLayoutParams(new Gallery.LayoutParams(150, 100));
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setBackgroundResource(mGalleryItemBackground);
return imageView;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.menuSet:
Bitmap mBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.ornek1);
WallpaperManager myWallpaperManager = WallpaperManager.getInstance(getApplicationContext());
try {
myWallpaperManager.setBitmap(mBitmap);
Toast.makeText(NarutoHdWallpapers.this, "Wallpaper set", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(NarutoHdWallpapers.this, "Error setting wallpaper", Toast.LENGTH_SHORT).show();
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
If i change these blocks into a simple toast message it works fine.
Bitmap mBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.ornek1);
WallpaperManager myWallpaperManager = WallpaperManager.getInstance(getApplicationContext());
try {
myWallpaperManager.setBitmap(mBitmap);
Toast.makeText(NarutoHdWallpapers.this, "Wallpaper set", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(NarutoHdWallpapers.this, "Error setting wallpaper", Toast.LENGTH_SHORT).show();
}
**Note : I put the permission into a manifest

Related

images not appearing in gridView but after keyboard actived

i have two activites,transporting arraylist imageurls to activity AddProductActivity from activity Sdcard. The Sdcard.java code is:
public class Sdcard extends Activity {
private ArrayList<String> imageUrls;
private DisplayImageOptions options;
private ImageAdapter imageAdapter;
ImageLoader imageLoader;
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photoalbum);
getActionBar();
getActionBar().setHomeButtonEnabled(true);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setDisplayShowTitleEnabled(true);
getActionBar().setTitle("select image");
final String[] columns = { MediaStore.Images.Media.DATA,
MediaStore.Images.Media._ID };
final String orderBy = MediaStore.Images.Media.DATE_TAKEN;
Cursor imagecursor = managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null,
null, orderBy + " DESC");
this.imageUrls = new ArrayList<String>();
for (int i = 0; i < imagecursor.getCount(); i++) {
imagecursor.moveToPosition(i);
int dataColumnIndex = imagecursor
.getColumnIndex(MediaStore.Images.Media.DATA);
imageUrls.add(imagecursor.getString(dataColumnIndex));
System.out.println("=====> Array path => " + imageUrls.get(i));
}
options = new DisplayImageOptions.Builder()
.showImageForEmptyUri(R.drawable.ic_launcher)
.showImageOnFail(R.drawable.ic_error_loadingsmall)
.cacheInMemory(true)
.cacheOnDisk(true)
.considerExifParams(true)
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
imageLoader = ImageLoader.getInstance();
imageLoader.init(ImageLoaderConfiguration.createDefault(this));
imageAdapter = new ImageAdapter(this, imageUrls);
GridView gridView = (GridView) findViewById(R.id.album_gridview);
gridView.setAdapter(imageAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.select_image, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Intent intent = new Intent(Sdcard.this, AddProductActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return true;
case R.id.select_image_submit:
ArrayList<String> selectedItems = imageAdapter.getCheckedItems();
if (selectedItems.size() == 0) {
Toast.makeText(getBaseContext(), "no selected image!", Toast.LENGTH_LONG)
.show();
} else if (selectedItems.size() > 9) {
Toast.makeText(getBaseContext(), "must below 9 images", Toast.LENGTH_LONG)
.show();
} else {
Intent intent1 = new Intent(this, AddProductActivity.class);
intent1.putStringArrayListExtra("select_image", selectedItems);
intent1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
setResult(9392,intent1);
finish();
}
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onStop() {
imageLoader.stop();
super.onStop();
}
public class ImageAdapter extends BaseAdapter {
ArrayList<String> mList;
LayoutInflater mInflater;
Context mContext;
SparseBooleanArray mSparseBooleanArray;
public ImageAdapter(Context context, ArrayList<String> imageList) {
// TODO Auto-generated constructor stub
mContext = context;
mInflater = LayoutInflater.from(mContext);
mSparseBooleanArray = new SparseBooleanArray();
mList = new ArrayList<String>();
this.mList = imageList;
}
public ArrayList<String> getCheckedItems() {
ArrayList<String> mTempArry = new ArrayList<String>();
for (int i = 0; i < mList.size(); i++) {
if (mSparseBooleanArray.get(i)) {
mTempArry.add(mList.get(i));
}
}
return mTempArry;
}
#Override
public int getCount() {
return imageUrls.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
final ProgressBar spinner = (ProgressBar) findViewById(R.id.loading_image_fromsdcard);
if (convertView == null) {
convertView = mInflater.inflate(
R.layout.photoalbum_gridview_item, null);
}
CheckBox mCheckBox = (CheckBox) convertView
.findViewById(R.id.select_image_cb);
final ImageView imageView = (ImageView) convertView
.findViewById(R.id.photo_img_view);
imageLoader.displayImage("file://" + imageUrls.get(position),
imageView, options, new SimpleImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
spinner.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingFailed(String imageUri, View view,
FailReason failReason) {
String message = null;
switch (failReason.getType()) {
case IO_ERROR:
message = "Input/Output error";
break;
case DECODING_ERROR:
message = "Image can't be decoded";
break;
case NETWORK_DENIED:
message = "Downloads are denied";
break;
case OUT_OF_MEMORY:
message = "Out Of Memory error";
break;
case UNKNOWN:
message = "Unknown error";
break;
}
Toast.makeText(Sdcard.this, message,
Toast.LENGTH_SHORT).show();
spinner.setVisibility(View.GONE);
}
#Override
public void onLoadingComplete(String imageUri,
View view, Bitmap loadedImage) {
spinner.setVisibility(View.GONE);
Animation anim =AnimationUtils.loadAnimation(Sdcard.this,
R.anim.push_left_in);
imageView.setAnimation(anim);
anim.start();
}
});
imageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(),
"selected item is " + position, Toast.LENGTH_LONG)
.show();
}
});
mCheckBox.setTag(position);
mCheckBox.setChecked(mSparseBooleanArray.get(position));
mCheckBox.setOnCheckedChangeListener(mCheckedChangeListener);
return convertView;
}
OnCheckedChangeListener mCheckedChangeListener = new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
mSparseBooleanArray.put((Integer) buttonView.getTag(),
isChecked);
}
};
}
}
and activity AddProductActivity recive imageurls from activity Sdcard and display image on it, like the code
public class AddProductActivity extends Activity{
GridView gridView;
private String image;
private static final int GALLERY_REQUEST = 9390;
private DisplayImageOptions options;
ImageLoader imageLoader;
private ArrayList<String> selectImageUrls;
String[] f;
private SelectImageAdapter selectImageAdapter;
ImageView imageView;
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_product);
final ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(false);
// actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle("add product");
options = new DisplayImageOptions.Builder()
.showStubImage(R.drawable.ic_launcher)
.showImageOnFail(R.drawable.ic_error_loadingsmall)
.cacheInMemory().cacheOnDisc().build();
gridView = (GridView) findViewById(R.id.select_image_gridview);
this.selectImageUrls = new ArrayList<String>();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.add_product, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Intent intent = new Intent(AddProductActivity.this,
MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return true;
case R.id.action_upload_picture:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void onSelectFromSD(MenuItem item) {
Intent selectFromSdcard = new Intent(AddProductActivity.this,Sdcard.class);
startActivityForResult(selectFromSdcard, GALLERY_REQUEST);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
System.out.println("[requestCode=" + requestCode + "]" + "[resultCode="
+ resultCode + "]");
if (requestCode == GALLERY_REQUEST && resultCode == 9392
&& data != null) {
// image = data.getData().toString();
selectImageUrls = data.getStringArrayListExtra("select_image");
if (selectImageUrls != null) {
// System.out.println("recieve =" + selectImageUrls.size());
f = (String[]) selectImageUrls
.toArray(new String[selectImageUrls.size()]);
if (selectImageAdapter == null) {
selectImageAdapter = new SelectImageAdapter(this,
selectImageUrls);
imageLoader.init(ImageLoaderConfiguration
.createDefault(this));
gridView.setAdapter(selectImageAdapter);
selectImageAdapter.notifyDataSetChanged();
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
startFullImagePagerActivity(position);
}
});
} else {
selectImageAdapter.notifyDataSetChanged();
}
} else {
return;
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
protected void startFullImagePagerActivity(int position) {
// TODO Auto-generated method stub
Intent i = new Intent(AddProductActivity.this,
FullScreenViewActivity.class);
i.putStringArrayListExtra("position_url", selectImageUrls);
i.putExtra("position", position);
startActivity(i);
}
public class SelectImageAdapter extends BaseAdapter {
LayoutInflater mInflater;
Context mContext;
public SelectImageAdapter(Context context, ArrayList<String> imageList) {
// TODO Auto-generated constructor stub
mContext = context;
mInflater = LayoutInflater.from(mContext);
imageLoader = ImageLoader.getInstance();
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return selectImageUrls.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if (convertView == null) {
convertView = mInflater.inflate(R.layout.select_image, null);
}
final ImageView imageView = (ImageView) convertView.findViewById(R.id.select_images);
final ProgressBar spinner = (ProgressBar)convertView.findViewById(R.id.select_image_loading);
//final ViewAnimator animator = (ViewAnimator)convertView.findViewById(R.id.animator);
imageLoader.displayImage("file://" + selectImageUrls.get(position), imageView,
options, new SimpleImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
spinner.setVisibility(View.VISIBLE);
//animator.setDisplayedChild(1);
}
#Override
public void onLoadingFailed(String imageUri, View view,
FailReason failReason) {
String message = null;
switch (failReason.getType()) {
case IO_ERROR:
message = "Input/Output error";
break;
case DECODING_ERROR:
message = "Image can't be decoded";
break;
case NETWORK_DENIED:
message = "Downloads are denied";
break;
case OUT_OF_MEMORY:
message = "Out Of Memory error";
break;
case UNKNOWN:
message = "Unknown error";
break;
}Toast.makeText(AddProductActivity.this, message,Toast.LENGTH_SHORT).show();
spinner.setVisibility(View.GONE);
//animator.setDisplayedChild(0);
}
#Override
public void onLoadingComplete(String imageUri,
View view, Bitmap loadedImage) {
// Animation anim =
// AnimationUtils.loadAnimation(Sdcard.this,
// R.anim.push_left_in);
// imageView.setAnimation(anim);
// anim.start();
spinner.setVisibility(View.GONE);
notifyDataSetChanged();//followed with Armin's suggestion
}
});
return convertView;
}
}
but when it returned activity AddProductActivity,the images did not appear in gridview ,if i clicked the editorText to active the keyboard,the images appearing in the gridview. So i am puzzled,waiting for some suggestions, thanks!
image url :http://i61.tinypic.com/2ch9onq.png
actived keyboard image appearing: http://i61.tinypic.com/2l8uumc.png
if i used this getView() method in AddProductActivity,it works fine.
#Override
public View getView(final int position, View convertView, ViewGroup
parent)
{
if (convertView == null){
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(245, 150));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
}
else {
imageView = (ImageView) convertView;
}
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = false ;
bmOptions.inSampleSize = 4;
bmOptions.inPurgeable = true ;
Bitmap bitmap = BitmapFactory.decodeFile(selectImageUrls.get(position), bmOptions);
imageView.setImageBitmap(bitmap);
return imageView;
}
but it does not smooth when it transfored the imageurls back to AddProductActivity.
Try to replace adapter code.
public class SelectImageAdapter extends BaseAdapter {
Context mContext;
ViewHolder holder;
public SelectImageAdapter(Context context, ArrayList<String> imageList) {
// TODO Auto-generated constructor stub
mContext = context;
imageLoader = ImageLoader.getInstance();
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return selectImageUrls.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(mContext).inflate(R.layout.select_image, null);
holder.imageView = (ImageView) convertView.findViewById(R.id.select_images);
holder.spinner = (ProgressBar)convertView.findViewById(R.id.select_image_loading);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
//final ViewAnimator animator = (ViewAnimator)convertView.findViewById(R.id.animator);
imageLoader.displayImage("file://" + selectImageUrls.get(position),holder.imageView,
options, new SimpleImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
holder.spinner.setVisibility(View.VISIBLE);
//animator.setDisplayedChild(1);
}
#Override
public void onLoadingFailed(String imageUri, View view,
FailReason failReason) {
String message = null;
switch (failReason.getType()) {
case IO_ERROR:
message = "Input/Output error";
break;
case DECODING_ERROR:
message = "Image can't be decoded";
break;
case NETWORK_DENIED:
message = "Downloads are denied";
break;
case OUT_OF_MEMORY:
message = "Out Of Memory error";
break;
case UNKNOWN:
message = "Unknown error";
break;
}
Toast.makeText(AddProductActivity.this, message,Toast.LENGTH_SHORT).show();
holder.spinner.setVisibility(View.GONE);
//animator.setDisplayedChild(0);
}
#Override
public void onLoadingComplete(String imageUri,
View view, Bitmap loadedImage) {
// Animation anim =
// AnimationUtils.loadAnimation(Sdcard.this,
// R.anim.push_left_in);
// imageView.setAnimation(anim);
// anim.start();
holder.spinner.setVisibility(View.GONE);
}
});
return convertView;
}
class ViewHolder {
ImageView imageView;
ProgressBar spinner;
}
}
I believe what is missing in the code is a call to notifyDataSetChanged() after the images are loaded (in onLoadingComplete() callback of the listener).
The way the above code is written, if notifyDataSetChanged() is called in onLoadingComplete(), it will solve the problem that you have.
However, calling notifyDataSetChanged() every time in that callback method, may degrade the performance significantly. The more images you have, the more the performance may drop.
If you do observe performance drop by doing the above, to solve it, I would suggest using an image refresh helper mechanism. This way you can either call notifyDataSetChanged():
after n images have been loaded
or after every t seconds has passed
I hope the information above helps you.

ListView animation with images and text that runs on Froyo

I'd like to implement a ListView animation with an ImageView on the left and text on the right and I'm using an Adapter that gives a ListView the animations, and they're awesome, so I'd like to know how I can modify the class, particularly, the adapter to show a ListView with an ImageView on the left. Here's the class:
public class Post extends SherlockActivity implements
PullToRefreshAttacher.OnRefreshListener, OnItemLongClickListener,
OnItemClickListener {
private PullToRefreshAttacher mPullToRefreshAttacher;
private ListView listview;
private DisplayMetrics metrics;
ActionMode mMode;
Animation animation;
Intent i;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
sessionCheck();
}
private void sessionCheck() {
// TODO Auto-generated method stub
Session session = Session.getActiveSession();
if (session != null && session.isOpened()) {
// Get the user's data
listview = new ListView(this);
listview.setFadingEdgeLength(0);
ArrayList<String> strings = new ArrayList<String>();
for (int i = 0; i < 100; i++) {
strings.add("That's list number " + (i + 1));
}
MainAdapter mAdapter = new MainAdapter(this, strings, metrics);
listview.setAdapter(mAdapter);
listview.setOnItemLongClickListener(this);
listview.setOnItemClickListener(this);
setContentView(listview);
pullToRefresh();
} else {
Toast.makeText(getApplicationContext(), "Please log in first",
Toast.LENGTH_LONG).show();
i = new Intent(getApplicationContext(), StartBase.class);
startActivity(i);
}
}
private void pullToRefresh() {
// TODO Auto-generated method stub
PullToRefreshAttacher.Options ptrOptions = new PullToRefreshAttacher.Options();
ptrOptions.refreshScrollDistance = 0.6f;
ptrOptions.headerLayout = R.layout.customised_header;
ptrOptions.headerTransformer = new CustomisedHeaderTransformer();
mPullToRefreshAttacher = PullToRefreshAttacher.get(this, ptrOptions);
PullToRefreshAttacher.ViewDelegate handler = new AbsListViewDelegate();
mPullToRefreshAttacher.addRefreshableView(listview, handler, this);
}
#Override
public void onRefreshStarted(View view) {
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Notify PullToRefreshAttacher that the refresh has finished
mPullToRefreshAttacher.setRefreshComplete();
}
}.execute();
}
static class CustomisedHeaderTransformer extends
PullToRefreshAttacher.HeaderTransformer {
private View mHeaderView;
private TextView mMainTextView;
private TextView mProgressTextView;
#Override
public void onViewCreated(Activity activity, View headerView) {
mHeaderView = headerView;
mMainTextView = (TextView) headerView.findViewById(R.id.ptr_text);
mProgressTextView = (TextView) headerView
.findViewById(R.id.ptr_text_secondary);
}
#Override
public void onReset() {
mMainTextView.setVisibility(View.VISIBLE);
mMainTextView.setText(R.string.pull_to_refresh_pull_label);
mProgressTextView.setVisibility(View.GONE);
mProgressTextView.setText("");
}
#Override
public void onPulled(float percentagePulled) {
mProgressTextView.setVisibility(View.VISIBLE);
mProgressTextView
.setText(Math.round(100f * percentagePulled) + "%");
}
#Override
public void onRefreshStarted() {
mMainTextView.setText(R.string.pull_to_refresh_refreshing_label);
mProgressTextView.setVisibility(View.GONE);
}
#Override
public void onReleaseToRefresh() {
mMainTextView.setText(R.string.pull_to_refresh_release_label);
}
#Override
public void onRefreshMinimized() {
// In this header transformer, we will ignore this call
}
#Override
public boolean showHeaderView() {
final boolean changeVis = mHeaderView.getVisibility() != View.VISIBLE;
if (changeVis) {
mHeaderView.setVisibility(View.VISIBLE);
}
return changeVis;
}
#Override
public boolean hideHeaderView() {
final boolean changeVis = mHeaderView.getVisibility() != View.GONE;
if (changeVis) {
mHeaderView.setVisibility(View.GONE);
}
return changeVis;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.main, menu);
SubMenu subMenu1 = menu.addSubMenu("Categories");
subMenu1.add(0, 1, Menu.NONE, "One");
subMenu1.add(0, 2, Menu.NONE, "Two");
subMenu1.add(0, 3, Menu.NONE, "Three");
subMenu1.add(0, 4, Menu.NONE, "Four");
subMenu1.add(0, 5, Menu.NONE, "Five");
subMenu1.add(0, 6, Menu.NONE, "Six");
MenuItem subMenu1Item = subMenu1.getItem();
subMenu1Item.setIcon(android.R.drawable.ic_dialog_info);
subMenu1Item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS
| MenuItem.SHOW_AS_ACTION_WITH_TEXT);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 1:
Toast.makeText(getApplicationContext(), "That's selected",
Toast.LENGTH_LONG).show();
break;
case 2:
Toast.makeText(getApplicationContext(), "That's selected",
Toast.LENGTH_LONG).show();
break;
case 3:
Toast.makeText(getApplicationContext(), "That's selected",
Toast.LENGTH_LONG).show();
break;
case 4:
Toast.makeText(getApplicationContext(), "That's selected",
Toast.LENGTH_LONG).show();
break;
case 5:
Toast.makeText(getApplicationContext(), "That's selected",
Toast.LENGTH_LONG).show();
break;
case 6:
Toast.makeText(getApplicationContext(), "That's selected",
Toast.LENGTH_LONG).show();
break;
case R.id.action_account:
i = new Intent(getApplicationContext(), Account.class);
startActivity(i);
break;
case R.id.action_logout:
Toast.makeText(getApplicationContext(), "Working on this...",
Toast.LENGTH_LONG).show();
break;
}
return super.onOptionsItemSelected(item);
}
public class MainAdapter extends ArrayAdapter<String> {
private Context context;
private LayoutInflater mInflater;
private ArrayList<String> strings;
private DisplayMetrics metrics_;
private class Holder {
public TextView textview;
}
public MainAdapter(Context context, ArrayList<String> strings,
DisplayMetrics metrics) {
super(context, 0, strings);
this.context = context;
this.mInflater = (LayoutInflater) this.context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.strings = strings;
this.metrics_ = metrics;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
final String str = this.strings.get(position);
final Holder holder;
if (convertView == null) {
convertView = mInflater.inflate(
android.R.layout.simple_list_item_1, null);
convertView.setBackgroundColor(0xFF202020);
holder = new Holder();
holder.textview = (TextView) convertView
.findViewById(android.R.id.text1);
holder.textview.setTextColor(0xFFFFFFFF);
holder.textview.setBackgroundResource(R.drawable.list_selector);
convertView.setTag(holder);
} else {
holder = (Holder) convertView.getTag();
}
holder.textview.setText(str);
animation = animation = AnimationUtils.loadAnimation(context,
R.anim.push_left_in);
animation.setDuration(200);
convertView.startAnimation(animation);
animation = null;
return convertView;
}
}
private final class AnActionModeOfEpicProportions implements
ActionMode.Callback {
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
menu.add("One").setIcon(android.R.drawable.ic_dialog_info)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
menu.add("Two").setIcon(android.R.drawable.ic_dialog_info)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
menu.add("Three").setIcon(android.R.drawable.ic_dialog_info)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
menu.add("Four").setIcon(android.R.drawable.ic_dialog_info)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
menu.add("Five").setIcon(android.R.drawable.ic_dialog_info)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
menu.add("Six").setIcon(android.R.drawable.ic_dialog_info)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
Toast.makeText(getApplicationContext(), "Got click: " + item,
Toast.LENGTH_SHORT).show();
mode.finish();
return true;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
}
}
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
mMode = startActionMode(new AnActionModeOfEpicProportions());
return false;
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "List item selected",
Toast.LENGTH_LONG).show();
}
}
I've just copy pasted everything :-) The adapter you're looking for is MainAdapter...way down there. Please help me out.
You should modify this part:
if (convertView == null) {
convertView = mInflater.inflate(android.R.layout.simple_list_item_1, null);
convertView.setBackgroundColor(0xFF202020);
holder = new Holder();
holder.textview = (TextView) convertView.findViewById(android.R.id.text1);
holder.textview.setTextColor(0xFFFFFFFF);
holder.textview.setBackgroundResource(R.drawable.list_selector);
convertView.setTag(holder);
} else {
holder = (Holder) convertView.getTag();
}
So, android.R.layout.simple_list_item_1 is the layout that is used for list items. It contains only one TextView. To add ImageView you should use custom list item layout, for example this one:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:minHeight="?android:attr/listPreferredItemHeight">
<ImageView
android:id="#+id/pic"
android:layout_width="48dp"
android:layout_height="48dp"
android:src="#drawable/your_custom_image"
android:scaleType="centerCrop"/>
<TextView
android:id="#+id/text"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginLeft="8dp"/>
</LinearLayout>
Put it in XML file into res\layout directory and name it custom_list_item.xml. Then just replace android.R.layout.simple_list_item_1 with R.layout.custom_list_item and android.R.id.text1 with R.id.text in your code.
Thats all! Animation stays the same.
If you want to change image for each list item then you also should:
add ImageView imageView field into Holder class
add
holder.imageView = (ImageView) convertView.findViewById(R.id.pic);
after
holder.textview.setBackgroundResource(R.drawable.list_selector);
add
holder.imageView.setImage(R.drawable.my_drawable);
after
holder.textview.setText(str);
Change R.drawable.my_drawable to your custom drawable if needed.

Set Wallpaper from gallery according to position

I have a Gallery and an imageView as in this pic: http://i50.tinypic.com/2e6h2so.png
and i need button1 to set the current image as wallpaper
I am having a problem in setResource
myWallpaperManager.setResource(mImageIds[position]);
This is my code:
public class batman extends Activity implements OnClickListener{
Button set;
private int[] mImageIds = {
R.drawable.b,
R.drawable.b1,
R.drawable.b2,
R.drawable.b3,
R.drawable.b4,
R.drawable.b5,
R.drawable.b6,
R.drawable.b7,
R.drawable.b8,
R.drawable.b9,
R.drawable.b10,
R.drawable.b11,
R.drawable.b12,
R.drawable.b13,
R.drawable.b14,
R.drawable.b15,
R.drawable.b16,
R.drawable.b17,
R.drawable.b18,
R.drawable.b19,
R.drawable.b20,
R.drawable.b21,
R.drawable.b22,
R.drawable.b23,
R.drawable.b24,
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.batman);
set=(Button)findViewById(R.id.button1);
set.setOnClickListener(this);
Gallery g = (Gallery) findViewById(R.id.gallery);
g.setAdapter(new ImageAdapter(this));
g.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick
(AdapterView<?> parent, View v, int position, long id) {
ImageView imageView =(ImageView)findViewById(R.id.imageView1);
imageView.setImageResource(mImageIds[position]);
}
});
}
public class ImageAdapter extends BaseAdapter {
int mGalleryItemBackground;
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
TypedArray a = c.obtainStyledAttributes(R.styleable.GalleryA);
mGalleryItemBackground = a.getResourceId(
R.styleable.GalleryA_android_galleryItemBackground, 0);
a.recycle();
}
public int getCount() {
return mImageIds.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(mContext);
i.setImageResource(mImageIds[position]);
i.setLayoutParams(new Gallery.LayoutParams(150, 100));
i.setScaleType(ImageView.ScaleType.FIT_XY);
i.setBackgroundResource(mGalleryItemBackground);
return i;
}
}
public void onClick(View arg0) {
// TODO Auto-generated method stub
int id=arg0.getId();
if(id==R.id.button1)
{
WallpaperManager myWallpaperManager
= WallpaperManager.getInstance(getApplicationContext());
try {
myWallpaperManager.setResource(mImageIds[position]);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
First you need this permission in your manifest:
“android.permission.SET_WALLPAPER”
ImageAdapter i = (ImageAdapter)parent.getAdapter();
Bitmap mBitmap = BitmapFactory.decodeResource(getResources(),(int)i.getItemId(position));
WallpaperManager myWallpaperManager = WallpaperManager.getInstance(getApplicationContext());
try {
myWallpaperManager.setBitmap(mBitmap);
Toast.makeText(MainActivity.this, "Wallpaper set", Toast.LENGTH_SHORT).show();
}
catch (IOException e)
{
Toast.makeText(MainActivity.this, "Error setting wallpaper", Toast.LENGTH_SHORT).show();
}
}
});
}
First You have to add the SET_WALLPAPER permission to your AndroidManifest.xml
<manifest xlmns:android...>
...
<uses-permission android:name="android.permission.SET_WALLPAPER" />
</manifest>
And then change your Button ClickListener as below:
ImageAdapter image = (ImageAdapter)parent.getAdapter();
Bitmap mBitmap = BitmapFactory.decodeResource(getResources(),mImageIds[pos]); <----Try by changing this line.
WallpaperManager m_manager = WallpaperManager.getInstance(getApplicationContext());
try {
m_manager.setBitmap(mBitmap);
}
catch (IOException e)
{}
}
});
}

How do I populate a gallery and Imageswitcher quickly?

public class MainActivity extends Activity implements ViewSwitcher.ViewFactory, OnItemSelectedListener {
private Gallery gallery;
private ImageSwitcher imageSwitcher;
private ImageAdapter ia;
private int res_id;
private Bitmap mBitmap;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gallery = (Gallery) findViewById(R.id.gallery);
imageSwitcher = (ImageSwitcher) findViewById(R.id.image_switcher);
imageSwitcher.setFactory(this);
imageSwitcher.setInAnimation(AnimationUtils.loadAnimation(this,
android.R.anim.fade_in));
imageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this,
android.R.anim.fade_out));
ia = new ImageAdapter(this);
gallery.setAdapter(ia);
//Event listener
gallery.setOnItemSelectedListener(this);
}
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.layout.menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.menu_save:
mBitmap = BitmapFactory.decodeResource(getResources(),res_id);
String filename = "barca_"+res_id+".jpg";
File sd = Environment.getExternalStorageDirectory();
String full_path=sd.getAbsolutePath()+"/BarcaWallpapers/";
File temp=new File(full_path);
temp.mkdirs();
File dest = new File(temp,filename);
try {
FileOutputStream out = new FileOutputStream(dest);
mBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
Toast.makeText(this, "Saved in Folder "+full_path, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "error", Toast.LENGTH_LONG).show();
}
return true;
case R.id.menu_set_wallpapaer:
final WallpaperManager wallpaperManager = WallpaperManager.getInstance(MainActivity.this);
try{
wallpaperManager.setResource(res_id);
Toast.makeText(this,"Wallpaper Set", Toast.LENGTH_SHORT).show();
}
catch(Exception e)
{
Toast.makeText(this, "error setting wallpaper", Toast.LENGTH_SHORT).show();
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void onNothingSelected(AdapterView<?> parent) {
}
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
int imageResourceId = (Integer) ia.getItem(position);
res_id=imageResourceId;
imageSwitcher.setImageResource(imageResourceId);
}
public View makeView() {
ImageView i = new ImageView(this);
i.setScaleType(ImageView.ScaleType.FIT_CENTER);
i.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
return i;
}
private class ImageAdapter extends BaseAdapter {
private Context context;
private ImageAdapter(Context context) {
this.context = context;
}
private int[] IMAGE_IDS = {
R.drawable.img1,R.drawable.img2,R.drawable.img3,R.drawable.img4,R.drawable.img5,R.drawable.img6,
};
public int getCount() {
return IMAGE_IDS.length;
}
public Object getItem(int position) {
return IMAGE_IDS[position];
}
public long getItemId(int position) {
return IMAGE_IDS[position];
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(context);
imageView.setLayoutParams(new Gallery.LayoutParams(120,120));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(IMAGE_IDS[position]);
return imageView;
}
}
}
I have the above code for a wallpaper app. The activity xml layout file contains a gallery view and a imageswitcher below it in which the user can browse and navigate through the gallery and the corresponding image opens up below in the imageswitcher. User can then set the image as a wallpaper or save to sd card. The above code works perfectly for small images, but fails miserably for large images like the one I intend to have in the app. The app crashes when it runs out of memory(openglrenderer is out of memory). How do I fix this? Pls help me, Ive spent many a hour on this problem.
Thanks

Gallery images from url in android?

I would like to create an image gallery that get pictures from a url..this is my code but is not working...
public class ImagesActivity extends Activity
{
private String[] imageIDs= {"http://lh5.ggpht.com/_mrb7w4gF8Ds/TCpetKSqM1I/AAAAAAAAD2c/Qef6Gsqf12Y/s144-c/_DSC4374%20copy.jpg",
"http://lh5.ggpht.com/_Z6tbBnE-swM/TB0CryLkiLI/AAAAAAAAVSo/n6B78hsDUz4/s144-c/_DSC3454.jpg",
"http://lh3.ggpht.com/_GEnSvSHk4iE/TDSfmyCfn0I/AAAAAAAAF8Y/cqmhEoxbwys/s144-c/_MG_3675.jpg",
"http://lh6.ggpht.com/_Nsxc889y6hY/TBp7jfx-cgI/AAAAAAAAHAg/Rr7jX44r2Gc/s144-c/IMGP9775a.jpg"
};
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.displayview);
Gallery gallery = (Gallery) findViewById(R.id.gallery1);
gallery.setAdapter(new ImageAdapter(this));
gallery.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView parent, View v, int position, long id)
{
// Toast.makeText(getBaseContext(), "pic" + (position + 1) + " selected", Toast.LENGTH_SHORT).show();
//---display the images selected---
ImageView imageView = (ImageView) findViewById(R.id.image1);
imageView.setImageResource(imageIDs[position]);
}
});
}
public class ImageAdapter extends BaseAdapter
{
private Context context;
private int itemBackground;
public ImageAdapter(Context c)
{
context = c;
//---setting the style---
TypedArray a = obtainStyledAttributes(R.styleable.Gallery1);
itemBackground = a.getResourceId(
R.styleable.Gallery1_android_galleryItemBackground, 0);
a.recycle();
}
//---returns the number of images---
public int getCount() {
return imageIDs.length;
}
//---returns the ID of an item---
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
//---returns an ImageView view---
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(context);
imageView.setImageResource(imageIDs[position]);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setLayoutParams(new Gallery.LayoutParams(150, 120));
imageView.setBackgroundResource(itemBackground);
return imageView;
}
}
}
ViewsActivity.java
public class ViewsActivity extends Activity
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.main);
startActivity(new Intent(this, ImagesActivity.class));
}
}
The error is that i cant use imageView.setImageResource(imageIDs[position]); for strings...ant hepl please?
You need to decode the image from the link for example,
URL url = new URL("load your URL");
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
img_downloaded.setImageBitmap(bmp);
Update:
I modified your code, you may try with this,
public class MainActivity extends Activity {
private String[] imageIDs = {
"http://lh5.ggpht.com/_mrb7w4gF8Ds/TCpetKSqM1I/AAAAAAAAD2c/Qef6Gsqf12Y/s144-c/_DSC4374%20copy.jpg",
"http://lh5.ggpht.com/_Z6tbBnE-swM/TB0CryLkiLI/AAAAAAAAVSo/n6B78hsDUz4/s144-c/_DSC3454.jpg",
"http://lh3.ggpht.com/_GEnSvSHk4iE/TDSfmyCfn0I/AAAAAAAAF8Y/cqmhEoxbwys/s144-c/_MG_3675.jpg",
"http://lh6.ggpht.com/_Nsxc889y6hY/TBp7jfx-cgI/AAAAAAAAHAg/Rr7jX44r2Gc/s144-c/IMGP9775a.jpg" };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Gallery gallery = (Gallery) findViewById(R.id.gallery1);
gallery.setAdapter(new ImageAdapter(this));
gallery.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position,
long id) {
// Toast.makeText(getBaseContext(), "pic" + (position + 1) +
// " selected", Toast.LENGTH_SHORT).show();
// ---display the images selected---
ImageView imageView = (ImageView) findViewById(R.id.imageview1);
URL url = null;
try {
url = new URL(imageIDs[position]);
Bitmap bmp = null;
try {
bmp = BitmapFactory.decodeStream(url
.openConnection().getInputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
imageView.setImageBitmap(bmp);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public class ImageAdapter extends BaseAdapter {
private Context context;
private int itemBackground;
public ImageAdapter(Context c) {
context = c;
// ---setting the style---
TypedArray a = obtainStyledAttributes(R.styleable.Gallery1);
itemBackground = a.getResourceId(
R.styleable.Gallery1_android_galleryItemBackground, 0);
a.recycle();
}
// ---returns the number of images---
public int getCount() {
return imageIDs.length;
}
// ---returns the ID of an item---
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
// ---returns an ImageView view---
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(context);
// imageView.setImageResource(imageIDs[position]);
URL url;
try {
url = new URL(imageIDs[position]);
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection()
.getInputStream());
imageView.setImageBitmap(bmp);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setLayoutParams(new Gallery.LayoutParams(150, 120));
imageView.setBackgroundResource(itemBackground);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return imageView;
}
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Gallery
android:id="#+id/gallery1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ImageView
android:id="#+id/imageview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/gallery1" />
</RelativeLayout>
In the getView method:
URL newurl = new URL(imageIDs[position]); //Your URL String.
Bitmap image = BitmapFactory.decodeStream(newurl.openConnection().getInputStream());
imageView.setImageBitmap(image);
In this Gallery Image using url
Answer Click Link

Categories

Resources