How to load fast an image URL into android grid view? - android-asynctask

I have this following codes for displaying few url images into my android grid view. the problem is, it takes a lot of time just to display few numbers of images into my grid view. These are my codes:
public class GridViewImageAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> galleryAttributes = new ArrayList<HashMap<String, String>>();
private int imageWidth;
int ctr = 0;
public GridViewImageAdapter(Activity activity,
ArrayList<HashMap<String, String>> galleryAttributes, int imageWidth) {
this.activity = activity;
this.galleryAttributes = galleryAttributes;
this.imageWidth = imageWidth;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return galleryAttributes.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return galleryAttributes.get(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
ImageView imageView;
if(convertView == null){
imageView = new ImageView(activity);
}else{
imageView = (ImageView) convertView;
}
LoadImage loadImage = new LoadImage();
try {
Bitmap image = loadImage.execute(galleryAttributes.get(position).get("Link")).get();
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(imageWidth, imageWidth));
imageView.setImageBitmap(image);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return imageView;
}
public class LoadImage extends AsyncTask<String, String, Bitmap>{
#Override
protected Bitmap doInBackground(String... params) {
// TODO Auto-generated method stub
try{
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream((InputStream) new URL(params[0]).getContent(), null, o);
final int REQUIRED_WIDTH = imageWidth;
final int REQUIRED_HEIGHT = imageWidth;
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_WIDTH
&& o.outHeight / scale / 2 >= REQUIRED_HEIGHT)
scale *= 2;
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream((InputStream) new URL(params[0]).getContent(), null, o2);
}
catch(Exception e){
e.printStackTrace();
}
return null;
}
}

Try to use picasso
http://square.github.io/picasso/
This library will cache the picture that downloaded from the URL and next time you open it, it will loaded much more faster because you didn't need to download it again but just take it from the cache.
If the initial displaying is also slow, try to resizing it to reasonable size.
The usage is also pretty easy :
Picasso.with(context)
.load(url)
.resize(50, 50)
.centerCrop()
.into(imageView)

You can user Glide or Picasso.
But Glide is having thumbnail support too.
Glide.with(this)
.load(galleryAttributes.get(position).get("Link"))
.thumbnail(0.1f)
.into(imageView);
Picasso.with(this).load(galleryAttributes.get(position).get("Link")).into(imageView);

Related

Libgdx -stage inside game play screen conflicts with inputprocessor

In my LibGdx game,I want to create a pause button inside game screen.For this,I created a stage object like this.
Stage stage;
stage = new Stage(game.viewPort);
I wanted to include this statement:
Gdx.input.setInputProcessor(stage);
But another statement is already there;
Gdx.input.setInputProcessor(inputmultiplexer);
So when I add a pause button,It is showing up but listener for the button seems to be not working.
private void drawPauseButton() {
pauseButton = new ImageButton(new TextureRegionDrawable(pauseTexture),
new TextureRegionDrawable(pausePressTexture));
stage.addActor(pauseButton);
pauseButton.setPosition(Constants.WORLD_WIDTH,30, Align.bottomRight);
pauseButton.addListener(new ActorGestureListener() {
#Override
public void tap(InputEvent event, float x, float y, int count, int button) {
super.tap(event, x, y, count, button);
game.setScreen(new PauseScreen(game));
// dispose();
}
});
}
How can I resolve this issue?
Input multiplexer code:
public class MyInputProcessor implements InputProcessor,GestureListener {
public static boolean isTouchDown=false;
public static boolean isTouchUp=false;
public static boolean isTap=false;
public static boolean isLongPress=false;
public static boolean isFling=false;
public static boolean isSwipeDown=false;
public static boolean isSwipeUp=false;
public static boolean isSwipeLeft=false;
public static boolean isSwipeRight=false;
public static boolean isKeyDown=false;
public static boolean isZoomed=false;
public static float zoomInitDist=0;
public static float zoomDist=0;
public MyInputProcessor() {
// TODO Auto-generated constructor stub
System.out.println("My Input Processor Created..");
}
public InputMultiplexer returnInput() {
// TODO Auto-generated method stub
InputMultiplexer im = new InputMultiplexer();
GestureDetector gd = new GestureDetector(this);
im.addProcessor(gd);
im.addProcessor(this);
return im;
}
#Override
public boolean tap(float x, float y, int count, int button) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean longPress(float x, float y) {
// TODO Auto-generated method stub
this.isLongPress=true;
return false;
}
#Override
public boolean fling(float velocityX, float velocityY, int button) {
// TODO Auto-generated method stub
if(Math.abs(velocityX)>Math.abs(velocityY)){
if(velocityX>0){
this.isSwipeRight=true;
}else{
this.isSwipeLeft=true;
}
}else{
if(velocityY>0){
this.isSwipeDown=true;
}else{
this.isSwipeUp=true;
}
}
return false;
}
#Override
public boolean pan(float x, float y, float deltaX, float deltaY) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean panStop(float x, float y, int pointer, int button) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean zoom(float initialDistance, float distance) {
// TODO Auto-generated method stub
this.isZoomed=true;
this.zoomInitDist=initialDistance;
this.zoomDist=distance;
return false;
}
#Override
public boolean pinch(Vector2 initialPointer1, Vector2 initialPointer2, Vector2 pointer1, Vector2 pointer2) {
// TODO Auto-generated method stub
return false;
}
#Override
public void pinchStop() {
// TODO Auto-generated method stub
}
#Override
public boolean keyDown(int keycode) {
// TODO Auto-generated method stub
this.isKeyDown=true;
return true;
}
#Override
public boolean keyUp(int keycode) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean keyTyped(char character) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean mouseMoved(int screenX, int screenY) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean scrolled(int amount) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
MyInputProcessor.isTouchDown=true;
return false;
}
#Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
MyInputProcessor.isTouchUp=true;
return false;
}
#Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean touchDown(float x, float y, int pointer, int button) {
// TODO Auto-generated method stub
return false;
}
Inside gamescreen class' show method:
MyInputProcessor myInputProcessor = new MyInputProcessor();
InputMultiplexer im = myInputProcessor.returnInput();
Gdx.input.setInputProcessor(im);
An InputProcessor that delegates to an ordered list of other InputProcessors. Delegation for an event stops if a processor returns true, which indicates that the event was handled.
Stage implements InputProcessor, you can create another implementation and put into Gdx.input
Stage stage=new Stage(); // your 1st InputProcessor
InputPorcessor processor=new InputPorcessor(); //2nd InputProcessor
... // may be 3rd
InputMultiplexer inputMultiplexer=new InputMultiplexer();
inputMultiplexer.addProcessor(stage);
inputMultiplexer.addProcessor(processor);
Gdx.input.setInputProcessor(inputMultiplexer);
EDIT
Add your stage into your multiplexer and return in this way :
public InputMultiplexer returnInput(Stage stage) {
InputMultiplexer im = new InputMultiplexer();
GestureDetector gd = new GestureDetector(this);
im.addProcessor(stage);
im.addProcessor(gd);
im.addProcessor(this);
return im;
}
Set return value:
MyInputProcessor myInputProcessor = new MyInputProcessor();
InputMultiplexer im = myInputProcessor.returnInput(stage);
Gdx.input.setInputProcessor(im);

Grid view having duplicate column values

I am trying to build a Grid View inside Expandable list view. The problem i am facing is that the the columns in gridview are repeating no matter the number of columns i specify in xml. please find below the code and screen shot. That is there are two child view A and B. Instead of each coming in a single row. A is coming completely on 1st row no matter the number of columns and B is coming on the complete second rows.
ExpandableListAdapter
public class ExpandListAdapter extends BaseExpandableListAdapter {
private Activity activity;
private Context context;
private ArrayList<GroupModel> mMainDatabase;
private LayoutInflater inflater;
private ArrayList<String> parentItems, child, child1, child2;
private CustomGrid adapter;
private GridView grid;
ViewHolder viewHolder;
private static final String LOG_TAG = ExpandListAdapter.class.getSimpleName();
public ExpandListAdapter(ArrayList<GroupModel> mMainDatabase) {
this.mMainDatabase = mMainDatabase;
}
public void setInflater(LayoutInflater inflater, Activity activity) {
this.inflater = inflater;
this.activity = activity;
}
#Override
public int getGroupCount() {
return mMainDatabase.size();
}
#Override
public int getChildrenCount(int groupPosition) {
return mMainDatabase.get(groupPosition).getItemModels().size();
}
#Override
public Object getGroup(int groupPosition) {
return mMainDatabase.get(groupPosition);
}
#Override
public Object getChild(int groupPosition, int childPosition) {
return child.get(childPosition);
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
View v = convertView;
// if (convertView == null) {
// inflate the adapter_side
LayoutInflater vi = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.fragment_list_item, null);
// well set up the ViewHolder
viewHolder = new ViewHolder();
viewHolder.title = (TextView) v.findViewById(R.id.item_title);
viewHolder.image = (ImageView) v.findViewById(R.id.item_image);
viewHolder.image.setId(groupPosition);
if (mMainDatabase.get(groupPosition).getGroupImage() != null &&
!mMainDatabase.get(groupPosition).getGroupImage().equals(""))
Utilities.displayImage(activity.getApplicationContext(), mMainDatabase.get(groupPosition).getGroupImage(), viewHolder.image);
else
Picasso.with(activity).load("http://www.google.com")
.into(viewHolder.image);
viewHolder.title
.setText(mMainDatabase.get(groupPosition).getGroupName());
viewHolder.arrowExpand = (ImageView) v.findViewById(R.id.arrowExpand);
if (isExpanded)
viewHolder.arrowExpand.setImageResource(R.drawable.dropdown2);
else
viewHolder.arrowExpand.setImageResource(R.drawable.dropdown);
return v;
}
#Override
public View getChildView(final int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
if (convertView == null) {
// LayoutInflater infalInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.grid_view, null);
}
grid = (GridView) convertView.findViewById(R.id.grid);
adapter = new CustomGrid(activity, groupPosition, childPosition,activity, mMainDatabase);
grid.setAdapter(adapter);
grid.setTag(childPosition);
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(activity, FoodDetailActivity.class);
intent.putExtra("item", mMainDatabase.get(groupPosition).getItemModels().
get(Integer.parseInt(view.getTag().toString())));
intent.putExtra("grpId", mMainDatabase.get(groupPosition).get_id());
intent.putExtra("atBottom", true);
activity.startActivity(intent);
}
});
return convertView;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onGroupExpanded(int groupPosition) {
super.onGroupExpanded(groupPosition);
}
#SuppressLint("NewApi")
#Override
public void onGroupCollapsed(int groupPosition) {
super.onGroupCollapsed(groupPosition);
// ImageView img_selection = (ImageView) groupPosition
// .findViewById(R.id.arrowExpand);
}
static class ViewHolder {
TextView title;
TextView number;
TextView numbertxt;
ImageView image, arrowExpand;
Bitmap b;
int position;
}
}
Custom Grid Adapter
public class CustomGrid extends BaseAdapter {
private Context mContext;
private ArrayList<String> mItemName = null;
private ArrayList<String> mItemImage = null;
private int groupPosition, childPosition;
Activity activity;
ArrayList<GroupModel> mMainDatabase;
LayoutInflater inflater;
public CustomGrid(Context c,
int groupPosition, int childPosition, Activity activity, ArrayList<GroupModel> mMainDatabase) {
mContext = c;
this.groupPosition = groupPosition;
this.childPosition = childPosition;
this.activity = activity;
this.mMainDatabase = mMainDatabase;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mMainDatabase.get(groupPosition).getItemModels().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 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View grid;
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
grid = new View(mContext);
grid = inflater.inflate(R.layout.grid_single, null);
TextView textView = (TextView) grid.findViewById(R.id.grid_text);
ImageView imageView = (ImageView)grid.findViewById(R.id.grid_image);
textView.setText(mMainDatabase.get(groupPosition).getItemModels()
.get(childPosition).getItemName());
Log.d("CUSTOMGRID", "child name is " + mMainDatabase.get(groupPosition).getItemModels()
.get(childPosition).getItemName() + " child position is " + childPosition);
if (mMainDatabase.get(groupPosition).getItemModels().get(childPosition).getItemImage() != null &&
!mMainDatabase.get(groupPosition).getItemModels().get(childPosition).getItemImage()
.equals(""))
Picasso.with(activity)
.load(mMainDatabase.get(groupPosition).getItemModels()
.get(childPosition).getItemImage())
.placeholder(R.drawable.place).into(imageView);
else
Picasso.with(activity).load("http://www.google.com")
.placeholder(R.drawable.place).into(imageView);
} else {
grid = (View) convertView;
}
return grid;
}
}

Recyclerview adapter with asyncTask

I'm trying to use custom adapter with RecyclerView, but the holders are empty. I can't understand what did i miss. Please help.
In MainActivity's AsyncTask:
#Override
protected void onPostExecute(String result) {
json_result = result;
super.onPostExecute(result);
dialog.dismiss();
if (result == null) {
Toast.makeText(MainActivity.this, "error getting results...", Toast.LENGTH_LONG).show();
} else {
try {
JSONObject json = new JSONObject(result);
Log.e(TAG, "create json object");
JSONArray searchArray = json.getJSONArray("Search");
Log.e(TAG, "Search");
for (int i = 0; i < searchArray.length(); i++) {
Log.e(TAG, "run on length");
JSONObject searchObject = searchArray.getJSONObject(i);
Log.e(TAG, "create search object");
String title = searchObject.getString("Title");
Log.e(TAG, "Title" + title);
String type = searchObject.getString("Type");
Log.e(TAG, "Type" + type);
String year = searchObject.getString("Year");
Log.e(TAG, "Year" + year);
String imdbID = searchObject.getString("imdbID");
String poster = searchObject.getString("Poster");
Log.e(TAG, "" + result);
movieList.add(new Movie(title, type, year, imdbID, poster));
Log.e(TAG, "Add to adapter");
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "error parsing results...", Toast.LENGTH_LONG).show();
}
adapter.notifyDataSetChanged();
Log.e(TAG, "Notify");
}
}
Custom Adapter:
public class Adapter extends
RecyclerView.Adapter<Adapter.ViewHolder> {
private LruCache<String, Bitmap> bitmapCache;
Context context;
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView title;
public TextView year;
public TextView type;
public ImageView poster;
public ViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.txt_title);
year = (TextView) itemView.findViewById(R.id.txt_year);
type = (TextView) itemView.findViewById(R.id.txt_rating);
poster = (ImageView) itemView.findViewById(R.id.imageView);
}
}
private List<Movie> mList;
public Adapter(List<Movie> mList) {
this.mList = mList;
int numImages = 4 * 1024 * 1024;
this.bitmapCache = new LruCache<String, Bitmap>(numImages) {
#Override
protected int sizeOf(String key, Bitmap value) {
// this is how to calculate a bitmap size in bytes.
// (bytes-in-a-row * height)
return value.getRowBytes() * value.getHeight();
}
};
}
#Override
public Adapter.ViewHolder onCreateViewHolder
(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View movieView = inflater.inflate(R.layout.card_view, parent, false);
ViewHolder viewHolder = new ViewHolder(movieView);
return viewHolder;
}
#Override
public void onBindViewHolder
(Adapter.ViewHolder holder, int position) {
Movie movie = mList.get(position);
holder.title.setText(movie.getTitle());
holder.year.setText(movie.getYear());
holder.type.setText(movie.getType());
holder.poster.setVisibility(View.INVISIBLE);
GetImageTask task = new GetImageTask(movie, holder);
task.execute(movie.getPoster_url());
}
#Override
public int getItemCount() {
return mList.size();
}
class GetImageTask extends AsyncTask<String, Void, Bitmap> {
private final Movie movie;
private final ViewHolder holder;
public GetImageTask(Movie movie, ViewHolder holder) {
this.movie = movie;
this.holder = holder;
}
#Override
protected Bitmap doInBackground(String... params) {
//download:
String address = params[0];
Bitmap bitmap = HttpHandler.getBitmap(address, null);
//save it in the cache for later:
if (bitmap != null) {
bitmapCache.put(address, bitmap);
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap result) {
if (movie.equals(holder.poster)) {
holder.poster.setVisibility(View.VISIBLE);
holder.poster.setImageBitmap(result);
}
}
}
}
I think the problem is that my movie class is empty, but i do have JSON results in asynctask...
Your received data , which you have saved in the list -->movieList.
Have you used it in your adapter and set the adapter to the recycler view.
Initialize recycler view in main class
initialize adapter and pass the movielist as arguement to the adapter object created.
attach the adapter to the recyclerview --> recyclerView.setAdapter(adapter).
I think this should work

How to fix checkboxes auto random selection by scrolling listview, and also shows java.lang.IndexOutOfBoundsException: Invalid index 10, size is 10

Hi i'm new to android and doing custom listview with checkbox, in that i'm facing random selection of another list item checkbox while scrolling. I have gone through some threads but didn't solve my problem. Pls help me out from this. Here is my custom adapter
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class ViewRecord extends Activity {
DataBaseHelper db;
ListView listView;
Button delAll, more, setTime;
ListAdapter list;
CheckBox check;
boolean checks = false;
ArrayList<Contacts> arrayContacts = new ArrayList<Contacts>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.records);
listView = (ListView) findViewById(R.id.listview);
delAll = (Button) findViewById(R.id.delete);
more = (Button) findViewById(R.id.addMore);
setTime = (Button) findViewById(R.id.btnTime);
check = (CheckBox) findViewById(R.id.checkBox1);
loadlist();
// For adding more contacts to BlockList
more.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(ViewRecord.this, ContactList.class);
startActivity(intent);
}
});
// For selecting the whole Records to delete.....
check.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
list = new ListAdapter(getBaseContext());
checks = !checks;
for (int count =0; count<arrayContacts.size(); count++){
listView.setAdapter(list);
list.mCheckStates.put(count, checks);
list.notifyDataSetChanged();
}
// check.toggle();
}
});
}
private void loadlist() {
// TODO Auto-generated method stub
list = new ListAdapter(this);
listView.setAdapter(list);
//listView.setOnItemClickListener(this);
listView.setItemsCanFocus(false);
listView.setTextFilterEnabled(true);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
arrayContacts.clear();
// Reading DataBase Contacts.
db = new DataBaseHelper(getApplicationContext());
db.getWritableDatabase();
ArrayList<Contacts> arrayStor = db.getContacts();
for (int i = 0; i < arrayStor.size(); i++) {
String Id = arrayStor.get(i).getContactId();
String Name = arrayStor.get(i).getContactName();
String Number = arrayStor.get(i).getContactNumber();
Contacts contacts = new Contacts();
contacts.setContactId(Id);
contacts.setContactName(Name);
contacts.setContactNumber(Number);
arrayContacts.add(contacts);
}
// listView.setAdapter(new ListAdapter(this));
db.close();
}
private class ListAdapter extends BaseAdapter implements CompoundButton.OnCheckedChangeListener {
private SparseBooleanArray mCheckStates;
LayoutInflater inflater;
ViewHolder viewHolder;
CheckBox cb;
public ListAdapter(Context context) {
mCheckStates = new SparseBooleanArray(arrayContacts.size());
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return arrayContacts.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return 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) {
convertView = inflater.inflate(R.layout.listview_row, null);
cb = (CheckBox) convertView.findViewById(R.id.checkox);
cb.setTag(position);
cb.setChecked(mCheckStates.get(position, false));
cb.setOnCheckedChangeListener(this);
viewHolder = new ViewHolder();
viewHolder.txtName = (TextView) convertView.findViewById(R.id.txtdisplaypname);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.txtName.setText(arrayContacts.get(position).getContactName().trim());
delAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
AlertDialog.Builder alertbox = new AlertDialog.Builder(
ViewRecord.this);
alertbox.setCancelable(true);
alertbox.setMessage("Are you sure you want to delete ?");
alertbox.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0,
int arg1) {
if(check.isChecked()==true){
db.emptyRecords();
check.toggle();
ViewRecord.this.onResume();
}else
{
for(int i = 0; i < arrayContacts.size(); i++){
{
if(mCheckStates.get(i)==true)
{
db.RemoveRecord(arrayContacts.get(i).getContactId().trim(), "", "");
System.out.println("The contact name and id is :" + arrayContacts.get(i).getContactId() + arrayContacts.get(i).getContactName());
ViewRecord.this.onResume();
}
}
}
Toast.makeText(getApplicationContext()," Records Deleted...",Toast.LENGTH_SHORT).show();
db.close();
}
}
});
alertbox.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0,
int arg1) {
}
});
alertbox.show();
db.close();
}
});
setTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
ArrayList<String> contactName = new ArrayList<String>();
ArrayList<String> contactNumber = new ArrayList<String>();
for(int i = 0; i < arrayContacts.size(); i++)
{
if(mCheckStates.get(i)==true)
{
// For sending contact names to schedule
contactName.add(arrayContacts.get(i).getContactName());
contactNumber.add(arrayContacts.get(i).getContactNumber()) ;
}
}
Intent sendIntent = new Intent (getApplicationContext(), Time_Settings.class);
sendIntent.putExtra("contactName", contactName);
sendIntent.putExtra("contactNumber", contactNumber);
// Toast.makeText(getApplicationContext(), contactName + contactNumber, 0).show();
startActivity(sendIntent);
}
});
return convertView;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, checks);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
notifyDataSetChanged();
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
}
private class ViewHolder {
TextView txtName;
}
}
}
Here i did a view reusing thats why it does auto checking checkboxes, just remove the braces and else part from getView this solved my problem

Difficulty in resizing an image which is stored in a JLabel

I managed to increase an image of JLabel(which has an imageIcon stored in). When I press the increase size button, the original size of the image is increased on the panel, which is exactly what I want. However, when I click on my decrease size button(I figured dividing it by the scale might fix it)the label decreases, but the actual image appearance(size I guess)is changed. It's not decreasing the size, the same way my increase button increases the size. I have spent hours trying to figure out why by multiplying it, I am able to increase the size of a the label and the image in it(which implies that not just the label is increasing, the actual image is too)but for decrease(I'm dividing instead of multiplying)it doesn't work. Here is both my increase and decrease listener.
public class IncreaseSizeListener implements ActionListener {
static JLabel increasedLabel;
#Override
public void actionPerformed(ActionEvent e) {
increasedLabel = CardLabelListener.selectedLabel;
Icon icon = CardLabelListener.selectedLabel.getIcon();
int scale =2;
System.out.println("Increased size fired");
//I can now resize images, based on my needs
BufferedImage bi = new BufferedImage(
scale*icon.getIconWidth(),
scale*icon.getIconHeight(),
BufferedImage.TYPE_INT_ARGB);
Graphics2D g = bi.createGraphics();
g.scale(scale,scale);
icon.paintIcon(null,g,0,0);
g.dispose();
JLabel temp = new JLabel(new ImageIcon(bi));
//to ensure proper size is kept for the enlarged image
CardLabelListener.selectedLabel.setSize(icon.getIconWidth()*scale, icon.getIconHeight()*(scale));
CardLabelListener.selectedLabel.setIcon(temp.getIcon());
CardLabelListener.selectedLabel.updateUI();
}
}
public class DecreaseSizeListener implements ActionListener {
static JLabel increasedLabel;
#Override
public void actionPerformed(ActionEvent e) {
increasedLabel = CardLabelListener.selectedLabel;
Icon icon = CardLabelListener.selectedLabel.getIcon();
int scale =2;
//I can now resize images, based on my needs
BufferedImage bi = new BufferedImage(
icon.getIconWidth()/scale,
icon.getIconHeight()/scale,
BufferedImage.TYPE_INT_ARGB);
Graphics2D g = bi.createGraphics();
g.scale(scale,scale);
icon.paintIcon(null,g,0,0);
g.dispose();
JLabel temp = new JLabel(new ImageIcon(bi));
//to ensure proper size is kept for the enlarged image
CardLabelListener.selectedLabel.setSize( (icon.getIconWidth()/scale), (icon.getIconHeight()/(scale)));
CardLabelListener.selectedLabel.setIcon(temp.getIcon());
CardLabelListener.selectedLabel.updateUI();
}
}
Change g.scale(scale,scale); to g.scale(0.5d,0.5d); in your decrease action listener
Or you could do this...
int scale = 0.5;
//I can now resize images, based on my needs
BufferedImage bi = new BufferedImage(
icon.getIconWidth() * scale,
icon.getIconHeight() * scale,
BufferedImage.TYPE_INT_ARGB);
Graphics2D g = bi.createGraphics();
g.scale(scale,scale);
icon.paintIcon(null,g,0,0);
g.dispose();
// This really isn't required...
//JLabel temp = new JLabel(new ImageIcon(bi));
//to ensure proper size is kept for the enlarged image
// There is a better way...
//CardLabelListener.selectedLabel.setSize( (icon.getIconWidth()/scale), (icon.getIconHeight()/(scale)));
// This isn't required
//CardLabelListener.selectedLabel.setIcon(temp.getIcon());
// This doesn't do what you think it does...
//CardLabelListener.selectedLabel.updateUI();
CardLabelListener.selectedLabel.setIcon(new ImageIcon(bi));
CardLabelListener.selectedLabel.setSize(CardLabelListener.selectedLabel.getPreferredSize());
Now both the increase and decrease algorithm's are just about the same (except for the factor), you should be able to use a single method ;)
This is pretty much the code I ended up with...
public class ScaleMyIcon {
public static void main(String[] args) {
new ScaleMyIcon();
}
public ScaleMyIcon() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new ScaleMyIconPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
protected class ScaleMyIconPane extends JPanel {
public ScaleMyIconPane() {
setLayout(new BorderLayout());
ImageIcon image = null;
try {
image = new ImageIcon(ImageIO.read(getClass().getResource("/stormtrooper-tie.jpg")));
} catch (IOException ex) {
ex.printStackTrace();
}
JLabel label = new JLabel(image);
add(label);
JPanel buttons = new JPanel();
JButton increase = new JButton("+");
JButton decrease = new JButton("-");
buttons.add(increase);
buttons.add(decrease);
increase.addActionListener(new IncreaseSizeListener(label));
decrease.addActionListener(new DecreaseSizeListener(label));
add(buttons, BorderLayout.SOUTH);
}
}
public class Scaler {
public Icon getScaledInstance(Icon original, double scale) {
BufferedImage bi = new BufferedImage(
(int)Math.round(scale * original.getIconWidth()),
(int)Math.round(scale * original.getIconHeight()),
BufferedImage.TYPE_INT_ARGB);
Graphics2D g = bi.createGraphics();
g.scale(scale, scale);
original.paintIcon(null, g, 0, 0);
g.dispose();
return new ImageIcon(bi);
}
}
public class IncreaseSizeListener extends Scaler implements ActionListener {
private JLabel increasedLabel;
private IncreaseSizeListener(JLabel label) {
increasedLabel = label;
}
#Override
public void actionPerformed(ActionEvent e) {
Icon icon = increasedLabel.getIcon();
int scale = 2;
increasedLabel.setIcon(getScaledInstance(icon, scale));
}
}
public class DecreaseSizeListener extends Scaler implements ActionListener {
private JLabel decreasedLabel;
private DecreaseSizeListener(JLabel label) {
decreasedLabel = label;
}
#Override
public void actionPerformed(ActionEvent e) {
Icon icon = decreasedLabel.getIcon();
decreasedLabel.setIcon(getScaledInstance(icon, 0.5d));
}
}
}
UPDATED with different approach
While I was mucking around with it, I noticed two issues. There was no coalition between the up and down scales and you were never using the original image to scale against, you were always scaling the dirty image. Try scaling the image down and back up again.
This is my take on how to overcome those issues
public class ScaleMyIcon {
public static void main(String[] args) {
new ScaleMyIcon();
}
public ScaleMyIcon() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new ScaleMyIconPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
protected class ScaleMyIconPane extends JPanel {
public ScaleMyIconPane() {
setLayout(new BorderLayout());
ImageIcon image = null;
try {
image = new ImageIcon(ImageIO.read(getClass().getResource("/stormtrooper-tie.jpg")));
} catch (IOException ex) {
ex.printStackTrace();
}
JLabel label = new JLabel(image);
add(label);
JPanel buttons = new JPanel();
JButton increase = new JButton("+");
JButton decrease = new JButton("-");
buttons.add(increase);
buttons.add(decrease);
increase.addActionListener(new IncreaseSizeListener(label));
decrease.addActionListener(new DecreaseSizeListener(label));
add(buttons, BorderLayout.SOUTH);
}
}
public static class Scalable {
private JLabel label;
private Icon original;
private static double scale = 1;
private Scalable(JLabel label) {
this.label = label;
original = label.getIcon();
}
public JLabel getLabel() {
return label;
}
public double getScale() {
return scale;
}
public void setScale(double scale) {
this.scale = scale;
}
public void incrementScale(double factor) {
setScale(getScale() + factor);
}
public Icon getScaledInstance() {
BufferedImage bi = new BufferedImage(
(int) Math.round(scale * original.getIconWidth()),
(int) Math.round(scale * original.getIconHeight()),
BufferedImage.TYPE_INT_ARGB);
Graphics2D g = bi.createGraphics();
g.scale(scale, scale);
original.paintIcon(null, g, 0, 0);
g.dispose();
return new ImageIcon(bi);
}
}
public class IncreaseSizeListener extends Scalable implements ActionListener {
public IncreaseSizeListener(JLabel label) {
super(label);
}
#Override
public void actionPerformed(ActionEvent e) {
incrementScale(0.05);
getLabel().setIcon(getScaledInstance());
}
}
public class DecreaseSizeListener extends Scalable implements ActionListener {
private DecreaseSizeListener(JLabel label) {
super(label);
}
#Override
public void actionPerformed(ActionEvent e) {
incrementScale(-0.05);
getLabel().setIcon(getScaledInstance());
}
}
}

Resources