Optimization of code for more speed [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
i have this code and the scroll is slow
ApplicationAdapter
import java.util.List;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class ApplicationAdapter extends ArrayAdapter<ApplicationInfo> {
private List<ApplicationInfo> appsList = null;
private Context context;
private PackageManager packageManager;
public ApplicationAdapter(Context context, int textViewResourceId,
List<ApplicationInfo> appsList) {
super(context, textViewResourceId, appsList);
this.context = context;
this.appsList = appsList;
packageManager = context.getPackageManager();
}
#Override
public int getCount() {
return ((null != appsList) ? appsList.size() : 0);
}
#Override
public ApplicationInfo getItem(int position) {
return ((null != appsList) ? appsList.get(position) : null);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (null == view) {
LayoutInflater layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.snippet_list_row, null);
}
ApplicationInfo data = appsList.get(position);
if (null != data) {
TextView appName = (TextView) view.findViewById(R.id.app_name);
TextView packageName = (TextView) view.findViewById(R.id.app_paackage);
ImageView iconview = (ImageView) view.findViewById(R.id.app_icon);
appName.setText(data.loadLabel(packageManager));
packageName.setText(data.packageName);
iconview.setImageDrawable(data.loadIcon(packageManager));
}
return view;
}
};
MainActivity
import java.util.ArrayList;
import java.util.List;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.Button;
import android.widget.ListView;
public class MainActivity extends ListActivity {
private PackageManager packageManager = null;
private List<ApplicationInfo> applist = null;
private ApplicationAdapter listadaptor = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_eclair);
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);
/*
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();
}
*/
Uri packageUri = Uri.parse("package:"+app.packageName);
Intent uninstallIntent =
new Intent(Intent.ACTION_DELETE, packageUri);
startActivity(uninstallIntent);
}
private 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,
"Caricamento applicazioni in corso...");
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
}
When I run my application the scroll is very slow, how can I do to make it go smoother without jamming? Any kind of help is welcome. Thanks in advance.

Well, one quick fix I can help you with right now is using a static holder in your getView() method in your adapter. Do the following so that it recycles more efficiently instead of creating new views every time.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
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();
}
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;
}
I don't know exactly how much faster this will make your app, but it could help and this is also a common practice way to implement Adapters, so it'd be a good habit to start doing.
Hope this helps. Good luck!

the sloweness you are seeing is probably due to the application image fetch.
you should look at this Lazy load of images in ListView
using a ViewHolder could also help too
http://www.itworld.com/development/380008/how-make-smooth-scrolling-listviews-android

Related

caching images from json in listview?

I followed this lesson here which talk about json parsing and image loading in list view the example works good but it has a problem in imageview when scrolling up & down all images reloading so can anyone solve this problem?
this the adapter of listview
package com.wingnity.jsonparsingtutorial;
import java.io.InputStream;
import java.util.ArrayList;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class ActorAdapter extends ArrayAdapter<Actors> {
ArrayList<Actors> actorList;
LayoutInflater vi;
int Resource;
ViewHolder holder;
public ActorAdapter(Context context, int resource, ArrayList<Actors> objects) {
super(context, resource, objects);
vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = resource;
actorList = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// convert view = design
View v = convertView;
if (v == null) {
holder = new ViewHolder();
v = vi.inflate(Resource, null);
holder.imageview = (ImageView) v.findViewById(R.id.ivImage);
holder.tvName = (TextView) v.findViewById(R.id.tvName);
holder.tvDescription = (TextView) v.findViewById(R.id.tvDescriptionn);
holder.tvDOB = (TextView) v.findViewById(R.id.tvDateOfBirth);
holder.tvCountry = (TextView) v.findViewById(R.id.tvCountry);
holder.tvHeight = (TextView) v.findViewById(R.id.tvHeight);
holder.tvSpouse = (TextView) v.findViewById(R.id.tvSpouse);
holder.tvChildren = (TextView) v.findViewById(R.id.tvChildren);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.imageview.setImageResource(R.drawable.ic_launcher);
new DownloadImageTask(holder.imageview).execute(actorList.get(position).getImage());
holder.tvName.setText(actorList.get(position).getName());
holder.tvDescription.setText(actorList.get(position).getDescription());
holder.tvDOB.setText("B'day: " + actorList.get(position).getDob());
holder.tvCountry.setText(actorList.get(position).getCountry());
holder.tvHeight.setText("Height: " + actorList.get(position).getHeight());
holder.tvSpouse.setText("Spouse: " + actorList.get(position).getSpouse());
holder.tvChildren.setText("Children: " + actorList.get(position).getChildren());
return v;
}
static class ViewHolder {
public ImageView imageview;
public TextView tvName;
public TextView tvDescription;
public TextView tvDOB;
public TextView tvCountry;
public TextView tvHeight;
public TextView tvSpouse;
public TextView tvChildren;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}
Used the Android Universal Image-Loader This is best
Declare
private ImageLoader imageLoader1;
On Create
imageLoader1 = ImageLoader.getInstance();
imageLoader1.init(ImageLoaderConfiguration.createDefault(getActivity()));
no_image here a drawable image without any image load in Cache
DisplayImageOptions
options = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.showImageOnLoading(R.drawable.no_image) // resource or drawable
.showImageForEmptyUri(R.drawable.no_image) // resource or drawable
.showImageOnFail(R.drawable.no_image)
.considerExifParams(true)
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
imageLoader1.displayImage(yourpath.replace(" ", "%20"), ivprofile, options);
You Can Use Piccaso Also and Glide also
here is the code after editing it works like a charm
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
public class ActorAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Actors> movieItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public ActorAdapter(Activity activity, List<Actors> movieItems) {
this.activity = activity;
this.movieItems = movieItems;
}
#Override
public int getCount() {
return movieItems.size();
}
#Override
public Object getItem(int location) {
return movieItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_item, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView thumbNail = (NetworkImageView) convertView
.findViewById(R.id.flag);
TextView title = (TextView) convertView.findViewById(R.id.rank);
// getting movie data for the row
Actors m = movieItems.get(position);
// thumbnail image
thumbNail.setImageUrl(m.getImage(), imageLoader);
// title
title.setText(m.getName());
return convertView;
}
}

Cannot resolve constructor adapter with listview using baseadapter

I want to know how to pass the argument to custom adapter . I'm trying to implement a YouTube video list using listview + baseadapter. I'm not sure how to populate properly the listview using the baseadapter
My error is:
Error:(67, 39) error: constructor VideoListAdapter in class YouTubeVideo.VideoListAdapter cannot be applied to given types;
required: Context
found: YouTubeVideo,int,List<Video>
reason: actual and formal argument lists differ in length
Here is my code:
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.crashlytics.android.Crashlytics;
import com.google.android.youtube.player.YouTubeApiServiceUtil;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubeThumbnailLoader;
import com.google.android.youtube.player.YouTubeThumbnailView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import io.fabric.sdk.android.Fabric;
public class YouTubeVideo extends AppCompatActivity {
public static List<Video> MyVideo = new ArrayList<Video>();
public static Map<String, Video> Video_Map = new HashMap<>();
private static void addItem(final Video currentVideo) {
MyVideo.add(currentVideo);
Video_Map.put(currentVideo.getVideoId(), currentVideo);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_you_tube_video);
Fabric.with(this, new Crashlytics());
//Check for any issues
final YouTubeInitializationResult result = YouTubeApiServiceUtil.isYouTubeApiServiceAvailable(this);
if (result != YouTubeInitializationResult.SUCCESS) {
//If there are any issues we can show an error dialog.
result.getErrorDialog(this, 0).show();
}
populateVideoList();
populateListView();
}
private void populateVideoList() {
addItem(new Video("tttG6SdnCd4", "Open in the YouTube App"));
addItem(new Video("x-hH_Txxzls", "Open in the YouTube App in fullscreen"));
addItem(new Video("TTh_qYMzSZk", "Open in the Standalone player in fullscreen"));
addItem(new Video("tttG6SdnCd4", "Open in the Standalone player in \"Light Box\" mode"));
addItem(new Video("x-hH_Txxzls", "Open in the YouTubeFragment"));
}
private void populateListView() {
ArrayAdapter<Video> adapter = new VideoListAdapter(YouTubeVideo.this, R.layout.video_view, MyVideo);
ListView list = (ListView) findViewById(R.id.videoListView);
list.setAdapter(adapter);
}
//------------------------------------------------------------------------------------------------------------------- 12/05/16
private class VideoListAdapter extends BaseAdapter implements YouTubeThumbnailView.OnInitializedListener {
private Context mContext;
private Map<View, YouTubeThumbnailLoader> mLoaders;
public VideoListAdapter(final Context context) {
mContext = context;
mLoaders = new HashMap<>();
}
#Override
public int getCount() {
return MyVideo.size();
}
#Override
public Object getItem(int position) {
return MyVideo.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
//------------------------------------------------------------------------------------------------------------------- 13/05/16
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View videoRow = convertView;
VideoHolder holder;
final Video currentVideo = MyVideo.get(position);
if (videoRow == null) {
//Create the row
final LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
videoRow = inflater.inflate(R.layout.video_view, parent, false);
//Create the video holder
holder = new VideoHolder();
//Set the title
holder.title = (TextView) videoRow.findViewById(R.id.textView_title);
holder.title.setText(currentVideo.getVideoTitle());
//Initialise the thumbnail
holder.thumb = (YouTubeThumbnailView) videoRow.findViewById(R.id.imageView_thumbnail);
holder.thumb.setTag(currentVideo.getVideoId());
holder.thumb.initialize(mContext.getString(R.string.DEVELOPER_KEY), this);
videoRow.setTag(holder);
} else {
//Create it again
holder = (VideoHolder) videoRow.getTag();
final YouTubeThumbnailLoader loader = mLoaders.get(holder.thumb);
//Set the title
if (currentVideo != null) {
holder.title.setText(currentVideo.getVideoTitle());
if (loader == null) {
//Loader is currently initialising
holder.thumb.setTag(currentVideo.getVideoId());
} else {
//The loader is already initialised
loader.setVideo(currentVideo.getVideoId());
}
}
}
return videoRow;
}
#Override
public void onInitializationSuccess(YouTubeThumbnailView view, YouTubeThumbnailLoader loader) {
mLoaders.put(view, loader);
loader.setVideo((String) view.getTag());
}
#Override
public void onInitializationFailure(YouTubeThumbnailView thumbnailView, YouTubeInitializationResult errorReason) {
final String errorMessage = errorReason.toString();
Toast.makeText(mContext, errorMessage, Toast.LENGTH_LONG).show();
}
private class VideoHolder {
YouTubeThumbnailView thumb;
TextView title;
}
}
}
I can not find a constructor in VideoListAdapter with three parameters , I think you missed the following constructor in VideoListAdapter
public VideoListAdapter (Context context, int layoutResourceId,
List<Video> myvideos) {
super(activity, layoutResourceId, myvideos);
mContext = context;
}
or replace
ArrayAdapter<Video> adapter = new VideoListAdapter(YouTubeVideo.this, R.layout.video_view, MyVideo);
with
VideoListAdapter adapter = new VideoListAdapter(YouTubeVideo.this);
It is really easy to resolve it;
public VideoListAdapter (Context context, int layoutId, List lists) {
super(context);
mContext = context;
this.layoutId = layoutId;
this.lists = lists;
}
good luck!

How to add a listview item to a whole other listview

So in my android app, I have two scrollable tabs which each contain Listview using a Fragment. One a list of apps and the other is blank. What I am aiming to do is add a plus button in place of where my checkbox is and duplicate that item in the other listview which is blank.
I have done research on this, but I have not found any successful examples on how to implement this.
Android - Add an item from one ListView to another ListView?
Here is my fragment that returns the apps
package com.spicycurryman.getdisciplined10.app;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageItemInfo;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import com.ibc.android.demo.appslist.app.ApkAdapter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class InstalledAppActivity extends Fragment
implements OnItemClickListener {
PackageManager packageManager;
ListView apkList;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setHasOptionsMenu(true);
View rootView = inflater.inflate(R.layout.user_installed, container, false);
packageManager = getActivity().getPackageManager();
/*To filter out System apps*/
apkList = (ListView) rootView.findViewById(R.id.applist);
new LoadApplications(getActivity().getApplicationContext()).execute();
return rootView;
}
/**
* Return whether the given PackageInfo represents a system package or not.
* User-installed packages (Market or otherwise) should not be denoted as
* system packages.
*
* #param pkgInfo
* #return boolean
*/
private boolean isSystemPackage(PackageInfo pkgInfo) {
return ((pkgInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) ? true
: false;
}
private boolean isSystemPackage1(PackageInfo pkgInfo) {
return ((pkgInfo.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) ? false
: true;
}
// Don't need in Fragment
/*#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.block, menu);
// super.onCreateOptionsMenu(menu,inflater);
}*/
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
}
private class LoadApplications extends AsyncTask<Void, Void, Void> {
Context mContext;
private ProgressDialog pDialog;
List<PackageInfo> packageList1 = new ArrayList<PackageInfo>();
public LoadApplications(Context context){
Context mContext = context;
}
#Override
protected Void doInBackground(Void... params) {
List<PackageInfo> packageList = packageManager
.getInstalledPackages(PackageManager.GET_PERMISSIONS);
/* List<ApplicationInfo> list = mContext.getPackageManager().getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES);
for(int n = 0;n<list.size();n++){
if ((list.get(n).flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP))
}*/
for(PackageInfo pi : packageList) {
boolean b = isSystemPackage(pi);
boolean c = isSystemPackage1(pi);
if(!b || !c ) {
packageList1.add(pi);
}
}
//sort by application name
final PackageItemInfo.DisplayNameComparator comparator = new PackageItemInfo.DisplayNameComparator(packageManager);
Collections.sort(packageList1, new Comparator<PackageInfo>() {
#Override
public int compare(PackageInfo lhs, PackageInfo rhs) {
return comparator.compare(lhs.applicationInfo, rhs.applicationInfo);
}
});
return null;
}
#Override
protected void onCancelled() {
super.onCancelled();
}
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(InstalledAppActivity.this.getActivity());
pDialog.setMessage("Loading your apps...");
pDialog.show();
}
#Override
protected void onPostExecute(Void result) {
apkList.setAdapter(new ApkAdapter(getActivity(), packageList1, packageManager));
if (pDialog.isShowing()){
pDialog.dismiss();
}
super.onPostExecute(result);
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
}
And here is my adapter class:
package com.ibc.android.demo.appslist.app;
import android.app.Activity;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.TextView;
import com.spicycurryman.getdisciplined10.app.R;
import java.util.List;
public class ApkAdapter extends BaseAdapter {
List<PackageInfo> packageList;
Activity context;
PackageManager packageManager;
boolean[] itemChecked;
public ApkAdapter(Activity context, List<PackageInfo> packageList,
PackageManager packageManager) {
super();
this.context = context;
this.packageList = packageList;
this.packageManager = packageManager;
itemChecked = new boolean[packageList.size()];
}
private class ViewHolder {
TextView apkName;
CheckBox ck1;
}
public int getCount() {
return packageList.size();
}
public Object getItem(int position) {
return packageList.get(position);
}
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
LayoutInflater inflater = context.getLayoutInflater();
if (convertView == null) {
convertView = inflater.inflate(R.layout.installed_apps, null);
holder = new ViewHolder();
holder.apkName = (TextView) convertView
.findViewById(R.id.appname);
holder.ck1 = (CheckBox) convertView
.findViewById(R.id.checkBox1);
convertView.setTag(holder);
//holder.ck1.setTag(packageList.get(position));
} else {
holder = (ViewHolder) convertView.getTag();
}
// ViewHolder holder = (ViewHolder) convertView.getTag();
PackageInfo packageInfo = (PackageInfo) getItem(position);
Drawable appIcon = packageManager
.getApplicationIcon(packageInfo.applicationInfo);
String appName = packageManager.getApplicationLabel(
packageInfo.applicationInfo).toString();
appIcon.setBounds(0, 0, 75, 75);
holder.apkName.setCompoundDrawables(appIcon, null, null, null);
holder.apkName.setCompoundDrawablePadding(15);
holder.apkName.setText(appName);
holder.ck1.setChecked(false);
if (itemChecked[position])
holder.ck1.setChecked(true);
else
holder.ck1.setChecked(false);
holder.ck1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (holder.ck1.isChecked())
itemChecked[position] = true;
else
itemChecked[position] = false;
}
});
return convertView;
}
}
How would I go about achieving this?
So what you are doing is, you are populating a listview of installed apps using package manager. Add a plus button in place of the checkbox. Now get installed apps similar to this -
List<PackageInfo> packageList1 = packageManager.getInstalledPackages(0);
final PackageItemInfo.DisplayNameComparator comparator = new PackageItemInfo.DisplayNameComparator(packageManager);
Collections.sort(packageList1, new Comparator<PackageInfo>() {
#Override
public int compare(PackageInfo lhs, PackageInfo rhs) {
return comparator.compare(lhs.applicationInfo, rhs.applicationInfo);
}
});
for (int i = 0; i < packageList1.size(); i++) {
PackageInfo PackInfo = packageList1.get(i);
if (((PackInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) != true) {
//Add to adapter
}
}
}
Now, create a public string array in the activity which is holding the tabs. When you click on the plus button add the packagename to the array.
Now on the other tab use the same adapter, but here before adding it to the adapter check if it is found in the string array using the index. Something like -
List<PackageInfo> packageList1 = packageManager.getInstalledPackages(0);
final PackageItemInfo.DisplayNameComparator comparator = new PackageItemInfo.DisplayNameComparator(packageManager);
Collections.sort(packageList1, new Comparator<PackageInfo>() {
#Override
public int compare(PackageInfo lhs, PackageInfo rhs) {
return comparator.compare(lhs.applicationInfo, rhs.applicationInfo);
}
});
for (int i = 0; i < packageList1.size(); i++) {
PackageInfo PackInfo = packageList1.get(i);
if (((PackInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) != true) {
if (Mainactivity.array contains String PackageName= PackInfo.packageName)
{
//Add to adapter
}
}
}
}
To persist the selected apps, add their package name to shared_preferences.
edit :
In your fragment's LoadApplications class, you retrieve a list of installed apps. On the second fragment use the same code, but just add one more condition
for(PackageInfo pi : packageList) {
boolean b = isSystemPackage(pi);
boolean c = isSystemPackage1(pi);
if(!b || !c ) {
if (array contains packagename){
packageList1.add(pi);
}
}
List<UserApps> packageListBlocked = new ArrayList<UserApps>();
holder.ck1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (holder.ck1.isChecked())
itemChecked[position] = true;
packageListBlocked.add(packageList.get(position));
else
itemChecked[position] = false;
}
});
ArrayList can hold duplicate data, so be cautious while adding.
Now you have all checkedItems in packageListBlocked pass it on to next tab and set data, make sure you call adapter.notifyDataSetChanged();

ApplicationAdapter error when trying to get installed apps

I am have scrollable tabs in my action bar and in one of those tabs I am trying to get a list of user installed apps and used system apps, like Flipoard, youtube, messaging etc. (eventually in alphabetical order)
I am trying to follow these, but I am having some errors implementing it because I am using fragments.
How to get a list of installed android applications and pick one to run
http://javatechig.com/android/how-to-get-list-of-installed-apps-in-android
http://techblogon.com/get-installed-applications-list-android-example/
This is what I have for my Fragment:
package com.spicycurryman.getdisciplined10.app;
import android.app.ProgressDialog;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageItemInfo;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import com.ibc.android.demo.appslist.app.ApplicationAdapter;
import java.util.ArrayList;
import java.util.List;
public class InstalledAppActivity extends Fragment
implements OnItemClickListener {
PackageManager packageManager;
ListView apkList;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setHasOptionsMenu(true);
View rootView = inflater.inflate(R.layout.user_installed, container, false);
packageManager = getActivity().getPackageManager();
/*To filter out System apps*/
apkList = (ListView) rootView.findViewById(R.id.applist);
new LoadApplications().execute();
return rootView;
}
/**
* Return whether the given PackageInfo represents a system package or not.
* User-installed packages (Market or otherwise) should not be denoted as
* system packages.
*
* #parampkgInfo
* #return boolean
*/
/* private boolean isSystemPackage(ApplicationInfo pkgInfo) {
return ((pkgInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) ? true
: false;
}*/
// Don't need in Fragment
/*#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.block, menu);
// super.onCreateOptionsMenu(menu,inflater);
}*/
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
}
private class LoadApplications extends AsyncTask<Void, Void, Void> {
private ProgressDialog pDialog;
List<ApplicationInfo> packageList1 = new ArrayList<ApplicationInfo>();
#Override
protected Void doInBackground(Void... params) {
List<ApplicationInfo> packages = packageManager.getInstalledApplications(PackageManager.GET_META_DATA);
for(ApplicationInfo pi : packages) {
packageList1.add(pi);
}
//sort by application name
final PackageItemInfo.DisplayNameComparator comparator = new PackageItemInfo.DisplayNameComparator(packageManager);
/*Collections.sort(packageList1, new Comparator<PackageInfo>() {
#Override
public int compare(PackageInfo lhs, PackageInfo rhs) {
return comparator.compare(lhs.applicationInfo, rhs.applicationInfo);
}
});*/
return null;
}
#Override
protected void onCancelled() {
super.onCancelled();
}
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(InstalledAppActivity.this.getActivity());
pDialog.setMessage("Loading your apps...");
pDialog.show();
}
#Override
protected void onPostExecute(Void result) {
apkList.setAdapter(new ApplicationAdapter(getActivity(), packageList1, packageManager));
if (pDialog.isShowing()){
pDialog.dismiss();
}
super.onPostExecute(result);
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
}
and this here is my ArrayAdapter class:
package com.ibc.android.demo.appslist.app;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.spicycurryman.getdisciplined10.app.R;
import java.util.List;
public class ApplicationAdapter extends ArrayAdapter<ApplicationInfo> {
private List<ApplicationInfo> appsList = null;
private Context context;
private PackageManager packageManager;
public ApplicationAdapter(Context context, List<ApplicationInfo> textViewResourceId,
PackageManager appsList) {
super(context, textViewResourceId, appsList);
this.context = context;
this.appsList = (List<ApplicationInfo>) appsList;
packageManager = context.getPackageManager();
}
#Override
public int getCount() {
return ((null != appsList) ? appsList.size() : 0);
}
#Override
public ApplicationInfo getItem(int position) {
return ((null != appsList) ? appsList.get(position) : null);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (null == view) {
LayoutInflater layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.snippet_list_row, null);
}
ApplicationInfo data = appsList.get(position);
if (null != data) {
TextView appName = (TextView) view.findViewById(R.id.app_name);
TextView packageName = (TextView) view.findViewById(R.id.app_package);
ImageView iconview = (ImageView) view.findViewById(R.id.app_icon);
appName.setText(data.loadLabel(packageManager));
packageName.setText(data.packageName);
iconview.setImageDrawable(data.loadIcon(packageManager));
}
return view;
}
};
This is the current error I am getting.
I am not sure what I should do to resolve this error and successfully get a list of user installed and used system apps in alphabetical order in all in a fragment.
What can be done about my approach and how can I achieve this?
One of the arguments you're passing to the constructor of the super class, that is an ArrayAdapter, does not match with any of the ArrayAdapter's constructors.
I believe that argument is the the PackageManager appsList, you should instead pass a List<T> appsList to match the constructor defined here.

Very slow scroll, context menu and crash by ProgressDialog

i have many problem with this code
ApplicationAdapter
import java.util.List;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class ApplicationAdapter extends ArrayAdapter<ApplicationInfo> {
private List<ApplicationInfo> appsList = null;
private Context context;
private PackageManager packageManager;
public ApplicationAdapter(Context context, int textViewResourceId,
List<ApplicationInfo> appsList) {
super(context, textViewResourceId, appsList);
this.context = context;
this.appsList = appsList;
packageManager = context.getPackageManager();
}
#Override
public int getCount() {
return ((null != appsList) ? appsList.size() : 0);
}
#Override
public ApplicationInfo getItem(int position) {
return ((null != appsList) ? appsList.get(position) : null);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (null == view) {
LayoutInflater layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.snippet_list_row, null);
}
ApplicationInfo data = appsList.get(position);
if (null != data) {
TextView appName = (TextView) view.findViewById(R.id.app_name);
TextView packageName = (TextView) view.findViewById(R.id.app_paackage);
ImageView iconview = (ImageView) view.findViewById(R.id.app_icon);
appName.setText(data.loadLabel(packageManager));
packageName.setText(data.packageName);
iconview.setImageDrawable(data.loadIcon(packageManager));
}
return view;
}
};
MainActivity
import java.util.ArrayList;
import java.util.List;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.Button;
import android.widget.ListView;
public class MainActivity extends ListActivity {
private PackageManager packageManager = null;
private List<ApplicationInfo> applist = null;
private ApplicationAdapter listadaptor = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_eclair);
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);
/*
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();
}
*/
Uri packageUri = Uri.parse("package:"+app.packageName);
Intent uninstallIntent =
new Intent(Intent.ACTION_DELETE, packageUri);
startActivity(uninstallIntent);
}
private 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,
"Caricamento applicazioni in corso...");
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
}
First, if you are viewing the ProgressDialog I rotate the phone, the application crashes even though I put the onDestroy method. Second, the scroll is very slow, you have no idea on how I can improve it and make it fluid? Third and last thing, I just can not enter a ContextMenu, I really did many attempts but I always get errors. Do you know help me?
When you switch orientations, Android will create a new View. You're probably getting crashes because your background thread is trying to change the state on the old one. (It may also be having trouble because your background thread isn't on the UI thread)
Post error from logcat

Categories