Can't open PDF from asset from list button - android

I have 2 apps that I have PDFs in the asset folders. In app A the code works perfectly fine but in app B it doesn't work. I don't get any errors. When clicking the button in app B it opens adobe acrobat but I get a toast saying "This file could not be accessed. check the location or network and try again". I even put the PDF in app A to make sure nothing was wrong with this PDF file. It opened fine in app A.
Here is my code for app B. I'm trying to open it via a button in a list.
[CODE]
public class InteractiveArrayAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
static final String TAG = InteractiveArrayAdapter.class.getSimpleName();
String ta = "helen.pdf";
GPXParser mParser = new GPXParser();
public InteractiveArrayAdapter(Context context, String[] values) {
super(context, R.layout.rowbuttonlayout, values);
this.context = context;
this.values = values;
}
static class ViewHolder {
protected TextView text,header, number, web;
protected ImageButton web_pic, imageView;
ImageView bike, atv, utv;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (convertView == null) {
LayoutInflater inflator = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflator.inflate(R.layout.rowbuttonlayout, null);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.header = (TextView) view.findViewById(R.id.header);
viewHolder.text = (TextView) view.findViewById(R.id.label);
viewHolder.bike = (ImageView) view.findViewById(R.id.bike);
viewHolder.atv = (ImageView) view.findViewById(R.id.atv);
viewHolder.utv = (ImageView) view.findViewById(R.id.utv);
viewHolder.web_pic = (ImageButton) view.findViewById(R.id.web_pic);
viewHolder.imageView = (ImageButton) view.findViewById(R.id.check);
view.setTag(viewHolder);
viewHolder.imageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent myIntent = new Intent(context, MapActivity.class);
context.startActivity(myIntent);
}
});
viewHolder.web_pic.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
copyReadAssets();
}
});
}
ViewHolder holder = (ViewHolder) view.getTag();
holder.header.setText(values[position]);
holder.imageView.setImageResource(R.drawable.map1);
holder.web_pic.setImageResource(R.drawable.pdf);
holder.bike.setImageResource(R.drawable.bike);
holder.atv.setImageResource(R.drawable.atv_2);
holder.utv.setImageResource(R.drawable.utv);
if (position == 0) {
holder.text.setText("17.82 mi");
}
if (position == 1) {
holder.text.setText("29.09 mi");
}
if (position == 2) {
holder.text.setText("11.06 mi");
}
return view;
}
private void copyReadAssets() {
AssetManager assetManager =context. getAssets();
InputStream in = null;
OutputStream out = null;
File file = new File(context.getFilesDir(), ta);
try {
in = assetManager.open(ta);
out = context.openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e) {
Log.e("tag", e.getMessage());
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(
Uri.parse("file://" +context. getFilesDir() + "/"+ta),
"application/pdf");
context. startActivity(intent);
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
}
}
[CODE/]

Try below code to open PDF,
in = assetManager.open(ta);
String out= Environment.getExternalStorageDirectory().getAbsolutePath() +"/"+ ta);
File outFile = new File(out, ta);
FileOutputStream oStream = new FileOutputStream(outFile);
copyFile(in, oStream);

Related

recyclerview footer click to load images

I'm trying to achieve some thing like the image below. Here when recyclerview is empty it will show the camera imageview in footer and when I click on the image, I can select image from camera or gallery (which will be saved in an internal storage folder) and display them in recyclerview. But I'm getting ArrayIndexOutOfBoundsException in onBindViewHolder in case 1. How to display images from internal folder?
java.lang.ArrayIndexOutOfBoundsException: length=0; index=-1
at java.util.ArrayList.get(ArrayList.java:413)
at com.sam.testapp.ImageAdapter.onBindViewHolder(ImageAdapter.java:85)
at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6279)
at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6312)
at android.support.v7.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5258)
at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5521)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5363)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5359)
at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2141)
at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1525)
at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1488)
at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:585)
at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3506)
at android.support.v7.widget.RecyclerView.onMeasure(RecyclerView.java:2969)
// Activity
public class MainActivity extends AppCompatActivity{
Toolbar toolbar;
RecyclerView recycler;
ImageAdapter adapter;
private ArrayList<Object> itemList;
String[] items = new String [] {"http://i.imgur.com/7P2v384.jpg", "http://i.imgur.com/Fb95GwC.jpg", "http://i.imgur.com/qciJxBg.jpg","http://i.imgur.com/h2jgdAd.jpg"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
recycler = (RecyclerView)findViewById(R.id.recycler);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this, OrientationHelper.HORIZONTAL, false);
recycler.setLayoutManager(linearLayoutManager);
recycler.setItemAnimator(new DefaultItemAnimator());
adapter = new ImageAdapter(MainActivity.this, itemList);
recycler.setAdapter(adapter);
//Collections.addAll(itemList, items);
itemList = new ArrayList<Object>(Arrays.asList(items));
itemList.add(1);
}
}
// Adapter
public class ImageAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context mContext;
private static final int TYPE_FOOTER = 0;
private static final int TYPE_ITEM = 1;
final CharSequence[] items = {
"Camera", "Gallery", "Cancel"
};
private ArrayList<Object> finalImages = new ArrayList<>();
private static final String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/TESTAPP";
public ImageAdapter(Context context, ArrayList<Object> itemList) {
this.finalImages = itemList;
this.mContext = context;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder viewHolder = null;
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
switch (viewType) {
case 0:
View v0 = LayoutInflater.from(parent.getContext()).inflate(R.layout.customrowlayout, parent, false);
viewHolder = new VHFooter(v0);
break;
case 1:
View v1 = inflater.inflate(R.layout.imagerowlayout, parent, false);
viewHolder = new VHItem(v1);
break;
}
return viewHolder;
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
switch (holder.getItemViewType()) {
case 0:
VHFooter vh0 = (VHFooter) holder;
vh0.imgv.setImageResource(R.drawable.camera);
vh0.imgv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showDialog();
}
});
break;
case 1:
VHItem vh1 = (VHItem) holder;
String path = (String) finalImages.get(position);
if (!TextUtils.isEmpty(path)) {
Picasso.with(mContext).load(path).into(vh1.image);
}
break;
}
}
private void showDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
((Activity) mContext).startActivityForResult(intent, 0);
dialog.dismiss();
} else if (item == 1) {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
((Activity) mContext).startActivityForResult(intent, 1);
dialog.dismiss();
} else if (item == 2) {
dialog.dismiss();
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == 0) {
savefile(data, true);
loadfile();
} else if (resultCode == RESULT_OK && requestCode == 1) {
savefile(data, false);
loadfile();
}
}
private void savefile(Intent data, boolean isCamera) {
if (isCamera) {
Bitmap bmap = (Bitmap) data.getExtras().get("data");
File directory = new File(file_path);
if (!directory.exists()) {
directory.mkdirs();
}
File file = new File(directory, "myimage.jpg");
try {
FileOutputStream fos = new FileOutputStream(file);
bmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
Uri uri = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = mContext.getContentResolver().query(uri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
Bitmap bmap = (BitmapFactory.decodeFile(picturePath));
File directory = new File(file_path);
if (!directory.exists()) {
directory.mkdirs();
}
String timeStamp = new SimpleDateFormat("yyyyMMdd-HHmmss", Locale.ENGLISH).format(new Date());
File file = new File(directory, "IMG_" + timeStamp + ".jpg");
try {
FileOutputStream fos = new FileOutputStream(file);
bmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void loadfile() {
File directory = new File(file_path);
File newfile[] = directory.listFiles();
Log.e("sammy_arrlistsize_befor", " " + finalImages.size());
if (finalImages != null) finalImages.clear();
for (int i = 0; i < newfile.length; i++) {
String path = "file://" + newfile[i].getAbsolutePath();
finalImages.add(path);
Log.e("sammy_imagepath", " " + path);
}
Log.e("sammy_arrlistsize_after", " " + finalImages.size());
notifyDataSetChanged();
}
#Override
public int getItemCount() {
return this.finalImages.size();
}
#Override
public int getItemViewType(int position) {
if (finalImages.get(position) instanceof String) {
return TYPE_ITEM;
} else if (finalImages.get(position) instanceof Integer) {
return TYPE_FOOTER;
}
return -1;
}
class VHItem extends RecyclerView.ViewHolder {
ImageView image;
public VHItem(View itemView) {
super(itemView);
image = (ImageView) itemView.findViewById(R.id.image);
}
}
class VHFooter extends RecyclerView.ViewHolder {
ImageView imgv;
public VHFooter(View itemView) {
super(itemView);
imgv = (ImageView) itemView.findViewById(R.id.imgv);
}
}
}
First in MainActivity
private ArrayList<Object> itemList = new ArrayList<>();
itemList.addAll(yourStringList);
itemList.add(1);
then use below adapter class
public class ImageAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context mContext;
private static final int TYPE_FOOTER = 0;
private static final int TYPE_ITEM = 1;
final CharSequence[] items = {
"Camera", "Gallery", "Cancel"
};
private ArrayList<Object> finalImages = new ArrayList<>();
private static final String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/TESTAPP";
public ImageAdapter(Context context, ArrayList<Object> itemList) {
this.finalImages = itemList;
this.mContext = context;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder viewHolder = null;
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
switch (viewType) {
case 0:
View v0 = LayoutInflater.from(parent.getContext()).inflate(R.layout.customrowlayout, parent, false);
viewHolder = new VHFooter(v0);
break;
case 1:
View v1 = inflater.inflate(R.layout.imagerowlayout, parent, false);
viewHolder = new VHItem(v1);
break;
}
return viewHolder;
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
switch (holder.getItemViewType()) {
case 0:
VHFooter vh0 = (VHFooter) holder;
vh0.imgv.setImageResource(R.drawable.camera);
// Picasso.with(mContext).load(R.drawable.camera).into(vh0.imgv);
//piccaso is commented for now
vh0.imgv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showDialog();
}
});
break;
case 1:
VHItem vh1 = (VHItem) holder;
String path = (String) finalImages.get(position);
if (!TextUtils.isEmpty(path)) {
Picasso.with(mContext).load(path).into(vh1.image);
}
break;
}
}
private void showDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
((Activity) mContext).startActivityForResult(intent, 0);
dialog.dismiss();
} else if (item == 1) {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
((Activity) mContext).startActivityForResult(intent, 1);
dialog.dismiss();
} else if (item == 2) {
dialog.dismiss();
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == 0) {
savefile(data, true);
loadfile();
} else if (resultCode == RESULT_OK && requestCode == 1) {
savefile(data, false);
loadfile();
}
}
private void savefile(Intent data, boolean isCamera) {
if (isCamera) {
Bitmap bmap = (Bitmap) data.getExtras().get("data");
File directory = new File(file_path);
if (!directory.exists()) {
directory.mkdirs();
}
File file = new File(directory, "myimage.jpg");
try {
FileOutputStream fos = new FileOutputStream(file);
bmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
Uri uri = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = mContext.getContentResolver().query(uri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
Bitmap bmap = (BitmapFactory.decodeFile(picturePath));
File directory = new File(file_path);
if (!directory.exists()) {
directory.mkdirs();
}
String timeStamp = new SimpleDateFormat("yyyyMMdd-HHmmss", Locale.ENGLISH).format(new Date());
File file = new File(directory, "IMG_" + timeStamp + ".jpg");
try {
FileOutputStream fos = new FileOutputStream(file);
bmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void loadfile() {
File directory = new File(file_path);
File newfile[] = directory.listFiles();
Log.e("sammy_arrlistsize_befor", " " + finalImages.size());
if (finalImages != null) finalImages.clear();
for (int i = 0; i < newfile.length; i++) {
String path = "file://" + newfile[i].getAbsolutePath();
finalImages.add(path);
Log.e("sammy_imagepath", " " + path);
}
Log.e("sammy_arrlistsize_after", " " + finalImages.size());
notifyDataSetChanged();
}
#Override
public int getItemCount() {
return this.finalImages.size();
}
#Override
public int getItemViewType(int position) {
if (finalImages.get(position) instanceof String) {
return TYPE_ITEM;
} else if (finalImages.get(position) instanceof Integer) {
return TYPE_FOOTER;
}
return -1;
}
class VHItem extends RecyclerView.ViewHolder {
ImageView image;
public VHItem(View itemView) {
super(itemView);
image = (ImageView) itemView.findViewById(R.id.image);
}
}
class VHFooter extends RecyclerView.ViewHolder {
ImageView imgv;
public VHFooter(View itemView) {
super(itemView);
imgv = (ImageView) itemView.findViewById(R.id.imgv);
}
}
}
Your exception is being thrown because
#Override
public int getItemCount() {
return this.finalImages.size()+1;
}
should be
#Override
public int getItemCount() {
return this.finalImages.size();
}

share listview item (url image and text ) on facebook

I am fetching data from server and set it into listview. Each Listview item have photo ( url image ) and a text + share button . I have implemented all the code and working perfect.. But can any one help me.. How to implement facebook share intent when click on button of particular listview item.I want to share image and text
i ask from a way to the this
and thank you in advance
this is my code "MediaAdapter.java" :
public class MediaAdapter extends ArrayAdapter<Media> {
ArrayList<Media> mediaList;
Context context;
int Resource;
LayoutInflater vi;
ViewHolder holder;
ImageLoader imageLoader;
public MediaAdapter(Context context, int resource, ArrayList<Media> objects) {
super(context, resource, objects);
imageLoader = new ImageLoader(context);
vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = resource;
mediaList = objects;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// convert view = design
View v = convertView;
v = vi.inflate(Resource, null);
holder = new ViewHolder();
int loader = R.drawable.ic_launcher;
//l url d image
holder.imageview = (ImageView) v.findViewById(R.id.urlImage);
// load image
imageLoader.DisplayImage(mediaList.get(position).getUrl(), loader, holder.imageview );
holder.titre = (TextView) v.findViewById(R.id.titre);
holder.titre.setText(mediaList.get(position).getTitre());
v.setTag(holder);
holder.button = (Button) v.findViewById(R.id.btnOne);
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(v.getContext(), "test",Toast.LENGTH_SHORT).show();
}
});
return v;
}
static class ViewHolder {
public ImageView imageview;
public TextView titre;
public Button button;
}
}
Change this in the code ....
First remove this line from the constructor
imageLoader = new ImageLoader(context);
Change it to
ImageLoader imageLoader = ImageLoader.getInstance();
Secondly remove this line from the code :
imageLoader.DisplayImage(mediaList.get(position).getUrl(), loader, holder.imageview );
Change it to
imageLoader.loadImage(mediaList.get(position).getUrl(), new SimpleImageLoadingListener() {
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT,mediaList.get(position).getTitre());
shareIntent.setType("image/*");
shareIntent.putExtra(Intent.EXTRA_STREAM, getImageUri(context,loadedImage));
try {
context.startActivity(shareIntent);
} catch (Exception ex) {
Toast.makeText(context, ex.getMessage(),Toast.LENGTH_LONG).show();
}
}
});
}
});
Use this method to transform bitmap to uri:
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = Images.Media.insertImage(inContext.getContentResolver(),inImage, "Title", null);
return Uri.parse(path);
}
This will open the the share option for sharing to all the other apps including facebook. If facebook is selected by the user,then the image will be opened in the facebook app (if installed).Let me know if it working for you or not.
this is my new coode
it work like a charm
but i have a problem : but i have a problem when i click on share button of the item Number 2 ===== the content of the item number 3 is shared and note the Number 2 and vice-versa ????????????????
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Uri pictureUri = getLocalBitmapUri(holder.imageview);
if (pictureUri != null) {
// Construct a ShareIntent with link to image
String text = "image : "+mediaList.get(position).getTitre();
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_TEXT, text);
shareIntent.putExtra(Intent.EXTRA_STREAM, pictureUri);
shareIntent.setType("image/*");
// Launch sharing dialog for image
shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(shareIntent);
} else {
// ...sharing failed, handle error
}
///////////////////////////////////////////////////////////
private Uri getLocalBitmapUri(ImageView imageview) {
// TODO Auto-generated method stub
// Extract Bitmap from ImageView drawable
Drawable drawable =holder.imageview.getDrawable();
Bitmap bmp = null;
if (drawable instanceof BitmapDrawable){
bmp = ((BitmapDrawable) holder.imageview.getDrawable()).getBitmap();
} else {
return null;
}
// Store image to default external storage directory
Uri bmpUri = null;
try {
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), "share_image_" + System.currentTimeMillis() + ".png");
file.getParentFile().mkdirs();
FileOutputStream out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
bmpUri = Uri.fromFile(file);
} catch (IOException e) {
e.printStackTrace();
}
return bmpUri;
}

java.lang.IndexOutOfBoundsException: Invalid index 3, size is 2 in viewpager

In my application am using two languages using same adapter, first if user select first language, the data populate in ViewPager, if we swipe two,three pages after that if we change another language data populate in ViewPager, but if we click any button in pager ,it show this
error java.lang.IndexOutOfBoundsException: Invalid index 3, size is 2,
can anyone give solution for this error , thanks in advance.
public class MyCustomAdapter extends PagerAdapter {
Context context1;
LayoutInflater inflater = null;
String title;
public static LinearLayout full_link, containers, language;
public static Uri bmpUri = null;
TextView txtfullstory;
int pStatus = 0;
private Handler handler = new Handler();
public static Bitmap bitmap;
private SharedPreferences.Editor editor;
private SharedPreferences pref;
String user_type_id;
public MyCustomAdapter(Context context1,
ArrayList<String> NewsidArray,
ArrayList<String> NewsdescArray,
ArrayList<String> NewstitleArray,
ArrayList<String> NewsimageArray,
ArrayList<String> NewsdateArray,
ArrayList<String> NewsauthorArray,
ArrayList<String> NewsurlArray) {
this.context1 = context1;
newsidArray = NewsidArray;
newsdescArray = NewsdescArray;
newstitleArray = NewstitleArray;
newsimageArray = NewsimageArray;
newsdateArray = NewsdateArray;
newsauthorArray = NewsauthorArray;
newsurlArray = NewsurlArray;
}
#Override
public int getCount() {
if (newstitleArray == null) {
return 0;
}
return newstitleArray.size();
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
public Object instantiateItem(ViewGroup container, final int position) {
final int delPosition = position;
final Holder holder = new Holder();
inflater = (LayoutInflater) context1.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View itemView = inflater.inflate(R.layout.fragment_layout, container, false);
holder.date = (TextView) itemView.findViewById(R.id.txtdate);
holder.txttitle = (TextView) itemView.findViewById(R.id.txttitle);
holder.txtdesc = (TextView) itemView.findViewById(R.id.txtdesc);
holder.txtauthor = (TextView) itemView.findViewById(R.id.txtauthor);
holder.imageview = (ImageView) itemView.findViewById(R.id.imageview);
holder.share = (ImageView) itemView.findViewById(R.id.share);
holder.url = (TextView) itemView.findViewById(R.id.url);
holder.reverse = (ImageView) itemView.findViewById(R.id.reverse);
holder.progress = (ProgressBar) itemView.findViewById(R.id.progress);
full_link = (LinearLayout)itemView.findViewById(R.id.line_above);
containers = (LinearLayout)itemView.findViewById(R.id.containers);
language = (LinearLayout)itemView.findViewById(R.id.language);
txtfullstory = (TextView) itemView.findViewById(R.id.txtfullstory);
String date = newsdateArray.get(position).toString();
String image = newsimageArray.get(position).toString();
holder.txtdesc.setText(Html.fromHtml(newsdescArray.get(position).toString()));
holder.txttitle.setText(Html.fromHtml(newstitleArray.get(position).toString()));
holder.txtauthor.setText(Html.fromHtml(newsauthorArray.get(position).toString()));
holder.url.setText(newsurlArray.get(position).toString());
Typeface font = Typeface.createFromAsset(context1.getAssets(), "fonts/Seravek.ttc");
holder.txtdesc.setTypeface(font);
holder.txttitle.setTypeface(font, Typeface.BOLD);
holder.txtauthor.setTypeface(font);
title = newstitleArray.get(position);
pref = context1.getSharedPreferences("MyPref", 0);
editor = pref.edit();
user_type_id = pref.getString("langid", null);
if(user_type_id != null && user_type_id.equals("2")){
txtfullstory.setText(Html.fromHtml("पर पूरी कहानी"));
}else {
txtfullstory.setText(Html.fromHtml("Full story on"));
}
try {
#SuppressLint("SimpleDateFormat") SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:sss");
Date parsedDate = dateFormat1.parse(date);
long times = parsedDate.getTime();
new Timestamp(times);
String result = (String) DateUtils.getRelativeTimeSpanString(times, System.currentTimeMillis() + 5 * 60 * 1000, 0);
holder.date.setText(result);
} catch (ParseException e) {
Log.d("Error", e.getMessage());
}
if(!(!image.equalsIgnoreCase("") && !image.equalsIgnoreCase(null))) {
holder.imageview.setVisibility(View.INVISIBLE);
}
else{
holder.progress.setVisibility(View.VISIBLE);
holder.imageview.setVisibility(View.INVISIBLE);
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while (pStatus <= 100) {
handler.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
holder.progress.setProgress(pStatus);
holder.progress.setSecondaryProgress(pStatus + 5);
}
});
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
pStatus++;
}
}
}).start();
holder.imageview.setScaleType(ImageView.ScaleType.FIT_XY);
Picasso.with(context1).load(WebService.WS_ImageOnlineURL + image).fit().centerCrop()
.error(R.drawable.image_loading).transform(new RoundedTransformation(4, 0)).into(holder.imageview, new Callback()
{
#Override
public void onSuccess()
{
holder.progress.setVisibility(View.INVISIBLE);
holder.imageview.setVisibility(View.VISIBLE);
}
#Override
public void onError()
{
}
});
}
itemView.setDrawingCacheEnabled(true);
itemView.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
itemView.layout(0, 0, 300, 400);
itemView.buildDrawingCache(true);
holder.share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.share.setVisibility(View.INVISIBLE);
holder.reverse.setVisibility(View.VISIBLE);
bitmap = Bitmap.createBitmap(itemView.getWidth(), itemView.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
itemView.draw(canvas);
try {
// output = new FileOutputStream(Environment.getExternalStorageDirectory() + "/path/to/file.png");
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), "share_image_" + System.currentTimeMillis() + ".png");
// File file = new File(Environment.getExternalStorageDirectory().getAbsoluteFile(), "share_image_" + System.currentTimeMillis() + ".png");
file.getParentFile().mkdirs();
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.close();
bmpUri = Uri.fromFile(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
holder.share.setVisibility(View.VISIBLE);
holder.reverse.setVisibility(View.INVISIBLE);
try {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
sendIntent.putExtra(Intent.EXTRA_TEXT, newstitleArray.get(myCustomPosition) + "\r\n" + "Get odd news only on Oddcast" + "\r\n" + "https://goo.gl/8jeJga");
sendIntent.setType("image/*");
context1.startActivity(sendIntent);
}catch(Exception e) {
e.printStackTrace();
}
}
});
holder.txttitle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
holder.share.setVisibility(View.INVISIBLE);
holder.reverse.setVisibility(View.VISIBLE);
bitmap = Bitmap.createBitmap(itemView.getWidth(),itemView.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
itemView.draw(canvas);
try {
// output = new FileOutputStream(Environment.getExternalStorageDirectory() + "/path/to/file.png");
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), "share_image_" + System.currentTimeMillis() + ".png");
// File file = new File(Environment.getExternalStorageDirectory().getAbsoluteFile(), "share_image_" + System.currentTimeMillis() + ".png");
file.getParentFile().mkdirs();
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.close();
bmpUri = Uri.fromFile(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
holder.share.setVisibility(View.VISIBLE);
holder.reverse.setVisibility(View.INVISIBLE);
Intent i = new Intent(context1, NewsDetailActivity.class);
i.putExtra("url", "" + newsurlArray.get(myCustomPosition));
i.putExtra("title", "" + newstitleArray.get(myCustomPosition));
context1.startActivity(i);
}
});
full_link.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
holder.share.setVisibility(View.INVISIBLE);
holder.reverse.setVisibility(View.VISIBLE);
bitmap = Bitmap.createBitmap(itemView.getWidth(),itemView.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
itemView.draw(canvas);
try {
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "share_image_" + System.currentTimeMillis() + ".png");
file.getParentFile().mkdirs();
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.close();
bmpUri = Uri.fromFile(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
holder.share.setVisibility(View.VISIBLE);
holder.reverse.setVisibility(View.INVISIBLE);
Intent i = new Intent(context1, NewsDetailActivity.class);
i.putExtra("url", "" + newsurlArray.get(myCustomPosition));
i.putExtra("title", "" + newstitleArray.get(myCustomPosition));
context1.startActivity(i);
}
});
language.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("newstitleArray", String.valueOf(newstitleArray.size()));
Intent language = new Intent(context1, UserPreferedLanguage.class);
context1.startActivity(language);
Activity activity = (Activity) context1;
activity.overridePendingTransition(R.anim.left_in, R.anim.right_out);
}
});
container.addView(itemView);
return itemView;
}
public class Holder {
TextView date,txtauthor,txttitle,txtdesc,url; //Initialize TextView variable
ImageView imageview,share,reverse;
ProgressBar progress;
}
public void destroyItem(ViewGroup container, int position, Object object) {
((LinearLayout) object).removeView(container);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
}
Execeptions
java.lang.IndexOutOfBoundsException: Invalid index 3, size is 2
java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
java.util.ArrayList.get(ArrayList.java:308)
oddcast.jetlabs.com.oddcast.adapter.MyCustomAdapter$3.onClick(MyCustomAdapter.java:267)
android.view.View.performClick(View.java:4761)
android.view.View$PerformClick.run(View.java:19767)
android.os.Handler.handleCallback(Handler.java:739)
android.os.Handler.dispatchMessage(Handler.java:95)
android.os.Looper.loop(Looper.java:135)
android.app.ActivityThread.main(ActivityThread.java:5312)
java.lang.reflect.Method.invoke(Native Method)
java.lang.reflect.Method.invoke(Method.java:372)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)

Android custom adapter list view images showing randomly while scroll

Hi i am a noob to android, I am trying to load some data to a ListView using custom adapter. I am using the following code for loading data. First time, it working well. But while I am trying to load more, then data loads and image is showing random while scrolling. After showing some random images in that list finally shows the correct image. It is repeating on the next scroll also
Here is my getView code
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
final ViewHolder holder;
if (v == null) {
LayoutInflater vi =
(LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.review_list_m, null);
v.setMinimumHeight(height);
holder = new ViewHolder();
holder.item1 = (TextView) v.findViewById(R.id.name);
holder.image = (ImageView) v.findViewById(R.id.posterView);
v.setTag(holder);
}
else
holder=(ViewHolder)v.getTag();
int colorPos = position % colors.length;
v.setBackgroundColor(Color.parseColor(colors[colorPos]));
final Custom custom = entries.get(position);
if (custom != null) {
holder.image.setBackgroundColor(Color.parseColor(colors[colorPos]));
holder.image.setLayoutParams(new LinearLayout.LayoutParams(height-10,width-10));
String imgUrl=custom.getImage();
AsyncHttpClient client = new AsyncHttpClient();
String[] allowedContentTypes = new String[] { "image/png", "image/jpeg" };
client.get(imgUrl, new BinaryHttpResponseHandler(allowedContentTypes) {
#Override
public void onSuccess(byte[] fileData) {
// Do something with the file
ByteArrayInputStream inputStream = new ByteArrayInputStream(fileData);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
holder.image.setImageBitmap(bitmap);
}
});
holder.item1.setHeight(height/3);
Log.v("PATH",custom.getcustomBig());
holder.item1.setText(custom.getcustomBig());
}
return v;
}
Any idea ? Please help
UPDATE
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
final ViewHolder holder;
if (v == null) {
LayoutInflater vi =
(LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.review_list_m, null);
v.setMinimumHeight(height);
holder = new ViewHolder();
holder.item1 = (TextView) v.findViewById(R.id.name);
holder.image = (ImageView) v.findViewById(R.id.posterView);
v.setTag(holder);
}
else
holder=(ViewHolder)v.getTag();
int colorPos = position % colors.length;
v.setBackgroundColor(Color.parseColor(colors[colorPos]));
final Custom custom = entries.get(position);
if (custom != null) {
holder.image.setBackgroundColor(Color.parseColor(colors[colorPos]));
holder.image.setLayoutParams(new LinearLayout.LayoutParams(height-10,width-10));
final String imgUrl=custom.getImage();
holder.image.setTag(imgUrl);
holder.image.setImageBitmap(null);
Bitmap cachedBitmap = cache.get(imgUrl);
if( cachedBitmap == null) {
Log.v("HERE","DOWNLOADING");
AsyncHttpClient client = new AsyncHttpClient();
String[] allowedContentTypes = new String[] { "image/png", "image/jpeg" };
client.get(imgUrl, new BinaryHttpResponseHandler(allowedContentTypes) {
#Override
public void onSuccess(byte[] fileData) {
// Do something with the file
ByteArrayInputStream inputStream = new ByteArrayInputStream(fileData);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
holder.image.setImageBitmap(bitmap);
}
});
}
else
{
holder.image.setImageBitmap(cachedBitmap);
}
holder.item1.setHeight(height/3);
//Log.v("PATH",custom.getcustomBig());
holder.item1.setText(custom.getcustomBig());
}
Problably you should set null bitmap to holder.image if v != null. Otherwise Android can show bitmap from other cell until new image is downloaded via async http request.
Example code (for problem with redownload images), it wasn't testes, but should give you idea how should it looks:
HashMap<String, Bitmap> cache = new HashMap<String, Bitmap>();
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//....
final Custom custom = entries.get(position);
if (custom != null) {
holder.image.setBackgroundColor(Color.parseColor(colors[colorPos]));
holder.image.setLayoutParams(new LinearLayout.LayoutParams(height-10,width-10));
String imgUrl=custom.getImage();
Bitmap cachedBitmap = cache.get(imgUrl);
if( cachedBitmap == null) {
AsyncHttpClient client = new AsyncHttpClient();
String[] allowedContentTypes = new String[] { "image/png", "image/jpeg" };
client.get(imgUrl, new BinaryHttpResponseHandler(allowedContentTypes) {
#Override
public void onSuccess(byte[] fileData) {
// Do something with the file
ByteArrayInputStream inputStream = new ByteArrayInputStream(fileData);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
holder.image.setImageBitmap(bitmap);
cache.add( imgUrl, bitmap );
}
});
}
else
{
holder.image.setImageBitmap(cachedBitmap);
}
holder.item1.setHeight(height/3);
Log.v("PATH",custom.getcustomBig());
holder.item1.setText(custom.getcustomBig());
}
EDITed answer
Validate your imageview's tag hasn't change before you set the Bitmap.
You could try:
/**
* Caches an image (or a group of them) async.
* #author
*
*/
public static class ImageCacher extends AsyncTask<String, String, Integer>{
Context context;
ImageView iv;
Bitmap b;
public ImageCacher(Context context, ImageView iv){
this.context = context;
this.iv = iv;
}
#Override
protected Integer doInBackground(String... params) {
for(final String param:params){
//check if already CACHED
String filename = String.format("%d", param.hashCode());
File file = new File(context.getFilesDir(), filename);
if(file.exists()){
try {
b = BitmapFactory.decodeFile(file.getAbsolutePath());
} catch (Exception e) {
}
if(b != null){
if(iv != null){
iv.post(new Runnable() {
public void run() {
String tag = (String) iv.getTag();
if(tag != null){
if(tag.matches(param))
iv.setImageBitmap(b);
}
}
});
}
return 0;
}else{
file.delete();
}
}
//download
file = new File(context.getFilesDir(), filename);
b = saveImageFromUrl(context, param);
if(b != null){
if(iv != null){
iv.post(new Runnable() {
public void run() {
String tag = (String) iv.getTag();
if(tag != null){
if(tag.matches(param))
iv.setImageBitmap(b);
}
}
});
}
}
}
return 0;
}
}
/**
* Gets an image given its url
* #param param
*/
public static Bitmap saveImageFromUrl(Context context, String fullUrl) {
Bitmap b = null;
try {
URL url = new URL(fullUrl);
URLConnection conn = url.openConnection();
conn.setDoInput(true);
conn.connect();
//save bitmap to file
InputStream is = conn.getInputStream();
String filename = String.format("%d", fullUrl.hashCode());
File file = new File(context.getFilesDir(), filename);
if(file.exists()){
//delete
file.delete();
file=null;
}
file = new File(context.getFilesDir(), filename);
FileOutputStream out = new FileOutputStream(file);
byte buffer[] = new byte[256];
while(true){
int cnt = is.read(buffer);
if(cnt <=0){
break;
}
out.write(buffer,0, cnt);
}
out.flush();
out.close();
is.close();
b = BitmapFactory.decodeFile(file.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
}
return b;
}
/**
* Gets an already cached photo
*
* #param context
* #param fullUrl
* #return
*/
public static Bitmap getCachedPhoto(Context context, String fullUrl){
System.gc();
String filename = String.format("%d", fullUrl.hashCode());
File file = new File(context.getFilesDir(), filename);
if(file.exists()){
try {
Bitmap b = BitmapFactory.decodeFile(file.getAbsolutePath());
return b;
} catch (Exception e) {
}
}
return null;
}
And then, to set the image in the adapter, you can do like:
//set info
vh.iv.setTag("");
String foto = your_url_goes_here;
vh.iv.setImageResource(R.drawable.fotodefault_2x);
if(!TextUtils.isEmpty(foto)){
vh.iv.setTag(foto);
Bitmap b = getCachedPhoto(context, foto);
if(b != null){
vh.iv.setImageBitmap(b);
}else{
new ImageCacher(context, vh.iv).execute(foto);
}
}
Don't forget to correctly encapsulate the class and methods.
Hope it helps.
I had this random pictures problem with my arrayAdapter. Then I used Picasso which takes care of imageView reusing in listview: http://square.github.io/picasso/
Example of code:
Picasso.with(mContext)
.load(url)
.resize(size, size)
.centerCrop()
.placeholder(R.drawable.image_holder)
.into(holder.imgDefaultImage);

Check when onClick is checked only?

I have a checkbox, that when checked, makes a bitmap and then saves that bitmap to internal storage. Then, in a gridView adapter, I have it check for the bitmap from internal storage with FileInputstream.
The issue is that the checkbox's onClick method is also in a class that extends baseadapter.
With the way it is now, when I start my app, it automatically checks for the bitmap and then returns a FileNotFound exception and then the onClick of the checkbox doesn't do anything.
I thought about this and realized that the reason it checks for it is that it is creating the gridView when I first open my app (which it is supposed to). In other words, it checks for the file because it is in the getView() method of my gridView adapter:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Try to reuse the views
ImageView view = (ImageView) convertView;
// if convert view is null then create a new instance else reuse it
if (view == null) {
view = new ImageView(Context);
Log.d("GridViewAdapter", "new imageView added");
}
try {
Bitmap bitmapA = null;
FileInputStream in = Context.openFileInput("bitmapA");
bitmapA = BitmapFactory.decodeStream(in);
in.close();
/*BufferedInputStream buf = new BufferedInputStream(in);
byte[] bitMapA = new byte[buf.available()];
buf.read(bitMapA);
Bitmap bM = BitmapFactory.decodeByteArray(bitMapA, 0, bitMapA.length);
*/view.setImageBitmap(bitmapA);
if (in != null) {
in.close();
}
/*if (buf != null) {
buf.close();
}*/
} catch (Exception e) {
e.printStackTrace();
}
view.setImageResource(drawables.get(position));
view.setScaleType(ImageView.ScaleType.CENTER_CROP);
view.setLayoutParams(new android.widget.GridView.LayoutParams(70, 70));
view.setTag(String.valueOf(position));
return view;
}
Is there a way that I can make it check internal storage ONLY IF the checkbox is checked?
Please note that the onClick method of the checkbox is in one class while I am getting the bitmap in another.
Here are my two full classes:
AppInfoAdapter (the one with the onClick method---I will only post the needed coding here):
package com.example.awesomefilebuilderwidget;
IMPORTS
public class AppInfoAdapter extends BaseAdapter {
private Context mContext;
private List<ResolveInfo> mListAppInfo;
private PackageManager mPackManager;
private List<ResolveInfo> originalListAppInfo;
private Filter filter;
private String fname;
public AppInfoAdapter(Context c, List<ResolveInfo> listApp,
PackageManager pm) {
mContext = c;
this.originalListAppInfo = this.mListAppInfo = listApp;
mPackManager = pm;
Log.d("AppInfoAdapter", "top");
}
#Override
public int getCount() {
Log.d("AppInfoAdapter", "getCount()");
return mListAppInfo.size();
}
#Override
public Object getItem(int position) {
Log.d("AppInfoAdapter", "getItem");
return mListAppInfo.get(position);
}
#Override
public long getItemId(int position) {
Log.d("AppInfoAdapter", "getItemId");
return position;
}
public static Bitmap scaleDownBitmap(Bitmap default_b, int newHeight, Context c) {
final float densityMultiplier = c.getResources().getDisplayMetrics().density;
int h= (int) (100*densityMultiplier);
int w= (int) (h * default_b.getWidth()/((double) default_b.getHeight()));
default_b=Bitmap.createScaledBitmap(default_b, w, h, true);
// TO SOLVE LOOK AT HERE:http://stackoverflow.com/questions/15517176/passing-bitmap-to-other-activity-getting-message-on-logcat-failed-binder-transac
return default_b;
}
public void SaveImage(Bitmap default_b) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 100000;
n = generator.nextInt(n);
String fname = "Image-" + n +".png";
File file = new File (myDir, fname);
Log.i("AppInfoAdapter", "" + file);
if (file.exists()) file.delete();
try {
// File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
// + "/" + fname + ".png");
FileOutputStream out = mContext.getApplicationContext().openFileOutput("bitmapA", Context.MODE_WORLD_WRITEABLE);
// FileOutputStream out = new FileOutputStream(file);
default_b.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// get the selected entry
final ResolveInfo entry = (ResolveInfo) mListAppInfo.get(position);
// reference to convertView
View v = convertView;
// inflate new layout if null
if (v == null) {
LayoutInflater inflater = LayoutInflater.from(mContext);
v = inflater.inflate(R.layout.layout_appinfo, null);
Log.d("AppInfoAdapter", "New layout inflated");
}
// load controls from layout resources
ImageView ivAppIcon = (ImageView) v.findViewById(R.id.ivIcon);
TextView tvAppName = (TextView) v.findViewById(R.id.tvName);
TextView tvPkgName = (TextView) v.findViewById(R.id.tvPack);
final CheckBox addCheckbox = (CheckBox) v
.findViewById(R.id.addCheckbox);
Log.d("AppInfoAdapter", "Controls from layout Resources Loaded");
// set data to display
ivAppIcon.setImageDrawable(entry.loadIcon(mPackManager));
tvAppName.setText(entry.activityInfo.loadLabel(mPackManager));
tvPkgName.setText(entry.activityInfo.packageName);
Log.d("AppInfoAdapter", "Data Set To Display");
addCheckbox
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (addCheckbox.isChecked()) {
System.out.println("Checked");
PackageManager pm = mContext.getPackageManager();
Drawable icon = null;
try {
icon = pm
.getApplicationIcon(entry.activityInfo.packageName);
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Drawable default_icon = pm.getDefaultActivityIcon();
if (icon instanceof BitmapDrawable
&& default_icon instanceof BitmapDrawable) {
BitmapDrawable icon_bd = (BitmapDrawable) icon;
Bitmap icon_b = icon_bd.getBitmap();
BitmapDrawable default_bd = (BitmapDrawable) pm
.getDefaultActivityIcon();
Bitmap default_b = default_bd.getBitmap();
if (icon_b == default_b) {
// It's the default icon
scaleDownBitmap(default_b, 100, v.getContext());
Log.d("AppInfoAdapter", "Scale Bitmap Chosen");
SaveImage(default_b);
Log.d("AppInfoAdapter", "Scaled BM saved to External Storage");
Intent intent = new Intent(v.getContext(), GridViewAdapter.class);
// intent.hasExtra("bitmapA");
v.getContext().startActivity(intent);
Log.d("AppInfoAdapter", "Intent started to send Bitmap");
}
}
} else {
System.out.println("Un-Checked");
}
}
});
// return view
return v;
}
GridViewAdapter:
package com.example.awesomefilebuilderwidget;
IMPORTS
public class GridViewAdapter extends BaseAdapter {
private Context Context;
// Keep all Images in array list
public ArrayList<Integer> drawables = new ArrayList<Integer>();
// Constructor
public GridViewAdapter(Context c){
Context = c;
Log.d("GridViewAdapter", "Constructor is set");
drawables.add(R.drawable.pattern1);
Log.d("GridViewAdapter", "pattern1 added");
drawables.add(R.drawable.pattern2);
Log.d("GridViewAdapter", "pattern2 added");
drawables.add(R.drawable.trashcan);
Log.d("GridViewAdapter", "trashcan added");
drawables.add(R.drawable.ic_launcher);
Log.d("GridViewAdapter", "ic_launcher added");
Bitmap default_b = BitmapFactory.decodeFile("picture");
}
#Override
// How many items are in the data set represented by this Adapter
public int getCount() {
return drawables.size();
}
#Override
// Get the data item associated with the specified position in the
// data set
public Object getItem(int position) {
return drawables.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Try to reuse the views
ImageView view = (ImageView) convertView;
// if convert view is null then create a new instance else reuse it
if (view == null) {
view = new ImageView(Context);
Log.d("GridViewAdapter", "new imageView added");
}
try {
Bitmap bitmapA = null;
FileInputStream in = Context.openFileInput("bitmapA");
bitmapA = BitmapFactory.decodeStream(in);
in.close();
/*BufferedInputStream buf = new BufferedInputStream(in);
byte[] bitMapA = new byte[buf.available()];
buf.read(bitMapA);
Bitmap bM = BitmapFactory.decodeByteArray(bitMapA, 0, bitMapA.length);
*/view.setImageBitmap(bitmapA);
if (in != null) {
in.close();
}
/*if (buf != null) {
buf.close();
}*/
} catch (Exception e) {
e.printStackTrace();
}
view.setImageResource(drawables.get(position));
view.setScaleType(ImageView.ScaleType.CENTER_CROP);
view.setLayoutParams(new android.widget.GridView.LayoutParams(70, 70));
view.setTag(String.valueOf(position));
return view;
}
}
FURTHER UPDATED CODING:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Try to reuse the views
ImageView view = (ImageView) convertView;
boolean checked = (mCheckBox==null)?false:(((CheckBox) mCheckBox).isChecked());
// if convert view is null then create a new instance else reuse it
if (view == null) {
view = new ImageView(Context);
Log.d("GridViewAdapter", "new imageView added");
}
if(checked = true){
try {
Bitmap bitmapA = null;
FileInputStream in = Context.openFileInput("bitmapA");
bitmapA = BitmapFactory.decodeStream(in);
in.close();
/*BufferedInputStream buf = new BufferedInputStream(in);
byte[] bitMapA = new byte[buf.available()];
buf.read(bitMapA);
Bitmap bM = BitmapFactory.decodeByteArray(bitMapA, 0, bitMapA.length);
*/view.setImageBitmap(bitmapA);
if (in != null) {
in.close();
}
/*if (buf != null) {
buf.close();
}*/
} catch (Exception e) {
e.printStackTrace();
}}
PLUS I ADDED THIS METHOD:
public void setCheckBox(CheckBox checkbox){
mCheckBox=checkbox;
}
AND THIS VARIABLE:
CheckBox mCheckBox=null;
You dont need to listen to the onClick event in the adapter.
Instead, you can read the checkbox status.
for this, in your adapter, you add a field and a setter:
CheckBox mCheckBox=null;
public void setCheckBox( CheckBox checkbox){
mCheckBox=checkbox;
}
and then, in the getView(), you add thiss line at the begining;
boolean checked = (mCheckBox==null)?false:(((CheckBox) mCheckBox).isChecked());
UPDATE
then in your activity, i suppose you have something like
GridViewAdapter mGridViewAdapter= new GridViewAdapter(this);
so, below you have to add:
CheckBox mCheckBox = findViewById(R,id.YOURCHECKBOXID);
mGridViewAdapter.setCheckBox(mCheckBox);
And that's it!

Categories

Resources