i have a big problem that is driving me crazy. I have a ListView with all apps installed but the scroll is very slow, so i want to improve it. I tried to put a Thread but it doesn't solv the problem. This is the code
ApplicationAdapter
public class ApplicationAdapter extends ArrayAdapter<ApplicationInfo> {
private List<ApplicationInfo> appsList = null;
private Context context;
private PackageManager packageManager;
Holder holder;
public ApplicationAdapter(Context context, int textViewResourceId,
List<ApplicationInfo> appsList) {
super(context, textViewResourceId, appsList);
this.context = context;
this.appsList = appsList;
packageManager = context.getPackageManager();
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
View view = convertView;
final Holder holder;
if (null == view) {
LayoutInflater layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.snippet_list_row, null);
holder = new Holder();
holder.appName = (TextView) view.findViewById(R.id.app_name);
holder.packageName = (TextView) view.findViewById(R.id.app_paackage);
holder.iconview = (ImageView) view.findViewById(R.id.app_icon);
view.setTag(holder);
}
else
{
holder = (Holder)view.getTag();
}
final ApplicationInfo data = appsList.get(position);
if (null != data) {
holder.appName.setText(data.loadLabel(packageManager));
holder.packageName.setText(data.packageName);
holder.iconview.setImageDrawable(data.loadIcon(packageManager));
}
return view;
}
static class Holder
{
TextView appName, packageName;
ImageView iconview;
}
}
Activity
public class Activity_Eclair extends ListActivity {
public PackageManager packageManager = null;
public List<ApplicationInfo> applist = null;
public ApplicationAdapter listadaptor = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_eclair);
ListView lv = getListView();
lv.setFastScrollEnabled(true);
lv.setScrollingCacheEnabled(false);
registerForContextMenu(lv);
packageManager = getPackageManager();
new LoadApplications().execute();
Button bottone1 = (Button)findViewById(R.id.button1);
bottone1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new LoadApplications().execute();
}
});};
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
ApplicationInfo app = applist.get(position);
Uri packageUri = Uri.parse("package:"+app.packageName);
Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageUri);
startActivity(uninstallIntent);
}
public List<ApplicationInfo> checkForLaunchIntent(List<ApplicationInfo> list) {
ArrayList<ApplicationInfo> applist = new ArrayList<ApplicationInfo>();
for (ApplicationInfo info : list) {
try {
if (null != packageManager.getLaunchIntentForPackage(info.packageName)) {
applist.add(info);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return applist;
}
private class LoadApplications extends AsyncTask<Void, Void, Void> {
public ProgressDialog progress = null;
#Override
protected Void doInBackground(Void... params) {
applist = checkForLaunchIntent(packageManager.getInstalledApplications(PackageManager.GET_META_DATA));
listadaptor = new ApplicationAdapter(Activity_Eclair.this,
R.layout.snippet_list_row, applist);
return null;
}
#Override
protected void onCancelled() {
super.onCancelled();
}
protected void onDestroy() {
if(progress!=null)
if(progress.isShowing()){
progress.dismiss();
}
}
#Override
protected void onPostExecute(Void result) {
setListAdapter(listadaptor);
progress.dismiss();
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
progress = ProgressDialog.show(Activity_Eclair.this, null,
"Loading...");
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
private final static int UPDATE_MENU_OPTION = 1;
private final static int DELETE_MENU_OPTION = 2;
private final static int TRUNCATE_MENU_OPTION = 3;
private final static int DELETE = 4;
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
final long examId = info.id;
ApplicationInfo app = applist.get((int) info.id);
switch (item.getItemId()) {
case UPDATE_MENU_OPTION:
try {
Intent intent = packageManager
.getLaunchIntentForPackage(app.packageName);
if (null != intent) {
startActivity(intent);
}
} catch (ActivityNotFoundException e) {
Toast.makeText(Activity_Eclair.this, e.getMessage(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(Activity_Eclair.this, e.getMessage(),
Toast.LENGTH_LONG).show();
}
return true;
case DELETE_MENU_OPTION:
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id="+app.packageName));
startActivity(browserIntent);
return true;
case TRUNCATE_MENU_OPTION:
try {
//Open the specific App Info page:
Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.setData(Uri.parse("package:" + app.packageName));
startActivity(intent);
} catch ( ActivityNotFoundException e ) {
//e.printStackTrace();
//Open the generic Apps page:
Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_APPLICATIONS_SETTINGS);
startActivity(intent);
}
return true;
case DELETE:
{
Uri packageUri = Uri.parse("package:"+app.packageName);
Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageUri);
startActivity(uninstallIntent);
}
return true;
default:
return super.onContextItemSelected(item);
}
}
I state that I have already tried numerous snippets present on StackOverflow and on the Web but do not work.
}
1 - edit Manifest file add to activity
android:hardwareAccelerated="true"
2- Cache and draw icons to ImageView oneByOne we need 4 classes witch is :
Utils.class
public class Utils {
public static void CopyStream(InputStream is, OutputStream os)
{
final int buffer_size=1024;
try
{
byte[] bytes=new byte[buffer_size];
for(;;)
{
int count=is.read(bytes, 0, buffer_size);
if(count==-1)
break;
os.write(bytes, 0, count);
}
}
catch(Exception ex){}
}
}
MemoryCache.class
public class MemoryCache {
private static final String TAG = "MemoryCache";
private Map<String, Bitmap> cache=Collections.synchronizedMap(
new LinkedHashMap<String, Bitmap>(10,1.5f,true));//Last argument true for LRU ordering
private long size=0;//current allocated size
private long limit=1000000;//max memory in bytes
public MemoryCache(){
//use 25% of available heap size
setLimit(Runtime.getRuntime().maxMemory()/4);
}
public void setLimit(long new_limit){
limit=new_limit;
Log.i(TAG, "MemoryCache will use up to "+limit/1024./1024.+"MB");
}
public Bitmap get(String id){
try{
if(!cache.containsKey(id))
return null;
return cache.get(id);
}catch(NullPointerException ex){
ex.printStackTrace();
return null;
}
}
public void put(String id, Bitmap bitmap){
try{
if(cache.containsKey(id))
size-=getSizeInBytes(cache.get(id));
cache.put(id, bitmap);
size+=getSizeInBytes(bitmap);
checkSize();
}catch(Throwable th){
th.printStackTrace();
}
}
private void checkSize() {
Log.i(TAG, "cache size="+size+" length="+cache.size());
if(size>limit){
Iterator<Entry<String, Bitmap>> iter=cache.entrySet().iterator();
while(iter.hasNext()){
Entry<String, Bitmap> entry=iter.next();
size-=getSizeInBytes(entry.getValue());
iter.remove();
if(size<=limit)
break;
}
Log.i(TAG, "Clean cache. New size "+cache.size());
}
}
public void clear() {
try{
cache.clear();
size=0;
}catch(NullPointerException ex){
ex.printStackTrace();
}
}
long getSizeInBytes(Bitmap bitmap) {
if(bitmap==null)
return 0;
return bitmap.getRowBytes() * bitmap.getHeight();
}
}
FileCache.class
public class FileCache {
private File cacheDir;
String cacheFile = "cachefolder";
public FileCache(Context context, String subfolder ){
//Find the dir to save cached images
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),cacheFile+"/"+subfolder);
else
cacheDir=context.getCacheDir();
if(!cacheDir.exists())
cacheDir.mkdirs();
}
public FileCache(Context context){
//Find the dir to save cached images
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),cacheFile);
else
cacheDir=context.getCacheDir();
if(!cacheDir.exists())
cacheDir.mkdirs();
}
public File getFile(String url){
//I identify images by hashcode. Not a perfect solution, good for the demo.
String filename = String.valueOf(url.hashCode());
//Another possible solution (thanks to grantland)
//String filename = URLEncoder.encode(url);
File f = new File(cacheDir, filename);
return f;
}
public void clear(){
File[] files=cacheDir.listFiles();
if(files==null)
return;
for(File f:files)
f.delete();
}
}
ImageLoader.class :
public class ImageLoader {
public static int REQUIRED_SIZE=100;
public MemoryCache memoryCache = new MemoryCache();
FileCache fileCache;
private Map<ImageView, String> imageViews=Collections.synchronizedMap(new WeakHashMap<ImageView, String>());
ExecutorService executorService;
int stub_id = R.drawable.drawing_image;
public ImageLoader(Context context){
fileCache=new FileCache(context);
executorService=Executors.newFixedThreadPool(5);
}
public void DisplayImage(String url, ImageView imageView)
{
imageViews.put( imageView, url );
Bitmap bitmap = memoryCache.get(url);
if( bitmap != null )
{
imageView.setImageBitmap(bitmap);
}
else
{
queuePhoto(url, imageView);
imageView.setImageResource(stub_id);
}
}
/* private Bitmap bitmap_to_circel( Bitmap bitmap)
{
return bitmap;
Bitmap circleBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
BitmapShader shader = new BitmapShader (bitmap, TileMode.CLAMP, TileMode.CLAMP);
Paint paint = new Paint();
paint.setShader(shader);
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setDither(true);
Canvas c = new Canvas(circleBitmap);
c.drawCircle(bitmap.getWidth()/2, bitmap.getHeight()/2, bitmap.getWidth()/2, paint);
return circleBitmap;
}*/
private void queuePhoto(String url, ImageView imageView)
{
PhotoToLoad p = new PhotoToLoad(url, imageView);
executorService.submit(new PhotosLoader(p));
}
private Bitmap getBitmap(String url)
{
File f=fileCache.getFile(url);
//from SD cache
Bitmap b = decodeFile(f);
if(b!=null)
return b;
//from web
try {
Bitmap bitmap=null;
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is=conn.getInputStream();
OutputStream os = new FileOutputStream(f);
Utils.CopyStream(is, os);
os.close();
bitmap = decodeFile(f);
return bitmap;
} catch (Throwable ex){
ex.printStackTrace();
if(ex instanceof OutOfMemoryError)
memoryCache.clear();
return null;
}
}
//decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f){
try {
//decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f),null,o);
//Find the correct scale value. It should be the power of 2.
int width_tmp=o.outWidth, height_tmp=o.outHeight;
int scale=1;
while(true){
if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
break;
width_tmp/=2;
height_tmp/=2;
scale*=2;
}
//decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {}
return null;
}
//Task for the queue
private class PhotoToLoad
{
public String url;
public ImageView imageView;
public PhotoToLoad(String u, ImageView i){
url=u;
imageView=i;
}
}
class PhotosLoader implements Runnable {
PhotoToLoad photoToLoad;
PhotosLoader(PhotoToLoad photoToLoad){
this.photoToLoad=photoToLoad;
}
#Override
public void run() {
if(imageViewReused(photoToLoad))
return;
Bitmap bmp=getBitmap(photoToLoad.url);
memoryCache.put(photoToLoad.url, bmp);
if(imageViewReused(photoToLoad))
return;
BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad);
Activity a=(Activity)photoToLoad.imageView.getContext();
a.runOnUiThread(bd);
}
}
boolean imageViewReused(PhotoToLoad photoToLoad){
String tag=imageViews.get(photoToLoad.imageView);
if(tag==null || !tag.equals(photoToLoad.url))
return true;
return false;
}
//Used to display bitmap in the UI thread
class BitmapDisplayer implements Runnable
{
Bitmap bitmap;
PhotoToLoad photoToLoad;
public BitmapDisplayer(Bitmap b, PhotoToLoad p){bitmap=b;photoToLoad=p;}
public void run()
{
if(imageViewReused(photoToLoad))
return;
if(bitmap!=null)
photoToLoad.imageView.setImageBitmap(bitmap);
else
photoToLoad.imageView.setImageResource(stub_id);
}
}
public void clearCache() {
memoryCache.clear();
fileCache.clear();
}
}
3 - Add ImageLoader to your ApplicationAdapter and Start display images
public class ApplicationAdapter extends ArrayAdapter<ApplicationInfo> {
private List<ApplicationInfo> appsList = null;
private Context context;
private PackageManager packageManager;
Holder holder;
//added imageloader here <<------------------
ImageLoader imgLoader;
public ApplicationAdapter(Context context, int textViewResourceId,
List<ApplicationInfo> appsList) {
super(context, textViewResourceId, appsList);
this.context = context;
this.appsList = appsList;
packageManager = context.getPackageManager();
//Register image loader class <<---------------------
imgLoader = new ImageLoader(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
View view = convertView;
final Holder holder;
if (null == view) {
LayoutInflater layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.snippet_list_row, null);
holder = new Holder();
holder.appName = (TextView) view.findViewById(R.id.app_name);
holder.packageName = (TextView) view.findViewById(R.id.app_paackage);
holder.iconview = (ImageView) view.findViewById(R.id.app_icon);
view.setTag(holder);
}
else
{
holder = (Holder)view.getTag();
}
final ApplicationInfo data = appsList.get(position);
if (null != data) {
holder.appName.setText(data.loadLabel(packageManager));
holder.packageName.setText(data.packageName);
//now load icon provide Url and ImageView only and keep the rest to the class
//provide fill link url to the icon the class will download it , cache it , display it
//next time when scroll again to this position the icon will be displayed from cache file
imgLoader.DisplayImage(data.icon_link_url_with_http, holder.iconview);
}
return view;
}
static class Holder
{
TextView appName, packageName;
ImageView iconview;
}
}
now your list view will scroll quickly even if its has 1k ImageView
holder.iconview.setImageDrawable(data.loadIcon(packageManager));
You do that everytime you set an image, which is very very slow, hitting the disk and loading the image in full scale. Some apps have very big launcher icons, this can kill your ram quickly. Load all images into ram or the cache folder before creating the listview and it will run a lot quicker.
Related
I managed to save the image from imageview to gallery with the onlongclicklistner() with the help of code given below. But the problem is that it always save the last image dosent matters which image i try to save.
public class CapturePhotoUtils {
public final String insertImage(ContentResolver cr,
Bitmap source,
String title,
String description) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, title);
values.put(MediaStore.Images.Media.DISPLAY_NAME, title);
values.put(MediaStore.Images.Media.DESCRIPTION, description);
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
// Add the date meta data to ensure the image is added at the front of the gallery
values.put(MediaStore.Images.Media.DATE_ADDED, System.currentTimeMillis());
values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
Uri url = null;
String stringUrl = null; /* value to be returned */
try {
url = cr.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
if (source != null) {
OutputStream imageOut = cr.openOutputStream(url);
try {
source.compress(Bitmap.CompressFormat.JPEG, 50, imageOut);
} finally {
imageOut.close();
}
long id = ContentUris.parseId(url);
// Wait until MINI_KIND thumbnail is generated.
Bitmap miniThumb = MediaStore.Images.Thumbnails.getThumbnail(cr, id, MediaStore.Images.Thumbnails.MINI_KIND, null);
// This is for backward compatibility.
storeThumbnail(cr, miniThumb, id, 50F, 50F, MediaStore.Images.Thumbnails.MICRO_KIND);
} else {
cr.delete(url, null, null);
url = null;
}
} catch (Exception e) {
if (url != null) {
cr.delete(url, null, null);
url = null;
}
}
if (url != null) {
stringUrl = url.toString();
}
return stringUrl;
}
private final Bitmap storeThumbnail(
ContentResolver cr,
Bitmap source,
long id,
float width,
float height,
int kind) {
// create the matrix to scale it
Matrix matrix = new Matrix();
float scaleX = width / source.getWidth();
float scaleY = height / source.getHeight();
matrix.setScale(scaleX, scaleY);
Bitmap thumb = Bitmap.createBitmap(source, 0, 0,
source.getWidth(),
source.getHeight(), matrix,
true
);
ContentValues values = new ContentValues(4);
values.put(MediaStore.Images.Thumbnails.KIND,kind);
values.put(MediaStore.Images.Thumbnails.IMAGE_ID,(int)id);
values.put(MediaStore.Images.Thumbnails.HEIGHT,thumb.getHeight());
values.put(MediaStore.Images.Thumbnails.WIDTH,thumb.getWidth());
Uri url = cr.insert(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, values);
try {
OutputStream thumbOut = cr.openOutputStream(url);
thumb.compress(Bitmap.CompressFormat.JPEG, 100, thumbOut);
thumbOut.close();
return thumb;
} catch (FileNotFoundException ex) {
return null;
} catch (IOException ex) {
return null;
}
}
}
I am putting images from the viewpager getting images from array of drawables
class CustomPagerAdapter extends PagerAdapter {
Context mContext;
LayoutInflater mLayoutInflater;
public CustomPagerAdapter(Context context) {
mContext = context;
mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return mResources.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((LinearLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
View itemView = mLayoutInflater.inflate(R.layout.image_slider_item, container, false);
imageView = (TouchImageView) itemView.findViewById(R.id.imageView);
imageView.setImageResource(mResources[position]);
imageView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
CapturePhotoUtils photoUtils = new CapturePhotoUtils();
imageView.setDrawingCacheEnabled(true);
Bitmap b = imageView.getDrawingCache();
photoUtils.insertImage(Full_Screen_Slider.this.getContentResolver(),
b, "1image", "this is downloaded image sample");
Toast.makeText(mContext, "longpress ", Toast.LENGTH_SHORT).show();
return true;
}
});
container.addView(itemView);
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((LinearLayout) object);
}
}
Replace this
#Override
public Object instantiateItem(ViewGroup container,final int position) {
final View itemView = mLayoutInflater.inflate(R.layout.image_slider_item, container, false);
final TouchImageView imageView = (TouchImageView) itemView.findViewById(R.id.imageView);
imageView.setImageResource(mResources[position]);
imageView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
CapturePhotoUtils photoUtils = new CapturePhotoUtils();
imageView.setDrawingCacheEnabled(true);
Bitmap b = imageView.getDrawingCache();
photoUtils.insertImage(Full_Screen_Slider.this.getContentResolver(),
b, "1image", "this is downloaded image sample");
Toast.makeText(mContext, "longpress ", Toast.LENGTH_SHORT).show();
return true;
}
});
container.addView(itemView);
return itemView;
}
it is replacing your view each time it calls instantiateItem so make it final which will help.
I m getting this error in my code.
Please help me.
My code is as follows. I don't know how to solve this. When I click on the add button I want to add all data to the model class and that class should be filled with the list array in main activity.
public class MainActivity extends Activity implements DataTransferInterfase{
private Button btnSelect,btnShow;
public int REQUEST_CAMERA=1;
public int SELECT_IMAGE=0;
private GridView gridview;
private CustomAdapter gridAdaptor;
public TextView tvcounter;
public ImageItemBin imageItemBin;
private Uri mCapturedImageUri;
public static ArrayList<ImageItemBin> publicSelectedImage=new ArrayList<ImageItemBin>();
public ArrayList<ImageItemBin> showImagelist=new ArrayList<ImageItemBin>();
public Uri ImageUri;
private int count=publicSelectedImage.size();
private int coloumn=3;
private int row=count/coloumn;
public String imgPath="";
private Uri fileUri; // file url to store image
private static final String IMAGE_DIRECTORY_NAME = "Hello Camera";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSelect=(Button)findViewById(R.id.btnselect);
btnShow=(Button)findViewById(R.id.btnShow);
tvcounter=(TextView)findViewById(R.id.tvcounter);
publicSelectedImage=new ArrayList<ImageItemBin>();
//showImagelist=new ArrayList<ImageItemBin>();
showImagelist=new ArrayList<ImageItemBin>();
gridview=(GridView) findViewById(R.id.gridLayout_main);
// gridAdaptor=new CustomAdapter(MainActivity.this,publicSelectedImage);
// gridview.setAdapter(gridAdaptor);
//gridAdaptor(R.layout.custom_grid_item_layout,getView());
//gridLayout.addView(gridAdaptor.getView());
//gridLayout.addView(inflater.inflate(R.layout.custom_grid_item_layout,null));
//gridLayout.addView(img);
//tvcounter.setText(CountRecord(imageItemBin));
//tvcounter.setText(CustomAdapter.result+"");
showImagelist.add(CustomAdapter.showBin);
tvcounter.setText(showImagelist.size());
//showImagelist.add(CustomAdapter.result);
//tvcounter.setText(counter);
btnSelect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//custom dialogBox
final Dialog dialog=new Dialog(MainActivity.this);
dialog.setContentView(R.layout.custom_dialog_layout);
dialog.setTitle("Select from..");
//set the custom dialog components
TextView txtmsg=(TextView)dialog.findViewById(R.id.txtmsg);
Button btnGallaery=(Button)dialog.findViewById(R.id.btngallery);
Button btnCamara=(Button)dialog.findViewById(R.id.btncamara);
btnGallaery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent image=new Intent();
image.setType("image/*");
image.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(image,"select file"),SELECT_IMAGE);
dialog.dismiss();
}
});
btnCamara.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cam=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
/*if(cam.resolveActivity(getPackageManager())!=null){
String filename="temp.jpg";
ContentValues values=new ContentValues();
values.put(MediaStore.Images.Media.TITLE,filename);
mCapturedImageUri=getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,values);*/
//cam.putExtra(MediaStore.EXTRA_OUTPUT,setImageUri());
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
cam.putExtra("Image", fileUri);
startActivityForResult(cam,REQUEST_CAMERA);
dialog.dismiss();
// }
}
});
dialog.show();
}
});
btnShow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==SELECT_IMAGE){
if(resultCode==RESULT_OK && null!=data){
for (int i=0,c=0,r=0;i<count;i++,c++){
if(c==coloumn){
c=0;
r++;
}
}
ImageUri=data.getData();
imageItemBin=new ImageItemBin();
imageItemBin.setImage(ImageUri.toString());
publicSelectedImage.add(imageItemBin);
gridAdaptor=new CustomAdapter(MainActivity.this,publicSelectedImage,this);
gridview.setAdapter(gridAdaptor);
}
}
if(requestCode==REQUEST_CAMERA)
{
if(resultCode==RESULT_OK && data!=null){
/*String[] projection={MediaStore.Images.Media.DATA};
Cursor cursor=managedQuery(mCapturedImageUri,projection,null,null,null);
int coloumn_index_data=cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String picturePath=cursor.getString(coloumn_index_data);
Uri selectedImage=data.getData();
imageItemBin=new ImageItemBin();
imageItemBin.setImage(selectedImage.toString());
publicSelectedImage.add(imageItemBin);*/
// gridAdaptor=new CustomAdapter(MainActivity.this,publicSelectedImage);
// gridview.setAdapter(gridAdaptor);
Bitmap mphoto = (Bitmap) data.getExtras().get("data");
String stringImage=BitMapToString(mphoto);
// String getimage=getImagePath();
imageItemBin=new ImageItemBin();
imageItemBin.setImage(stringImage);
//imageItemBin.setImage(picturePth.toString());
publicSelectedImage.add(imageItemBin);
gridAdaptor=new CustomAdapter(MainActivity.this,publicSelectedImage,this);
gridview.setAdapter(gridAdaptor);
//gridAdaptor.notifyDataSetChanged();
// tvcounter.setText(counter);
//publicSelectedImage=selectedImage;
}
}
}
public Uri setImageUri() {
// Store image in dcim
File file = new File(Environment.getExternalStorageDirectory() + "/DCIM/", "image" + new Date().getTime() + ".png");
Uri imgUri = Uri.fromFile(file);
this.imgPath = file.getAbsolutePath();
return imgUri;
}
public String getImagePath() {
return imgPath;
}
/*private List<ImageItemBin> DisplayImage(){
ImageItemBin itembin=new ImageItemBin();
itembin.getImage();
}*/
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/*
* returning image / video
*/
private static File getOutputMediaFile(int type) {
// External sdcard location
/*File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
IMAGE_DIRECTORY_NAME);
*/
//File file = new File(Environment.getExternalStorageDirectory() + "/DCIM/", "image" + new Date().getTime() + ".jpg");
// Create the storage directory if it does not exist
/*if (!file.exists()) {
if (!file.mkdirs()) {
Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
+ IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}*/
// Create a media file name
//String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
// Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(Environment.getExternalStorageDirectory() + "/DCIM/", "image" + new Date().getTime() + ".jpg");
} /*else if (type == MEDIA_TYPE_VIDEO) {
//mediaFile = new File(file.getPath() + File.separator
// + "VID_" + timeStamp + ".mp4");
}*/ else {
return null;
}
return mediaFile;
//return file;
}
private Bitmap previewCapturedImage(Uri file)
{
Bitmap bitmap=null;
try {
// hide video preview
//videoPreview.setVisibility(View.GONE);
//imgPreview.setVisibility(View.VISIBLE);
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();
// downsizing image as it throws OutOfMemory Exception for larger
// images
options.inSampleSize = 8;
bitmap = BitmapFactory.decodeFile(file.getPath(),
options);
return bitmap;
//imgPreview.setImageBitmap(bitmap);
} catch (NullPointerException e) {
e.printStackTrace();
}
return bitmap;
}
public String BitMapToString(Bitmap bitmap){
ByteArrayOutputStream baos=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG,100, baos);
byte [] b=baos.toByteArray();
String temp= Base64.encodeToString(b, Base64.DEFAULT);
return temp;
}
public Bitmap StringToBitMap(String encodedString){
try{
byte [] encodeByte=Base64.decode(encodedString,Base64.DEFAULT);
Bitmap bitmap=BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
return bitmap;
}catch(Exception e){
e.getMessage();
return null;
}
}
public static int totalAmt=0;
#Override
public int CountRecord(ImageItemBin bin) {
//for (int i=0;i<count;i++){
totalAmt=totalAmt+1;
// }
return totalAmt;
}
}
I just got it.
here is the way for getting the perfect result.in adapter just add the data.get(position)to countRecord method.
public int CountRecord(ImageItemBin bin)
{
showImagelist.add(showBin);
int size=showImagelist.size();
tvcounter.setText(Integer.toString(size));
btnShow.setText(Integer.toString(size));
return 0;
}
CustomAdaptor.java
public class CustomAdapter extends BaseAdapter {
public static String counter="";
public static int result=0;
Context context;
private int layoutResourceId;
private ArrayList<ImageItemBin> data=new ArrayList<ImageItemBin>();
public static ImageItemBin showBin=new ImageItemBin();
DataTransferInterfase dataTransferInterfase;
String qty,title;
public MainActivity mainActivity;
ImageLoader imageLoader;
DisplayImageOptions options;
private static LayoutInflater inflater=null;
public CustomAdapter(MainActivity mainActivity,ArrayList<ImageItemBin> data,DataTransferInterfase dataTransferInterfase){
this.data=data;
this.context=mainActivity;
this.dataTransferInterfase=dataTransferInterfase;
this.mainActivity=mainActivity;
inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, final View convertView, ViewGroup parent) {
Holder holder=null;
View rootview=convertView;
if(rootview==null) {
rootview = inflater.inflate(R.layout.custom_grid_item_layout, null);
holder = new Holder();
holder.edttitle = (EditText) rootview.findViewById(R.id.edtTitle);
holder.edtqty = (EditText) rootview.findViewById(R.id.edtQty);
holder.image = (ImageView) rootview.findViewById(R.id.MyimageView);
holder.tvcounter=(TextView)rootview.findViewById(R.id.tvcounter);
imageLoader = ImageLoader.getInstance();
imageLoader.init(ImageLoaderConfiguration.createDefault(context));
rootview.setTag(holder);
qty=holder.edtqty.getText().toString();
title=holder.edttitle.getText().toString();
data.get(position).setTitle(title);
data.get(position).setQty(qty);
}
else
{
holder=(Holder)convertView.getTag();
holder.image.setTag(position);
holder.edttitle.setTag(position);
holder.edtqty.setTag(position);
qty=holder.edtqty.getText().toString();
title=holder.edttitle.getText().toString();
data.get(position).setTitle(title);
data.get(position).setQty(qty);
}
String img=data.get(position).getImage();
final String title=data.get(position).getTitle();
final String qty=data.get(position).getQty();
options = getDisplayImageOptions(context, R.mipmap.ic_launcher);
imageLoader.displayImage(img, holder.image, options);
holder.btnadd=(Button)rootview.findViewById(R.id.btnAdd);
final Holder finalHolder = holder;
//public static final ImageItemBin showBin=new ImageItemBin();
holder.btnadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
data.get(position).setQty(qty);
data.get(position).setTitle(title);
showBin.setImage(data.get(position).getImage());
showBin.setTitle(title);
showBin.setQty(qty);
mainActivity.CountRecord(data.get(position));
}
});
return rootview;
}
static class Holder{
ImageView image;
EditText edtqty;
EditText edttitle;
Button btnadd;
TextView tvcounter;
}
public static DisplayImageOptions getDisplayImageOptions(Context context, int defaultImg) {
DisplayImageOptions options = new DisplayImageOptions.Builder().showImageOnLoading(defaultImg)
.resetViewBeforeLoading(true).showImageForEmptyUri(defaultImg).showImageOnFail(defaultImg)
.cacheInMemory(true).cacheOnDisk(true).considerExifParams(true).bitmapConfig(Bitmap.Config.RGB_565)
.considerExifParams(true).build();
return options;
}
}
I do apologize for the noobish question, but I am building a music player in android studio and I am having problems with the songs playing one after the other like a playlist. The songs can only be picked by hand and after the song finishes it just stops until the user clicks another song. I've written two pieces of code that I suspect will solve this issue but I'm not really sure how to implement them or if they eventually will be of any use at all. I would really appreciate some help with this, could really really use it. Any advice or constructive criticism is always welcome, thanks in advance. here are the snippets:
//------------> to get the next song <---------------
int itemsInList=list.getAdapter().getCount();
for(int i=1;i<itemsInList;i++){
list.setSelection(i);
}
//--------------> to play the song on list item click <-------------------
#Override
protected void onListItemClick(ListView list, View view, int position,
long id) {
super.onListItemClick(list, view, position, id);
currentFile = (String) view.getTag();
startPlay(currentFile);
}
And just for reference here is my main java file:
public class MainActivity extends ListActivity {
private static final int UPDATE_FREQUENCY = 500;
private static final int STEP_VALUE = 4000;
private MediaCursorAdapter mediaAdapter = null;
private TextView selectedFile = null;
private SeekBar seekbar = null;
private MediaPlayer player = null;
private ListView list = null;
private ImageButton playButton = null;
private ImageButton prevButton = null;
private ImageButton nextButton = null;
private ImageButton btNext = null;
private ImageButton btPrev = null;
private boolean isStarted = true;
private String currentFile = "";
private boolean isMovingSeekBar = false;
private final Handler handler = new Handler();
private final Runnable updatePositionRunnable = new Runnable() {
public void run() {
updatePosition();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
selectedFile = (TextView) findViewById(R.id.selectedfile);
seekbar = (SeekBar) findViewById(R.id.seekbar);
playButton = (ImageButton) findViewById(R.id.play);
prevButton = (ImageButton) findViewById(R.id.prev);
nextButton = (ImageButton) findViewById(R.id.next);
btNext = (ImageButton) findViewById(R.id.btNxt);
btPrev = (ImageButton) findViewById(R.id.btPrev);
player = new MediaPlayer();
player.setOnCompletionListener(onCompletion);
player.setOnErrorListener(onError);
seekbar.setOnSeekBarChangeListener(seekBarChanged);
Cursor cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
if (null != cursor) {
cursor.moveToFirst();
mediaAdapter = new MediaCursorAdapter(this, R.layout.list_item, cursor);
setListAdapter(mediaAdapter);
playButton.setOnClickListener(onButtonClick);
nextButton.setOnClickListener(onButtonClick);
prevButton.setOnClickListener(onButtonClick);
btNext.setOnClickListener(onButtonClick);
btPrev.setOnClickListener(onButtonClick);
}
}
//----------- ??? ----------------------------------------------------------------
int itemsInList=list.getAdapter().getCount();
for(int i=1;i<itemsInList;i++){
list.setSelection(i);
}
#Override
protected void onListItemClick(ListView list, View view, int position, long id) {
super.onListItemClick(list, view, position, id);
currentFile = (String) view.getTag();
startPlay(currentFile);
}
// --------------------------------------------------------------------------------
#Override
protected void onDestroy() {
super.onDestroy();
handler.removeCallbacks(updatePositionRunnable);
player.stop();
player.reset();
player.release();
player = null;
}
private void startPlay(String file) {
Log.i("Selected: ", file);
selectedFile.setText(file);
seekbar.setProgress(0);
player.stop();
player.reset();
try {
player.setDataSource(file);
player.prepare();
player.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
seekbar.setMax(player.getDuration());
playButton.setImageResource(android.R.drawable.ic_media_pause);
updatePosition();
isStarted = true;
}
private void stopPlay() {
player.stop();
player.reset();
playButton.setImageResource(android.R.drawable.ic_media_play);
handler.removeCallbacks(updatePositionRunnable);
seekbar.setProgress(0);
isStarted = false;
}
private void updatePosition() {
handler.removeCallbacks(updatePositionRunnable);
seekbar.setProgress(player.getCurrentPosition());
handler.postDelayed(updatePositionRunnable, UPDATE_FREQUENCY);
}
private class MediaCursorAdapter extends SimpleCursorAdapter {
public MediaCursorAdapter(Context context, int layout, Cursor c) {
super(context, layout, c,
new String[]{MediaStore.MediaColumns.DISPLAY_NAME, MediaStore.MediaColumns.TITLE, MediaStore.Audio.AudioColumns.DURATION},
new int[]{R.id.displayname, R.id.title, R.id.duration});
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView title = (TextView) view.findViewById(R.id.title);
TextView name = (TextView) view.findViewById(R.id.displayname);
TextView duration = (TextView) view.findViewById(R.id.duration);
name.setText(cursor.getString(
cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME)));
title.setText(cursor.getString(
cursor.getColumnIndex(MediaStore.MediaColumns.TITLE)));
long durationInMs = Long.parseLong(cursor.getString(
cursor.getColumnIndex(MediaStore.Audio.AudioColumns.DURATION)));
double durationInMin = ((double) durationInMs / 1000.0) / 60.0;
durationInMin = new BigDecimal(Double.toString(durationInMin)).setScale(2, BigDecimal.ROUND_UP).doubleValue();
duration.setText("" + durationInMin);
view.setTag(cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.DATA)));
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(R.layout.list_item, parent, false);
bindView(v, context, cursor);
return v;
}
}
private View.OnClickListener onButtonClick = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.play: {
if (player.isPlaying()) {
handler.removeCallbacks(updatePositionRunnable);
player.pause();
playButton.setImageResource(android.R.drawable.ic_media_play);
} else {
if (isStarted) {
player.start();
playButton.setImageResource(android.R.drawable.ic_media_pause);
updatePosition();
} else {
startPlay(currentFile);
}
}
break;
}
case R.id.next: {
int seekto = player.getCurrentPosition() + STEP_VALUE;
if (seekto > player.getDuration())
seekto = player.getDuration();
player.pause();
player.seekTo(seekto);
player.start();
break;
}
case R.id.prev: {
int seekto = player.getCurrentPosition() - STEP_VALUE;
if (seekto < 0)
seekto = 0;
player.pause();
player.seekTo(seekto);
player.start();
break;
}
case R.id.btNxt: {
//TO DO
}
case R.id.btPrev: {
//TO DO
}
}
}
};
private MediaPlayer.OnCompletionListener onCompletion = new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
stopPlay();
}
};
private MediaPlayer.OnErrorListener onError = new MediaPlayer.OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
return false;
}
};
private SeekBar.OnSeekBarChangeListener seekBarChanged = new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
isMovingSeekBar = false;
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
isMovingSeekBar = true;
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (isMovingSeekBar) {
player.seekTo(progress);
Log.i("OnSeekBarChangeListener", "onProgressChanged");
}
}
};
}
You can look at my methods below to play the next song. Hope it helps.
public static void nextSong() {
int numOfSong = songList.size();
if (!isShuffle) { // Shuffle mode is off
if (currentPosition < numOfSong - 1) {
currentPosition++;
currentSong = songList.get(currentPosition);
Log.d("my_log", "position = "+currentPosition);
playBackMusic();
} else {
currentPosition = 0;
currentSong = songList.get(currentPosition);
Log.d("my_log", "position = "+currentPosition);
playBackMusic();
}
} else { // Shuffle mode is on
Random rand = new Random();
currentPosition = rand.nextInt(numOfSong);
currentSong = songList.get(currentPosition);
Log.d("my_log", "position = "+currentPosition);
playBackMusic();
}
}
And this is playBackMusic() method to play the song:
public static void playBackMusic() {
try {
mediaPlayer.release();
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(currentSong.getPath());
mediaPlayer.prepare();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
endOfTheSong();
}
});
isPlaying = true;
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
}
Method endOfTheSong() to handle what to do after playing current song.
public static void endOfTheSong() {
if (isRepeat == 1) { // currently repeat one song
mediaPlayer.seekTo(0);
mediaPlayer.start();
} else if (isRepeat == 2) { // currently repeat all songs
nextSong();
} else { // currently no repeat
if (currentPosition != songList.size() - 1) nextSong();
}
}
Hi in the below code I am getting array index out of bounds exception.Here friend array it's giving two values.
For ex:
friendinfo[0]=user1,friendinfo1=user2 and with checkbox when i am selecting user1 I want to show friend.length to 2 and checked value should be 1.
this is sample screen how to add the use3 and user1 when i am clicking the create button.
GroupList.java
public class GroupList extends ListActivity
{
boolean[] checkBoxState;
private IAppManager imService = null;
private FriendListAdapter friendAdapter;
public String ownusername = new String();
private class FriendListAdapter extends BaseAdapter
{
#SuppressWarnings("unused")
class ViewHolder {
TextView text;
ImageView icon;
CheckBox check1;
}
private LayoutInflater mInflater;
private Bitmap mOnlineIcon;
private Bitmap mOfflineIcon;
private FriendInfo[] friends = null;
public FriendListAdapter(Context context) {
super();
mInflater = LayoutInflater.from(context);
mOnlineIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.greenstar);
mOfflineIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.redstar);
}
public void setFriendList(FriendInfo[] friends)
{
this.friends = friends;
}
public int getCount() {
return friends.length;
}
public FriendInfo getItem(int position) {
return friends[position];
}
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null)
{
convertView = mInflater.inflate(R.layout.grouplist, null);
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.text);
holder.icon = (ImageView) convertView.findViewById(R.id.icon);
holder.check1 = (CheckBox) convertView.findViewById(R.id.checkBox1);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
holder.text.setText(friends[position].userName);
holder.icon.setImageBitmap(friends[position].status == STATUS.ONLINE ? mOnlineIcon : mOfflineIcon);
checkBoxState = new boolean[friends.length];
holder.check1.setChecked(checkBoxState[position]);
holder.check1.setOnCheckedChangeListener(new OnCheckedChangeListener(){
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
checkBoxState[position]=isChecked;
String check=friends[position].userName;
Toast.makeText(getApplicationContext(),friends[position].userName+"checked", Toast.LENGTH_LONG).show();
}
});
return convertView;
}
}
public class MessageReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.i("Broadcast receiver ", "received a message");
Bundle extra = intent.getExtras();
if (extra != null)
{
String action = intent.getAction();
if (action.equals(IMService.FRIEND_LIST_UPDATED))
{
GroupList.this.updateData(FriendController.getFriendsInfo(),
FriendController.getUnapprovedFriendsInfo());
}
}
}
};
public MessageReceiver messageReceiver = new MessageReceiver();
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
imService = ((IMService.IMBinder)service).getService();
FriendInfo[] friends = FriendController.getFriendsInfo();
if (friends != null) {
GroupList.this.updateData(friends, null);
}
String groupname = getIntent().getStringExtra("nick");
setTitle(groupname);
ownusername = imService.getUsername();
}
public void onServiceDisconnected(ComponentName className) {
imService = null;
Toast.makeText(GroupList.this, R.string.local_service_stopped,
Toast.LENGTH_SHORT).show();
}
};
#SuppressLint("NewApi")
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
setContentView(R.layout.group_list_screen);
friendAdapter = new FriendListAdapter(this);
Button create=(Button)findViewById(R.id.create);
create.setOnClickListener(new OnClickListener() {
#SuppressWarnings("unused")
#Override
public void onClick(View v) {
String groupname = getIntent().getStringExtra("nick");
try {
FriendInfo[] friend=FriendController.getFriendsInfo();
//checkBoxState = new CheckBox[friend.length];
/*try {
for(int i=0;i <=friend.length ;i++){
if(checkBoxState[i].isChecked()){
check[i]="1";
}
}
}catch (Exception e) {
e.printStackTrace();
}*/
String result1 = imService.CreateGroup(groupname,imService.getUsername(),friend);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Group Created Sucessfully",Toast.LENGTH_LONG).show();
}
});
}
public void updateData(FriendInfo[] friends, FriendInfo[] unApprovedFriends)
{
if (friends != null) {
friendAdapter.setFriendList(friends);
setListAdapter(friendAdapter);
}
if (unApprovedFriends != null)
{
NotificationManager NM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (unApprovedFriends.length > 0)
{
String tmp = new String();
for (int j = 0; j < unApprovedFriends.length; j++) {
tmp = tmp.concat(unApprovedFriends[j].userName).concat(",");
}
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.stat_sample)
.setContentTitle(getText(R.string.new_friend_request_exist));
/*Notification notification = new Notification(R.drawable.stat_sample,
getText(R.string.new_friend_request_exist),
System.currentTimeMillis());*/
Intent i = new Intent(this, UnApprovedFriendList.class);
i.putExtra(FriendInfo.FRIEND_LIST, tmp);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
i, 0);
mBuilder.setContentText("You have new friend request(s)");
mBuilder.setContentIntent(contentIntent);
NM.notify(R.string.new_friend_request_exist, mBuilder.build());
}
else
{
NM.cancel(R.string.new_friend_request_exist);
}
}
}
#Override
protected void onPause()
{
unregisterReceiver(messageReceiver);
unbindService(mConnection);
super.onPause();
}
#Override
protected void onResume()
{
super.onResume();
bindService(new Intent(GroupList.this, IMService.class), mConnection , Context.BIND_AUTO_CREATE);
IntentFilter i = new IntentFilter();
i.addAction(IMService.FRIEND_LIST_UPDATED);
registerReceiver(messageReceiver, i);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
You probably wanted to write :
if(checkBoxState[i]==isChecked)
if checkBoxState and friend arrays have the same length, checkBoxState[friend.length] is out of bounds, since the indices of an array are from 0 to length - 1.
Also note that your if condition contained an assignment operator = instead of a comparison operator ==.
Just use the index inside the for loop. Also since isChecked is already a boolean you can just assign it directly to checkBoxState
for (int i = 0; i < friend.length; i++) {
checkBoxState[i] = isChecked;
}
You are trying to access the index 2nd position in an array that has only a length of 2 (positions 0 and 1).
So please change the code as below,
if(checkBoxState[i]==isChecked)
Hello So I Was Having Problems With My List View That Contains Songs And There AlbumArt and I Want To make an AsyncTask To Get The Album Art In background.
Put Its either giving Me A NullPointer Or The Album Art is Blank Please Help
ImageLoader.java
public class ImageLoader extends AsyncTask<Object, String, Bitmap> {
private View view;
private Bitmap bitmap = null;
public static BitmapDrawable drawable = null;
Context context;
Cursor cursor;
long albumId = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID));
#Override
protected Bitmap doInBackground(Object... parameters) {
// Get the passed arguments here
final Uri ART_CONTENT_URI = Uri.parse("content://media/external/audio/albumart");
Uri albumArtUri = ContentUris.withAppendedId(ART_CONTENT_URI, albumId);
ContentResolver res = context.getContentResolver();
InputStream in;
try {
if(bitmap != null)
{
bitmap = null;
if(drawable != null)
{
drawable = null;
}
}
in = res.openInputStream(albumArtUri);
bitmap = BitmapFactory.decodeStream(in);
Bitmap resizedBitmap = Bitmap.createScaledBitmap(bitmap, 1280, 720, false);
// bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), albumArtUri);
drawable = new BitmapDrawable(context.getResources(), resizedBitmap);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
drawable = (BitmapDrawable) context.getResources().getDrawable(R.drawable.default_artwork);
};
return bitmap;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
if (bitmap != null && view != null) {
ImageView albumArt = (ImageView) view.getTag(R.id.iconlist);
albumArt.setImageBitmap(bitmap);
}
}
}
SongAdapter.java
public class SongAdapter extends CursorAdapter implements SectionIndexer{
private String mSections = "#ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private final LayoutInflater mInflater;
public SongAdapter(Context context, Cursor c, int textViewResourceId,
List<String> objects) {
super(context, c,textViewResourceId);
new ImageLoader().execute();
mInflater=LayoutInflater.from(context);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView title1 = (TextView) view.findViewById(R.id.titlelist);
TextView artist1 = (TextView) view.findViewById(R.id.artistlist);
ImageView album1 = (ImageView) view.findViewById(R.id.iconlist);
String title = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
String artist = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
String album = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM));
long albumId = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID));
StringBuilder titleBuild = new StringBuilder();
titleBuild.append(title);
if(titleBuild.length() > 35)
{
titleBuild.setLength(32);
title = titleBuild.toString()+"...";
}
else
{
title = titleBuild.toString();
}
StringBuilder artistBuild = new StringBuilder();
artistBuild.append(artist);
if(artistBuild.length() > 35)
{
artistBuild.setLength(32);
artist = artistBuild.toString()+"...";
}
else
{
artist = artistBuild.toString();
}
album1.setImageDrawable(ImageLoader.drawable);
title1.setText(title);
artist1.setText(artist);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater)context.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
return inflater.inflate(R.layout.rowlayout, parent, false);
}#Override
public int getPositionForSection(int section) {
// If there is no item for current section, previous section will be selected
for (int i = section; i >= 0; i--) {
for (int j = 0; j < getCount(); j++) {
if (i == 0) {
// For numeric section
for (int k = 0; k <= 9; k++) {
if (StringMatcher.match(String.valueOf(( getItem(j))), String.valueOf(k)))
return j;
}
} else {
if (StringMatcher.match(String.valueOf(getItem(j)), String.valueOf(mSections.charAt(i))))
return j;
}
}
}
return 0;
}
#Override
public int getSectionForPosition(int position) {
return 0;
}
#Override
public Object[] getSections() {
String[] sections = new String[mSections.length()];
for (int i = 0; i < mSections.length(); i++)
sections[i] = String.valueOf(mSections.charAt(i));
return sections;
}
}
Now This Code Gives Me A Null Pointer So Any Help Would Be Great
Your view object in the Async task is never initialized, atleast I don't see that code. What I think you could do is launch a new AsyncTask for every "new" view you're creating in your adapter. You would need to make the async task have a reference to the imageview you want to populate though. One way to do this is like this.
public class ImageLoader extends AsyncTask<Object, String, Bitmap> {
private WeakReference<ImageView> mReference;
private View view;
private Bitmap bitmap = null;
public static BitmapDrawable drawable = null;
Context context;
Cursor cursor;
long albumId = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID));
public ImageLoader(ImageView imageView) {
mReference = new WeakReference<ImageView>(imageView);
}
#Override
protected Bitmap doInBackground(Object... parameters) { ... your code }
#Override
protected Void onPostExecute(Bitmap bitmap) {
if(mReference != null) {
if(bitmap != null) {
ImageView view = mReference.get();
// note that this could still return null if the view or the reference has been
// garbage collected which it could be since it is a weak reference, so you should
// always check the status in this case.
//do what you want with the image view.
}
}
}
then in your adapter do something like this.
public class SongAdapter extends CursorAdapter implements SectionIndexer{
...other code...
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView title1 = (TextView) view.findViewById(R.id.titlelist);
TextView artist1 = (TextView) view.findViewById(R.id.artistlist);
ImageView album1 = (ImageView) view.findViewById(R.id.iconlist);
String title = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
String artist = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
String album = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM));
long albumId = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID));
StringBuilder titleBuild = new StringBuilder();
titleBuild.append(title);
if(titleBuild.length() > 35)
{
titleBuild.setLength(32);
title = titleBuild.toString()+"...";
}
else
{
title = titleBuild.toString();
}
StringBuilder artistBuild = new StringBuilder();
artistBuild.append(artist);
if(artistBuild.length() > 35)
{
artistBuild.setLength(32);
artist = artistBuild.toString()+"...";
}
else
{
artist = artistBuild.toString();
}
<---->
// new code
new ImageLoader(album1).execute();
// old code album1.setImageDrawable(ImageLoader.drawable);
title1.setText(title);
artist1.setText(artist);
}
}
I've used a similar technique in a grid view and it's cool because you can actually see each image view being populated.
Hope that helps!