ApplicationAdapter error when trying to get installed apps - java

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.

Related

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!

Android after getting user's contacts into a list, Can't use them

I've manged to use the following code for retrieving user's contacts into a list, and now I'm working on the next step (getting individual info of each contact):
package com.example.mycontacts;
import android.app.LoaderManager;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.app.ListFragment;
import android.widget.CursorAdapter;
import android.widget.SimpleCursorAdapter;
/**
* Created by daniel on 28/02/2016.
*/
public class ContactListFragment extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor> {
private CursorAdapter mAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// create adapter once
Context context = getActivity();
int layout = android.R.layout.simple_list_item_1;
Cursor c = null; // there is no cursor yet
int flags = 0; // no auto-requery! Loader requeries.
mAdapter = new SimpleCursorAdapter(context, layout, c, FROM, TO, flags);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// each time we are started use our listadapter
setListAdapter(mAdapter);
// and tell loader manager to start loading
getActivity().getLoaderManager().initLoader(0, null, (android.app.LoaderManager.LoaderCallbacks<Cursor>) this);
}
// columns requested from the database
private static final String[] PROJECTION = {
ContactsContract.Contacts._ID, // _ID is always required
ContactsContract.Contacts.DISPLAY_NAME_PRIMARY // that's what we want to display
};
// and name should be displayed in the text1 textview in item layout
private static final String[] FROM = { ContactsContract.Contacts.DISPLAY_NAME_PRIMARY };
private static final int[] TO = { android.R.id.text1 };
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// load from the "Contacts table"
Uri contentUri = ContactsContract.Contacts.CONTENT_URI;
// no sub-selection, no sort order, simply every row
// projection says we want just the _id and the name column
return new CursorLoader(getActivity(),
contentUri,
PROJECTION,
null,
null,
null);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
// Once cursor is loaded, give it to adapter
mAdapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
// on reset take any old cursor away
mAdapter.swapCursor(null);
}
}
The problem is, I can't find a way to get the info from each contact, in the onItemClick() of the list.
Any idea?
EDIT
I actually added:
ListView newsList = new ListView(getActivity());
newsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
but didn't know how to proceed and how interact with cursor.
EDIT2
I changed it from listfragment to dialogFragment with a listview, but still I don't get the contact's number by pressing on the item (in list).
what am I misiing here?
> package com.example...;
import android.app.LoaderManager;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
/**
* Created by daniel on 28/02/2016.
*/
public class DialogFragment extends android.support.v4.app.DialogFragment implements LoaderManager.LoaderCallbacks<Cursor> {
private TextView dateView;
private Spinner actionSpinner;
private Button okButton;
private CursorAdapter mAdapter;
private TimePicker timePicker;
private static final String[] FROM = { ContactsContract.Contacts.DISPLAY_NAME_PRIMARY };
private static final int[] TO = { android.R.id.text1 };
private ListView list;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.dialog,container,false);
Context context = getActivity();
int layout = android.R.layout.simple_list_item_1;
Cursor c = null; // there is no cursor yet
int flags = 0; // no auto-requery! Loader requeries.
mAdapter = new SimpleCursorAdapter(context, layout, c, FROM, TO, flags);
actionSpinner = (Spinner)v.findViewById(R.id.actionSpinner);
okButton = (Button)v.findViewById(R.id.saveButton);
list = (ListView)v.findViewById(R.id.listView);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(),
R.array.actions, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
actionSpinner.setAdapter(adapter);
okButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getDialog().dismiss();
Comm comm = (Comm) getActivity();
comm.pick();
}
});
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mAdapter.getItem(position);
Toast.makeText(getActivity(), String.valueOf(position), Toast.LENGTH_SHORT).show();
}
});
return v;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
list.setAdapter(mAdapter);
// and tell loader manager to start loading
getActivity().getLoaderManager().initLoader(0, null, (android.app.LoaderManager.LoaderCallbacks<Cursor>) this);
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// load from the "Contacts table"
Uri contentUri = ContactsContract.Contacts.CONTENT_URI;
// no sub-selection, no sort order, simply every row
// projection says we want just the _id and the name column
return new CursorLoader(getActivity(),
contentUri,
PROJECTION,
null,
null,
null); }
private static final String[] PROJECTION = {
ContactsContract.Contacts._ID, // _ID is always required
ContactsContract.Contacts.DISPLAY_NAME_PRIMARY // that's what we want to display
};
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
mAdapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
mAdapter.swapCursor(null);
}
}

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();

Optimization of code for more speed [closed]

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

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