I am using the code below to display the device images in a GridView.
But I am getting an image orientation problem while displaying them in the GridView.
Some images are showing in horizontal orientation mode
public class MultiImagePicActivity extends Activity {
GridView mGrid;
static public String[] arrPath,modifiedArrayPath;
private int ids[];
private int count;
static int selectCount;
Activity act=this;
Context ctx=this;
ArrayList<String> imagepaths;
public static int count1 = 0;
public static String classs;
static int maximageselection;
static int width,height;
//int sel=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
//now get Intent Extras
Bundle extras;
if (savedInstanceState == null)
{
//fetching extra data passed with intents in a Bundle type variable
extras = getIntent().getExtras();
if(extras == null)
{ maximageselection= 0;
classs=null;
}
else
{ /* fetching the string passed with intent using ‘extras’*/
maximageselection= extras.getInt("maximage");
classs=extras.getString("From");
}
}
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
width = size.x;
height = size.y;
imagepaths=new ArrayList<String>();
imagepaths.clear();
loadApps();
setContentView(R.layout.grid_1);
mGrid = (GridView) findViewById(R.id.myGrid);
mGrid.setAdapter(new ImageAdapterxtends());
mGrid.setChoiceMode(GridView.CHOICE_MODE_MULTIPLE_MODAL);
mGrid.setMultiChoiceModeListener(new MultiChoiceModeListener());
}
private void loadApps() {
final String[] columns = { MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID };
final String orderBy = MediaStore.Images.Media._ID;
Cursor imagecursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null, null, orderBy);
int image_column_index = imagecursor.getColumnIndex(MediaStore.Images.Media._ID);
this.count = imagecursor.getCount();
this.arrPath = new String[this.count];
ids = new int[count];
for (int i = 0; i <this.count; i++) {
imagecursor.moveToPosition(i);
ids[i] = imagecursor.getInt(image_column_index);
int dataColumnIndex = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);
arrPath[i] = imagecursor.getString(dataColumnIndex);
}
imagecursor.close();
}
#Override
public void onBackPressed() {
setResult(Activity.RESULT_CANCELED);
super.onBackPressed();
}
public class ImageAdapterxtends extends BaseAdapter{
CheckableLayout l;
ImageView i;
#Override
public int getCount() {
// TODO Auto-generated method stub
return arrPath.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return arrPath[position];
}
#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) {
i = new ImageView(MultiImagePicActivity.this);
i.setScaleType(ImageView.ScaleType.FIT_CENTER);
i.setLayoutParams(new ViewGroup.LayoutParams(50, 50));
l = new CheckableLayout(MultiImagePicActivity.this);
l.setLayoutParams(new GridView.LayoutParams(
GridView.LayoutParams.WRAP_CONTENT,
GridView.LayoutParams.WRAP_CONTENT));
l.addView(i);
} else {
l = (CheckableLayout) convertView;
i = (ImageView) l.getChildAt(0);
}
try {
setBitmap(i, ids[position]);
} catch (Throwable e) {
}
return l;
}
}
private void setBitmap(final ImageView iv,final int id) {
new AsyncTask<Void, Void, Bitmap>() {
Bitmap myBitmap;
#Override
protected Bitmap doInBackground(Void... params) {
return MediaStore.Images.Thumbnails.getThumbnail(getApplicationContext().getContentResolver(), id, MediaStore.Images.Thumbnails.MICRO_KIND, null);
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
//iv.setImageBitmap(result);
setMyBitmap(result);
}
public final void setMyBitmap(Bitmap bitmap) {
if (this.myBitmap != null) {
this.myBitmap.recycle();
}
this.myBitmap = bitmap;
iv.getLayoutParams().height = width/3;
iv.getLayoutParams().width = width/3;
iv.setImageBitmap(myBitmap);
}
}.execute();
}
public class CheckableLayout extends FrameLayout implements Checkable {
private boolean mChecked;
public CheckableLayout(Context context) {
super(context);
}
public void setChecked(boolean checked) {
mChecked = checked;
setForeground(checked ? getResources().getDrawable(R.drawable.tr) : null);
}
public boolean isChecked() {
return mChecked;
}
public void toggle() {
setChecked(!mChecked);
}
}
public class MultiChoiceModeListener implements
GridView.MultiChoiceModeListener {
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// Inflate the menu for the CAB
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
//return true;
mode.setTitle("Select Items");
mode.setSubtitle("One item selected");
return true;
}
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return true;
}
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
// Respond to clicks on the actions in the CAB
switch (item.getItemId()) {
case R.id.menu_ok:
if(classs.equals("SliderExistingDetailedActivity")){
Intent i = new Intent();
modifiedArrayPath=imagepaths.toArray(new String[imagepaths.size()]);
i.putExtra("selectedImagepath", modifiedArrayPath);
//i.putExtra("data", selectedPath);
setResult(Activity.RESULT_OK, i);
finish();
}else{
Intent intent=new Intent(MultiImagePicActivity.this, AudioSelectActivity.class);
intent.putExtra("IMAGEPATHS", imagepaths);
startActivity(intent);
finish();
}
return true;
default:
return false;
}
}
public void onDestroyActionMode(ActionMode mode) {
Toast.makeText(getApplicationContext(), "text", 1);
}
public void onItemCheckedStateChanged(ActionMode mode, int position,
long id, boolean checked) {
selectCount = mGrid.getCheckedItemCount();
if(checked){
imagepaths.add(arrPath[position]);
if(selectCount>maximageselection){
imagepaths.remove(arrPath[position]);
new AlertDialog.Builder(MultiImagePicActivity.this)
.setTitle("Restriction")
.setMessage("You can add at max "+maximageselection+" images !!!")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
mGrid.refreshDrawableState();
dialog.dismiss();
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
}
else{
imagepaths.remove(arrPath[position]);
}
switch (selectCount) {
case 1:
mode.setSubtitle("One item selected");
break;
default:
mode.setSubtitle("" + selectCount + " items selected");
break;
}
}
//}
}
}
Related
I have checked all the related posts so far, but did not managed to fix this "Out of memory on a 1843216-byte allocation" error my GridView activity generates.
Basically this activity displays the images from the phone's gallery in a GridView (as a multiple image picker), at first it loads everything just fine, at the second try I get the memory error and the GridView skips loading some of the image thumbnails.
I have disabled the memory caching by: ".cacheInMemory(false)", and using only disk caching with fixed ImageView width and height, but still got the memory error.
Could someone help me out? Thanks!
The CustomGalleryActivity, showing all pictures on the phone:
public class CustomGalleryActivity extends Activity {
GridView gridGallery;
Handler handler;
GalleryAdapter adapter;
ImageView imgNoMedia;
Button btnGalleryOk;
String action;
private ImageLoader imageLoader;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.gallery);
action = getIntent().getAction();
if (action == null) {
finish();
}
initImageLoader();
init();
}
private void initImageLoader() {
try {
String CACHE_DIR = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/.temp_tmp";
new File(CACHE_DIR).mkdirs();
File cacheDir = StorageUtils.getOwnCacheDirectory(getBaseContext(),
CACHE_DIR);
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.imageScaleType(ImageScaleType.EXACTLY)
.bitmapConfig(Bitmap.Config.RGB_565)
.cacheInMemory(false)
.cacheOnDisk(true)
.considerExifParams(true)
.build();
ImageLoaderConfiguration.Builder builder = new ImageLoaderConfiguration.Builder(getBaseContext())
.threadPriority(Thread.NORM_PRIORITY - 2)
.denyCacheImageMultipleSizesInMemory()
.defaultDisplayImageOptions(defaultOptions)
.discCache(new UnlimitedDiscCache(cacheDir))
.tasksProcessingOrder(QueueProcessingType.LIFO);
//.memoryCache(new WeakMemoryCache());
L.writeLogs(false);
ImageLoaderConfiguration config = builder.build();
imageLoader = ImageLoader.getInstance();
imageLoader.destroy();
imageLoader.init(config);
} catch (Exception e) {
}
}
private void init() {
handler = new Handler();
gridGallery = (GridView) findViewById(R.id.gridGallery);
gridGallery.setFastScrollEnabled(true);
adapter = new GalleryAdapter(getApplicationContext(), imageLoader);
PauseOnScrollListener listener = new PauseOnScrollListener(imageLoader,
true, true);
gridGallery.setOnScrollListener(listener);
if (action.equalsIgnoreCase(Action.ACTION_MULTIPLE_PICK)) {
findViewById(R.id.llBottomContainer).setVisibility(View.VISIBLE);
gridGallery.setOnItemClickListener(mItemMulClickListener);
adapter.setMultiplePick(true);
} else if (action.equalsIgnoreCase(Action.ACTION_PICK)) {
findViewById(R.id.llBottomContainer).setVisibility(View.GONE);
gridGallery.setOnItemClickListener(mItemSingleClickListener);
adapter.setMultiplePick(false);
}
gridGallery.setAdapter(adapter);
imgNoMedia = (ImageView) findViewById(R.id.imgNoMedia);
btnGalleryOk = (Button) findViewById(R.id.btnGalleryOk);
btnGalleryOk.setOnClickListener(mOkClickListener);
new Thread() {
#Override
public void run() {
Looper.prepare();
handler.post(new Runnable() {
#Override
public void run() {
adapter.addAll(getGalleryPhotos());
checkImageStatus();
}
});
Looper.loop();
};
}.start();
}
private void checkImageStatus() {
if (adapter.isEmpty()) {
imgNoMedia.setVisibility(View.VISIBLE);
} else {
imgNoMedia.setVisibility(View.GONE);
}
}
View.OnClickListener mOkClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<CustomGallery> selected = adapter.getSelected();
String[] allPath = new String[selected.size()];
for (int i = 0; i < allPath.length; i++) {
allPath[i] = selected.get(i).sdcardPath;
}
Intent data = new Intent().putExtra("all_path", allPath);
setResult(RESULT_OK, data);
finish();
}
};
AdapterView.OnItemClickListener mItemMulClickListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> l, View v, int position, long id) {
//adapter.changeSelection(v, position);
if (adapter.getSelected().size() >= 15) {
Toast.makeText(getApplicationContext(), "Max. 15 de poze pot fi selectate o data!", Toast.LENGTH_LONG).show();
} else {
adapter.changeSelection(v, position);
}
}
};
AdapterView.OnItemClickListener mItemSingleClickListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> l, View v, int position, long id) {
CustomGallery item = adapter.getItem(position);
Intent data = new Intent().putExtra("single_path", item.sdcardPath);
setResult(RESULT_OK, data);
finish();
}
};
private ArrayList<CustomGallery> getGalleryPhotos() {
ArrayList<CustomGallery> galleryList = new ArrayList<CustomGallery>();
try {
final String[] columns = { MediaStore.Images.Media.DATA,
MediaStore.Images.Media._ID };
final String orderBy = MediaStore.Images.Media._ID;
#SuppressWarnings("deprecation")
Cursor imagecursor = managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns,
null, null, orderBy);
if (imagecursor != null && imagecursor.getCount() > 0) {
while (imagecursor.moveToNext()) {
CustomGallery item = new CustomGallery();
int dataColumnIndex = imagecursor
.getColumnIndex(MediaStore.Images.Media.DATA);
item.sdcardPath = imagecursor.getString(dataColumnIndex);
galleryList.add(item);
}
}
} catch (Exception e) {
e.printStackTrace();
}
// show newest photo at beginning of the list
Collections.reverse(galleryList);
return galleryList;
}
}
And its CustomAdapter:
public class GalleryAdapter extends BaseAdapter {
private Context mContext;
private LayoutInflater infalter;
private ArrayList<CustomGallery> data = new ArrayList<CustomGallery>();
ImageLoader imageLoader;
private boolean isActionMultiplePick;
public GalleryAdapter(Context c, ImageLoader imageLoader) {
infalter = (LayoutInflater) c
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mContext = c;
this.imageLoader = imageLoader;
// clearCache();
}
#Override
public int getCount() {
return data.size();
}
#Override
public CustomGallery getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public void setMultiplePick(boolean isMultiplePick) {
this.isActionMultiplePick = isMultiplePick;
}
public void selectAll(boolean selection) {
for (int i = 0; i < data.size(); i++) {
data.get(i).isSeleted = selection;
}
notifyDataSetChanged();
}
public boolean isAllSelected() {
boolean isAllSelected = true;
for (int i = 0; i < data.size(); i++) {
if (!data.get(i).isSeleted) {
isAllSelected = false;
break;
}
}
return isAllSelected;
}
public boolean isAnySelected() {
boolean isAnySelected = false;
for (int i = 0; i < data.size(); i++) {
if (data.get(i).isSeleted) {
isAnySelected = true;
break;
}
}
return isAnySelected;
}
public ArrayList<CustomGallery> getSelected() {
ArrayList<CustomGallery> dataT = new ArrayList<CustomGallery>();
for (int i = 0; i < data.size(); i++) {
if (data.get(i).isSeleted) {
dataT.add(data.get(i));
}
}
return dataT;
}
public void addAll(ArrayList<CustomGallery> files) {
try {
this.data.clear();
this.data.addAll(files);
} catch (Exception e) {
e.printStackTrace();
}
notifyDataSetChanged();
}
public void changeSelection(View v, int position) {
if (data.get(position).isSeleted) {
data.get(position).isSeleted = false;
} else {
data.get(position).isSeleted = true;
}
((ViewHolder) v.getTag()).imgQueueMultiSelected.setSelected(data
.get(position).isSeleted);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = infalter.inflate(R.layout.gallery_item, null);
holder = new ViewHolder();
holder.imgQueue = (ImageView) convertView
.findViewById(R.id.imgQueue);
holder.imgQueueMultiSelected = (ImageView) convertView
.findViewById(R.id.imgQueueMultiSelected);
if (isActionMultiplePick) {
holder.imgQueueMultiSelected.setVisibility(View.VISIBLE);
} else {
holder.imgQueueMultiSelected.setVisibility(View.GONE);
}
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.imgQueue.setTag(position);
try {
imageLoader.displayImage("file://" + data.get(position).sdcardPath,
holder.imgQueue, new SimpleImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
holder.imgQueue.setImageResource(R.drawable.no_media);
super.onLoadingStarted(imageUri, view);
}
});
if (isActionMultiplePick) {
holder.imgQueueMultiSelected
.setSelected(data.get(position).isSeleted);
}
} catch (Exception e) {
e.printStackTrace();
}
return convertView;
}
public class ViewHolder {
ImageView imgQueue;
ImageView imgQueueMultiSelected;
}
public void clearCache() {
imageLoader.clearDiscCache();
imageLoader.clearMemoryCache();
}
public void clear() {
data.clear();
notifyDataSetChanged();
}
}
Try to do this with Picasso library instead of using image loader library. Hope this may helpful for you.
https://github.com/square/picasso
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.
i have prepared an onclicklistener listview to put in a tab menu but after all done, i have noticed that such thing is not possible, i dont know may be with a small change to the code i can achieve what i need but my brain seriously stopped due to fraustrating:( :
public class MainActivity extends FragmentActivity {
private final Handler handler = new Handler();
private PagerSlidingTabStrip tabs;
private ViewPager pager;
private MyPagerAdapter adapter;
private Drawable oldBackground = null;
private int currentColor = 0xFF666666;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
pager = (ViewPager) findViewById(R.id.pager);
adapter = new MyPagerAdapter(getSupportFragmentManager());
pager.setAdapter(adapter);
final int pageMargin = (int)
TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources()
.getDisplayMetrics());
pager.setPageMargin(pageMargin);
tabs.setViewPager(pager);
changeColor(currentColor);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_contact:
QuickContactFragment dialog = new QuickContactFragment();
dialog.show(getSupportFragmentManager(), "QuickContactFragment");
return true;
}
return super.onOptionsItemSelected(item);
}
private void changeColor(int newColor) {
tabs.setIndicatorColor(newColor);
// change ActionBar color just if an ActionBar is available
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
Drawable colorDrawable = new ColorDrawable(newColor);
Drawable bottomDrawable =
getResources().getDrawable(R.drawable.actionbar_bottom);
LayerDrawable ld = new LayerDrawable(new Drawable[] {
colorDrawable, bottomDrawable });
if (oldBackground == null) {
if (Build.VERSION.SDK_INT <
Build.VERSION_CODES.JELLY_BEAN_MR1) {
ld.setCallback(drawableCallback);
} else {
getActionBar().setBackgroundDrawable(ld);
}
} else {
TransitionDrawable td = new TransitionDrawable(new
Drawable[] { oldBackground, ld });
// workaround for broken ActionBarContainer drawable
handling on
// pre-API 17 builds
// https://github.com/android/platform_frameworks_base
/commit/a7cc06d82e45918c37429a59b14545c6a57db4e4
if (Build.VERSION.SDK_INT <
Build.VERSION_CODES.JELLY_BEAN_MR1) {
td.setCallback(drawableCallback);
} else {
getActionBar().setBackgroundDrawable(td);
}
td.startTransition(200);
}
oldBackground = ld;
// http://stackoverflow.com/questions/11002691/actionbar-
setbackgrounddrawable-nulling-background-from-thread-handler
getActionBar().setDisplayShowTitleEnabled(false);
getActionBar().setDisplayShowTitleEnabled(true);
}
currentColor = newColor;
}
public void onColorClicked(View v) {
int color = Color.parseColor(v.getTag().toString());
changeColor(color);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("currentColor", currentColor);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
currentColor = savedInstanceState.getInt("currentColor");
changeColor(currentColor);
}
private Drawable.Callback drawableCallback = new Drawable.Callback() {
#Override
public void invalidateDrawable(Drawable who) {
getActionBar().setBackgroundDrawable(who);
}
#Override
public void scheduleDrawable(Drawable who, Runnable what, long when) {
handler.postAtTime(what, when);
}
#Override
public void unscheduleDrawable(Drawable who, Runnable what) {
handler.removeCallbacks(what);
}
};
public class MyPagerAdapter extends FragmentPagerAdapter {
private final String[] TITLES = { "Categories", "Home", "Top Paid" };
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public CharSequence getPageTitle(int position) {
return TITLES[position];
}
#Override
public int getCount() {
return TITLES.length;
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
// Top Rated fragment activity
return new TopRatedFragment();
case 1:
// Games fragment activity
return new GamesFragment();
case 2:
// Movies fragment activity
return new MoviesFragment();
}
return null;
}
}
}
here my beloved listview :
public class PinnedSectionListActivity extends ListActivity implements
OnClickListener {
static class SimpleAdapter extends ArrayAdapter<Item> implements
PinnedSectionListAdapter {
private static final int[] COLORS = new int[] {
android.R.color.holo_green_light, android.R.color.holo_orange_dark,
android.R.color.holo_blue_light, android.R.color.holo_red_light };
public SimpleAdapter(Context context, int resource, int textViewResourceId) {
super(context, resource, textViewResourceId);
final int sectionsNumber = 'Z' - 'A' + 1;
prepareSections(sectionsNumber);
int sectionPosition = 0, listPosition = 0;
for (char i=0; i<sectionsNumber; i++) {
Item section = new Item(Item.SECTION, String.valueOf((char)('A' + i)));
section.sectionPosition = sectionPosition;
section.listPosition = listPosition++;
onSectionAdded(section, sectionPosition);
add(section);
final int itemsNumber = (int) Math.abs((Math.cos(2f*Math.PI/3f *
sectionsNumber / (i+1f)) * 25f));
for (int j=0;j<itemsNumber;j++) {
Item item = new Item(Item.ITEM,
section.text.toUpperCase(Locale.ENGLISH) + " - " + j);
item.sectionPosition = sectionPosition;
item.listPosition = listPosition++;
add(item);
}
sectionPosition++;
}
}
protected void prepareSections(int sectionsNumber) { }
protected void onSectionAdded(Item section, int sectionPosition) { }
#Override public View getView(int position, View convertView, ViewGroup parent) {
TextView view = (TextView) super.getView(position, convertView, parent);
view.setTextColor(Color.DKGRAY);
view.setTag("" + position);
Item item = getItem(position);
if (item.type == Item.SECTION) {
//view.setOnClickListener(PinnedSectionListActivity.this);
view.setBackgroundColor(parent.getResources().getColor(COLORS[item.sectionPosition %
COLORS.length]));
}
return view;
}
#Override public int getViewTypeCount() {
return 2;
}
#Override public int getItemViewType(int position) {
return getItem(position).type;
}
#Override
public boolean isItemViewTypePinned(int viewType) {
return viewType == Item.SECTION;
}
}
static class FastScrollAdapter extends SimpleAdapter implements SectionIndexer {
private Item[] sections;
public FastScrollAdapter(Context context, int resource, int textViewResourceId) {
super(context, resource, textViewResourceId);
}
#Override protected void prepareSections(int sectionsNumber) {
sections = new Item[sectionsNumber];
}
#Override protected void onSectionAdded(Item section, int sectionPosition) {
sections[sectionPosition] = section;
}
#Override public Item[] getSections() {
return sections;
}
#Override public int getPositionForSection(int section) {
if (section >= sections.length) {
section = sections.length - 1;
}
return sections[section].listPosition;
}
#Override public int getSectionForPosition(int position) {
if (position >= getCount()) {
position = getCount() - 1;
}
return getItem(position).sectionPosition;
}
}
static class Item {
public static final int ITEM = 0;
public static final int SECTION = 1;
public final int type;
public final String text;
public int sectionPosition;
public int listPosition;
public Item(int type, String text) {
this.type = type;
this.text = text;
}
#Override public String toString() {
return text;
}
}
private boolean hasHeaderAndFooter;
private boolean isFastScroll;
private boolean addPadding;
private boolean isShadowVisible = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contacts);
if (savedInstanceState != null) {
isFastScroll = savedInstanceState.getBoolean("isFastScroll");
addPadding = savedInstanceState.getBoolean("addPadding");
isShadowVisible = savedInstanceState.getBoolean("isShadowVisible");
hasHeaderAndFooter =
savedInstanceState.getBoolean("hasHeaderAndFooter");
}
initializeHeaderAndFooter();
initializeAdapter();
initializePadding();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean("isFastScroll", isFastScroll);
outState.putBoolean("addPadding", addPadding);
outState.putBoolean("isShadowVisible", isShadowVisible);
outState.putBoolean("hasHeaderAndFooter", hasHeaderAndFooter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Item item = (Item) getListView().getAdapter().getItem(position);
if (item != null) {
Toast.makeText(this, "Item " + position + ": " + item.text,
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Item " + position, Toast.LENGTH_SHORT).show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
menu.getItem(0).setChecked(isFastScroll);
menu.getItem(1).setChecked(addPadding);
menu.getItem(2).setChecked(isShadowVisible);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_fastscroll:
isFastScroll = !isFastScroll;
item.setChecked(isFastScroll);
initializeAdapter();
break;
case R.id.action_addpadding:
addPadding = !addPadding;
item.setChecked(addPadding);
initializePadding();
break;
case R.id.action_showShadow:
isShadowVisible = !isShadowVisible;
item.setChecked(isShadowVisible);
((PinnedSectionListView)getListView()).setShadowVisible(isShadowVisible);
break;
case R.id.action_showHeaderAndFooter:
hasHeaderAndFooter = !hasHeaderAndFooter;
item.setChecked(hasHeaderAndFooter);
initializeHeaderAndFooter();
break;
}
return true;
}
private void initializePadding() {
float density = getResources().getDisplayMetrics().density;
int padding = addPadding ? (int) (16 * density) : 0;
getListView().setPadding(padding, padding, padding, padding);
}
private void initializeHeaderAndFooter() {
setListAdapter(null);
if (hasHeaderAndFooter) {
ListView list = getListView();
LayoutInflater inflater = LayoutInflater.from(this);
TextView header1 = (TextView)
inflater.inflate(android.R.layout.simple_list_item_1, list, false);
header1.setText("First header");
list.addHeaderView(header1);
TextView header2 = (TextView)
inflater.inflate(android.R.layout.simple_list_item_1, list, false);
header2.setText("Second header");
list.addHeaderView(header2);
TextView footer = (TextView)
inflater.inflate(android.R.layout.simple_list_item_1, list, false);
footer.setText("Single footer");
list.addFooterView(footer);
}
initializeAdapter();
}
#SuppressLint("NewApi")
private void initializeAdapter() {
getListView().setFastScrollEnabled(isFastScroll);
if (isFastScroll) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
getListView().setFastScrollAlwaysVisible(true);
}
setListAdapter(new FastScrollAdapter(this,
android.R.layout.simple_list_item_1, android.R.id.text1));
} else {
setListAdapter(new SimpleAdapter(this, android.R.layout.simple_list_item_1,
android.R.id.text1));
}
}
#Override
public void onClick(View v) {
Toast.makeText(this, "Item: " + v.getTag() , Toast.LENGTH_SHORT).show();
}
}
i think what you need is navigation drawer
or you can use action bar
I tried update my listview when i delete an item in cart or update quantitiy of a product but it doesnt work. Where is my mistake?? I try notifyDataSetChanged(); method but it doesnt work instantly. I want to refresh my listview when i change it. How can i do it? Do i need write a method in adapter class or something else?
public class Cart extends Activity implements OnClickListener{
private ArrayList<String> textfield;
private ArrayList<String> birimfield;
private ArrayList<String> adetfield;
private ArrayList<String> pricefield;
private ArrayList<String> shortfield;
private ArrayList<Drawable> imagefield;
private CustomAdapter customadapter;
public static double sepetbedeli;
public static double toplambedel;
public static int couponid;
private boolean isCouponExists=false;
public String adet;
public static final double kargobedeli=6.0;
String ad;
TextView greeting;
ImageButton sepet,devam;
Button uyelik,hakkimizda;
public static ArrayList<CartSystem> userCart = new ArrayList<CartSystem>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_cart);
Bundle extras = getIntent().getExtras();
if (extras != null) {
ad=extras.getString("ad");
greeting=(TextView)findViewById(R.id.greetingsText);
greeting.setText("Hoşgeldiniz, "+extras.getString("ad"));
}
for (int i = 0; i < userCart.size(); i++) {
if(userCart.get(i).birim=="adet"||userCart.get(i).birim=="Adet")
{
System.out.println("Adetli sipariş bulundu!");
userCart.get(i).adet="1";
}
}
preparetext();
preparefiyat();
preparekisa();
prepareadet();
preparebirim();
try {
prepareimage();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
customadapter.notifyDataSetChanged();
ListView gridView=(ListView)findViewById(R.id.listView1);
gridView.setCacheColorHint(Color.TRANSPARENT);
gridView.requestFocus(0);
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
AlertDialog.Builder alert = new AlertDialog.Builder(Cart.this);
final int i =position;
alert.setTitle("Ürün "+userCart.get(position).birim+" miktarını değiştir.");
alert.setMessage("Yeni miktarı giriniz:");
// Set an EditText view to get user input
final EditText servername = new EditText(Cart.this);
alert.setView(servername);
alert.setPositiveButton("Değiştir", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
adet = servername.getText().toString();
userCart.get(i).adet=adet;
customadapter.notifyDataSetChanged();
gridView.setAdapter(customadapter);
}
});
alert.setNeutralButton("Ürünü Sil", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int whichButton) {
userCart.remove(i);
customadapter.notifyDataSetChanged();
gridView.setAdapter(customadapter);
}
});
alert.show();
}
});
Kontroller();
customadapter= new CustomAdapter(this, textfield, imagefield,adetfield,birimfield,pricefield,shortfield);
gridView.setAdapter(customadapter);
TextBoxKontrolleri();
}
private void TextBoxKontrolleri()
{
TextView sepettoplam = (TextView)findViewById(R.id.txtsepetfiyati);
for (int i = 0; i < userCart.size(); i++) {
sepetbedeli+=Double.parseDouble(userCart.get(i).fiyat);
}
sepettoplam.setText("Sepet Bedeli: " +Double.toString(sepetbedeli)+" TL");
TextView kargo = (TextView)findViewById(R.id.txtkargobedeli);
TextView toplam = (TextView)findViewById(R.id.txttoplam);
TextView kargotext = (TextView)findViewById(R.id.txtkargobizden);
if(sepetbedeli+kargobedeli<100)
{
kargo.setText("Kargo Bedeli: "+Double.toString(kargobedeli)+" TL");
toplam.setText("Toplam Bedel: " +Double.toString(sepetbedeli+kargobedeli)+" TL");
kargotext.setText(Double.toString(100-sepetbedeli)+" TL kadar daha alışveriş yaparsanız kargo bizden");
}
else
{
kargo.setText("Kargo Bedeli: 0 TL");
toplam.setText("Toplam Bedel: " +Double.toString(sepetbedeli)+" TL");
kargotext.setText("Kargo bizden");
System.out.println("Toplam: "+toplambedel);
}
}
private void Kontroller() {
sepet = (ImageButton)findViewById(R.id.imageButton1);
devam = (ImageButton)findViewById(R.id.imageButton2);
uyelik =(Button) findViewById(R.id.uyelikBilgileriniz);
hakkimizda =(Button) findViewById(R.id.hakkimizda);
uyelik.setOnClickListener(this);
hakkimizda.setOnClickListener(this);
devam.setOnClickListener(this);
sepet.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.imageButton2:
try {
if(isCouponExists==false)
{
couponid=-1;
}
else
{
couponid=1;
}
System.out.println(toplambedel);
Intent intent = new Intent(this, Class.forName("com.Troyateck.sucukevim.Payment"));
intent.putExtra("ad",ad);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplicationContext().startActivity(intent);
} catch (ClassNotFoundException e) {
Toast.makeText(this, "Hata : " + e.toString(),
Toast.LENGTH_SHORT).show();
}
break;
}
}
public void preparetext()
{
textfield=new ArrayList<String>();
for (int i = 0; i < userCart.size(); i++) {
textfield.add(userCart.get(i).urunadi);
}
}
public void preparefiyat()
{
pricefield=new ArrayList<String>();
for (int i = 0; i < userCart.size(); i++) {
pricefield.add(userCart.get(i).fiyat);
}
}
public void preparekisa()
{
System.out.println(userCart.size());
shortfield=new ArrayList<String>();
for (int i = 0; i < userCart.size(); i++) {
shortfield.add(userCart.get(i).detay);
}
}
public void prepareadet()
{
adetfield=new ArrayList<String>();
for (int i = 0; i < userCart.size(); i++) {
adetfield.add(userCart.get(i).adet);
}
}
public void preparebirim()
{
birimfield=new ArrayList<String>();
for (int i = 0; i < userCart.size(); i++) {
birimfield.add(userCart.get(i).birim);
System.out.println(userCart.get(i).birim);
}
}
public void prepareimage() throws InterruptedException, ExecutionException
{
imagefield=new ArrayList<Drawable>();
for (int i = 0; i < userCart.size(); i++) {
LoadImageFromWeb get = new LoadImageFromWeb();
Drawable res = get.execute(new String[] { userCart.get(i).resim }).get();
imagefield.add(res);
}
}
private class LoadImageFromWeb extends AsyncTask<String, Drawable, Drawable> {
#Override
protected Drawable doInBackground(String... params) {
try
{
InputStream is = (InputStream) new URL(params[0]).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
}catch (Exception e) {
System.out.println("Exc="+e.getMessage());
return null;
}
}
}
private class CustomAdapter extends ArrayAdapter<Object>
{
Activity activity;
ArrayList<String> textfield;
ArrayList<String> adetfield;
ArrayList<String> birimfield;
ArrayList<String> pricefield;
ArrayList<String> shortfield;
ArrayList<Drawable> imagefield;
public CustomAdapter(Activity context, ArrayList<String> name,ArrayList<Drawable> image,ArrayList<String> adetfield,ArrayList<String> birimfield,ArrayList<String> pricefield,ArrayList<String> shortfield)
{
super(context, 0);
activity=context;
this.textfield=name;
this.imagefield=image;
this.adetfield=adetfield;
this.birimfield=birimfield;
this.pricefield=pricefield;
this.shortfield=shortfield;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ImageView imgViewFlag;
TextView txtViewTitle;
TextView txtViewFiyat;
TextView txtViewDetay;
TextView txtViewAdet;
TextView txtViewBirim;
LayoutInflater inflator = activity.getLayoutInflater();
convertView = inflator.inflate(R.layout.cartgrid, null);
txtViewTitle = (TextView) convertView.findViewById(R.id.baslik);
txtViewAdet = (TextView) convertView.findViewById(R.id.textView1);
txtViewFiyat=(TextView)convertView.findViewById(R.id.fiyat);
txtViewDetay=(TextView)convertView.findViewById(R.id.aciklama);
txtViewBirim = (TextView) convertView.findViewById(R.id.textView2);
imgViewFlag = (ImageView) convertView.findViewById(R.id.resim);
txtViewTitle.setText(textfield.get(position));
txtViewAdet.setText(adetfield.get(position));
txtViewFiyat.setText(pricefield.get(position));
txtViewDetay.setText(shortfield.get(position));
txtViewBirim.setText(birimfield.get(position));
imgViewFlag.setImageDrawable(imagefield.get(position));
return convertView;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return textfield.size();
}
#Override
public String getItem(int position) {
// TODO Auto-generated method stub
return textfield.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.cart, menu);
return true;
}
public void AddToCart(int id,String ad,String adet,String resim,String fiyat,String detay,String birim)
{
System.out.println("job2"+" "+id+" "+ad+" "+adet+" "+resim+" "+adet+" "+birim);
userCart.add(new CartSystem(id,ad,adet,resim,fiyat,detay,birim));
System.out.println(userCart.size());
}
public class CartSystem
{
public CartSystem()
{
}
public CartSystem(int id,String urunadi,String adet,String resim,String fiyat,String detay,String birim)
{
this.id=id;
this.urunadi=urunadi;
this.adet=adet;
this.resim=resim;
this.birim=birim;
this.fiyat=fiyat;
this.detay=detay;
}
public int id;
public String urunadi;
public String adet;
public String fiyat;
public String detay;
public String birim;
public String resim;
}
public static void setprice(Double price) {
Cart.toplambedel = price;
}
public static String getprice() {
return Double.toString(toplambedel);
}
}
notifyDataSetChanged() method should be called after setAdapter() method.
Try listViewVariable.notify() .
I have the following class to show some images...
I have implemented an ability to download images to the sd card.
If I go through them everything is fine (Image + Title showing) but if I start the download at a certain image, uses another url (of another image) so I somehow think that my ViewPager is not updated correctly or something.
This is my class:
public class ImagePagerActivity extends BaseActivity {
private ViewPager pager;
LinearLayout buttonBar;
TextView txtTitle;
String urlOfImageToDownload;
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private ProgressDialog mProgressDialog;
private static DisplayImageOptions options;
ImageView imageView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ac_image_pager);
Bundle bundle = getIntent().getExtras();
String[] imageUrls = bundle.getStringArray(Extra.IMAGES);
String[] imageTitles = bundle.getStringArray(Extra.TITLES);
int pagerPosition = bundle.getInt(Extra.IMAGE_POSITION, 0);
options = new DisplayImageOptions.Builder()
.cacheOnDisc().showImageForEmptyUri(R.drawable.no_image)
.imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2)
.build();
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(new ImagePagerAdapter(imageUrls, imageTitles));
pager.setCurrentItem(pagerPosition);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
if (imageView.getDrawable() == null)
menu.getItem(0).setEnabled(false);
return true;
}
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, 0, 0,
getString(R.string.save_image)).setIcon(android.R.drawable.ic_menu_save);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 0:
Random randomGenerator = new Random();
int randomInt = 0;
for (int idx = 1; idx <= 10; ++idx) {
randomInt = randomGenerator.nextInt(100000);
}
imageView.setDrawingCacheEnabled(true);
Bitmap b = imageView.getDrawingCache();
try {
b.compress(CompressFormat.JPEG, 100,
new
FileOutputStream(Environment.getExternalStorageDirectory()
.getPath() + "/DCIM/image" + randomInt + ".jpg"));
Crouton.makeText(ImagePagerActivity.this,
"Bild erfolgreich gespeichert",
Style.INFO)
.show();
} catch (FileNotFoundException e) {
Crouton.makeText(ImagePagerActivity.this,
"Fehler beim speichern von Datei",
Style.ALERT)
.show();
}
startDownload();
return true;
}
return false;
}
private void startDownload() {
String url = urlOfImageToDownload;
Log.e(MainActivity.LOG_TAG, "url=" + urlOfImageToDownload);
new DownloadFileAsync().execute(url);
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage(getString(R.string.downloading_image));
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
#Override
protected void onStop() {
imageLoader.stop();
super.onStop();
}
private class ImagePagerAdapter extends PagerAdapter {
private String[] images;
private String[] titles;
private LayoutInflater inflater;
ImagePagerAdapter(String[] images, String[] imageTitles) {
this.images = images;
this.titles = imageTitles;
inflater = getLayoutInflater();
}
#Override
public void destroyItem(View container, int position, Object object) {
((ViewPager) container).removeView((View) object);
}
#Override
public void finishUpdate(View container) {
}
#Override
public int getCount() {
return images.length;
}
#Override
public Object instantiateItem(View view, int position) {
final FrameLayout imageLayout = (FrameLayout) inflater.inflate(
R.layout.item_pager_image, null);
imageView = (ImageView) imageLayout
.findViewById(R.id.image);
final ProgressBar spinner = (ProgressBar) imageLayout
.findViewById(R.id.loading);
txtTitle = (TextView) imageLayout.findViewById(R.id.txtTitle);
urlOfImageToDownload = images[position];
buttonBar = (LinearLayout) imageLayout.findViewById(R.id.buttonBar);
txtTitle.setText(titles[position]);
imageLoader.displayImage(images[position], imageView, options,
new ImageLoadingListener() {
#Override
public void onLoadingStarted() {
spinner.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingFailed(FailReason failReason) {
switch (failReason) {
case IO_ERROR:
break;
case OUT_OF_MEMORY:
break;
case UNKNOWN:
break;
}
spinner.setVisibility(View.GONE);
imageView.setImageResource(android.R.drawable.ic_delete);
}
#Override
public void onLoadingComplete(Bitmap bm) {
spinner.setVisibility(View.GONE);
}
#Override
public void onLoadingCancelled() {
spinner.setVisibility(View.GONE);
}
});
((ViewPager) view).addView(imageLayout, 0);
return imageLayout;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
#Override
public void restoreState(Parcelable state, ClassLoader loader) {
}
#Override
public Parcelable saveState() {
return null;
}
#Override
public void startUpdate(View container) {
}
}
class DownloadFileAsync extends AsyncTask<String, String, String> {
#SuppressWarnings("deprecation")
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected String doInBackground(String... aurl) {
int count;
try {
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
Random rand = new Random();
int randomNumber = rand.nextInt(100000);
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(
"sdcard/nature_" + randomNumber + ".jpg");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
}
return null;
}
protected void onProgressUpdate(String... progress) {
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
Crouton.makeText(ImagePagerActivity.this,
getString(R.string.image_saved),
Style.CONFIRM)
.show();
}
}
}
Thanks for any help!
Issue:
The first time the user looks at an image in the ViewPager, instantiateItem(..) for that image will be called and the field urlOfImagetoDownload will be set to the correct URL:
urlOfImageToDownload = images[position];
However if the user now returns to an image he has seen before that is already instantiated, instantiateItem(...) will not be called and urlOfImageToDownload will hold the wrong URL (of the previous image).
Solution:
You can use ViewPager#getCurrentItem() to retrieve the index of the current image, then use that index with images[] to get the right URL when the user clicks to download.