Get And Display List Of Installed Programs on Android - java

I'm currently developing an app that will allow the user to choose an app and launch it at a later time (there is more functionality but this is the main thing I'm having an issue with.)
I'm looking for a way to get a list of the applications (user installed or updateable ex. Gmail, GMaps, etc...) And throw it into an AlertDialog similar to how you add a shortcut to the Homescreen (Long press -> Applications).
This is the thread I'm using that has the code to get the list of applications that I need. However how would I turn this into an AlertDialog?
Here is the code from the thread.
public void getApps()
{
PackageManager pm = getPackageManager();
List<ApplicationInfo> apps = pm.getInstalledApplications(0);
List<ApplicationInfo> installedApps = new ArrayList<ApplicationInfo>();
for(ApplicationInfo app : apps) {
//checks for flags; if flagged, check if updated system app
if((app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) == 1) {
installedApps.add(app);
//it's a system app, not interested
} else if ((app.flags & ApplicationInfo.FLAG_SYSTEM) == 1) {
//Discard this one
//in this case, it should be a user-installed app
} else {
installedApps.add(app);
}
}
}//end getApps()
And here is the code I use for displaying an AlertDialog similar to what I want to use.
//PseudoCode does not compile
public void displayAppList(View v)
{
final CharSequence[] items = {getApps()};
AlertDialog.Builder builder = new AlertDialog.Builder(SchedulerActivity.this);
builder.setTitle("Choose an App To Launch");
builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
appChoiceString[count] = items[item];
Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
}
});
builder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Toast.makeText(SchedulerActivity.this, "Success", Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Toast.makeText(SchedulerActivity.this, "Fail", Toast.LENGTH_SHORT).show();
}
});
AlertDialog alert = builder.create();
alert.show();
}
Any help as to getting this to display properly would be awesome.

Why not just use the standard intent chooser? (See this). Otherwise, you probably want to explain what is not displaying the way you want, and how you really want it to look in detail.

Related

Delete touch around a dialog in Java Android Studio

I'm looking at how to remove the effect of the touch around a dialog
I created a dialog when there is no connection detected
Code
#Override
public void onErrorResponse(String _param1, String _param2) {
final String _tag = _param1;
final String _message = _param2;
nc.setTitle("No connection");
nc.setIcon(R.drawable.ic_launcher);
nc.setMessage("Turn on your connection and then relaunch the app");
nc.setPositiveButton("Retry", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface _dialog, int _which) {
i.setClass(getApplicationContext(), SplashActivity.class);
startActivity(i);
}
});
nc.setNegativeButton("Close App", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface _dialog, int _which) {
finish();
}
});
nc.create().show();
}
};
}
When the dialog appears it must make the 350x100
When I click on the screen around the dialog it removes
I would like to know if it is possible to remove the touch around the dialog when it is displayed ?
Try this: dialog.setCanceledOnTouchOutside(false);. It will still allow you to cancel the dialog with back button, but it will prevent the dialog from closing when touching around it.
EDIT
In your code you should change the nc.create().show(); at the end to:
AlertDialog alertDialog = nc.create();
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.show();
You probably need to add setCancelable(false) during creating
https://developer.android.com/reference/android/app/AlertDialog

Android selectable Bluetooth List

How can I make a popup on Android so when you click one of the devices it saves the device name to a variable. When I do it nothing happens and I really need some help with how to figure this out.
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
// No bluetooth support on device
}
if (mBluetoothAdapter != null)
{
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
String[] btarray;
List<String> btlist = new ArrayList<String>();
BTArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
// get paired devices
pairedDevices = mBluetoothAdapter.getBondedDevices();
// put it's one to the adapter
for(BluetoothDevice device : pairedDevices) {
btlist.add(device.getAddress());
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("BT")
.setItems(btlist2, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// The 'which' argument contains the index position
// of the selected item
}
});
builder.create();
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("BT")
.setItems(btlist2, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// The 'which' argument contains the index position
// of the selected item
}
});
builder.create();
This didn't work
Okay the info you provided is incomplete so here is my guesswork.
You have adapter BTArrayAdapter instance but you are not using it.
You seems to have btlist but trying to use btlist2
You are building AlertDialog but not showing it.
Not sure if you are correctly requesting bluetooth permissions as you did not provide the info
So these are the things you need to check:
Once you created your adapter, you need to populate it with data somehow, e.g. BTArrayAdapter.addAll(btlist);
Make sure you're using the data list you are actually populating (btlist)
Once you built your dialog, make sure to show it (builder.create().show();)
Make sure you have <uses-permission android:name="android.permission.BLUETOOTH" /> in your manifest and make sure you are requesting location permissions dynamically (better try to populate list manually and see if it's showing, then you'll know it's something wrong with the permissions request)
I think instead of setItems of AlertDialog.Builder you should be using:
.setAdapter(BTArrayAdapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
PS.: actually you are not discovering so you probably don't need to ask for location permissions.

AlertDialog not displaying in android studio

I have an AlertDialog in android studio as shown below:
final EditText columninput = new EditText(this);
columninput.setInputType(InputType.TYPE_CLASS_NUMBER);
AlertDialog.Builder adb = new AlertDialog.Builder(this);
adb.setTitle("Choose column number");
adb.setView(columninput);
adb.setMessage("Please specify the number of columns you would like to decrypt your message with.");
adb.setCancelable(true);
adb.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
boolean bool = true;
try {
col = Integer.parseInt(columninput.getText().toString());
}
catch (Exception e) {
bool = false;
Toast t = Toast.makeText(getApplicationContext(), "Incorrect input", Toast.LENGTH_LONG);
t.show();
}
if (bool) {
dialog.dismiss();
}
}
});
adb.show();
method1(toRead, col);
Note that toRead is another variable dealt with outside of this context; it should not be causing any errors. When I run my application, the AlertDialog is never shown, and method1 runs immediately. However, when I comment out the last line (method1(toRead, col)), the alertdialog appears when the application is run. Why is this, and how can I ensure that the alertDialog is always shown?
This issue appears because, when you open AlertDialog, the activity goes into pause state.
So, when you hide the last line and don't call the method the activity is able to go into Pause state and the AlertDialog appears successfully.
While in the other case, when the last method is called, what happens is:
before your AlertDialog gets created, the method1() gets called.
I hope this helps.
May this helps you:
Example:
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Delete")
.setMessage("Are you sure you want to delete Product?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dbni.delete(ItemID);
arrayStudent = dbni.selectAll();
list_view.setAdapter(new Adapter_viewitem(mactivity, arrayStudent));
Toast.makeText(getApplicationContext(), "Product deleted successfully", Toast.LENGTH_SHORT).show();
}
}).setNegativeButton("No", null).show();

Android AlertDialog crashes with BadTokenException?

this is my first post so please bear with me.
I'm a high school developer and recently released an Android app on the play store. I'm using Crashlytics to capture exceptions, and for this some reason it throws this error.
Fatal Exception: android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy#1989547c is not valid; is your activity running?
It was reported specifically on the LG D855, Nexus 5, and the Huawei PLK AL10 occurring on versions 5.0, 5.0.2, 5.1.1 and 6.0.1. I've looked online, and have found that this occurs when an activity does not exist. This error occurs on the initial startup of the app.
The following is the code I use for an Alert Dialog which simply asks if the user wants to see a tutorial (y/n)
public void showTutorialDialog() {
AlertDialog tutorialDialog = new AlertDialog.Builder(this)
.setTitle(R.string.tutorial_question_title)
.setCancelable(false)
.setMessage(R.string.tutorial_question)
.setPositiveButton(getResources().getString(R.string.tutorial_question_pos), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Take to tutorial
// Assume isn't backer for now..
finish();
Intent i = new Intent(StartupActivity.this, TutorialActivity.class);
i.putExtra("from", "StartupActivity");
startActivity(i);
}
})
.setNegativeButton(getResources().getString(R.string.tutorial_question_neg), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// No tutorial, ask if they are a backer
showBackerDialog();
}
}).show();
Upon the initial start of the app, I load the users purchase details using IabHelper in a separate class. This class, called PurchaseRetriever, retrieves the content of users purchases asynchronously and stores it in an ArrayList. This is how my code works.
if (mManager.isUserFirstTime()) {
// Initialize purchase retriever.
// The rest will be done when the observer reports that purchase data has been retrieved.
mPurchases = PurchaseRetriever.getInstance(StartupActivity.this);
mPurchases.addObserver(new FirstStartupObserver(this));
StartupManager.FIRST = true;
loadImageContent();
It runs using the Observer pattern, so when the purchase details are queried it calls the update() method in FirstStartupObserver, which then by a reference to StartupActivity, calls startupActivity.showTutorialDialog();where the error occurs.
I've tested it on multiple devices I and my friends own personally (Nexus 6, Nexus 5, Nexus 7 tablet, Samsung Galaxy Tab, various devices on Samsung Remote Lab) yet it works fine on my end...
Any advice appreciated, thanks.
Edit: Here is StartupActivity.
/**
* Main startup activity. Determines which activity to launch.
* Puts the user in one place or another depending on if they are a backer.
*/
public class StartupActivity extends AppCompatActivity {
private StartupManager mManager;
private ProgressBar bar;
// --- Used if first time app loading to query purchase info
private PurchaseRetriever mPurchases;
#Override
protected void onCreate(Bundle savedInstanceState) {
// Used in either cases
// If first time, displayed, if not, hidden//
//hideNavBar();
User.init(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_startup);
bar = (ProgressBar)this.findViewById(R.id.progressBar);
mManager = new StartupManager(this);
// Returns true if data was corrupt before
if (mManager.isDataCorrupt()) {
bar.setVisibility(View.VISIBLE);
loadImageContent();
// Reset watch to default black
// Internally starts NewMainActivity
ErrorManager.fixCorruptData(bar, this);
} else {
// Stays true until user selects watch
if (mManager.isUserFirstTime()) {
// Initialize purchase retriever.
// The rest will be done when the observer reports that purchase data has been retrieved.
mPurchases = PurchaseRetriever.getInstance(StartupActivity.this);
mPurchases.addObserver(new FirstStartupObserver(this));
StartupManager.FIRST = true;
loadImageContent();
} else {
// NOT first time starting app.
mPurchases = PurchaseRetriever.getInstance(StartupActivity.this);
mPurchases.addObserver(new AfterFirstStartupObserver(this));
loadImageContent();
}
}
}
// Two main dialogs used
public void showTutorialDialog() {
AlertDialog tutorialDialog = new AlertDialog.Builder(this)
.setTitle(R.string.tutorial_question_title)
.setCancelable(false)
.setMessage(R.string.tutorial_question)
.setPositiveButton(getResources().getString(R.string.tutorial_question_pos), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Take to tutorial
// Assume isn't backer for now..
finish();
Intent i = new Intent(StartupActivity.this, TutorialActivity.class);
i.putExtra("from", "StartupActivity");
startActivity(i);
}
})
.setNegativeButton(getResources().getString(R.string.tutorial_question_neg), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// No tutorial, ask if they are a backer
showBackerDialog();
}
}).show();
tutorialDialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(Color.RED);
tutorialDialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(Color.RED);
}
private void showBackerDialog() {
// Show AlertDialog ask if they are kickstarter backer
AlertDialog askDialog = new AlertDialog.Builder(this)
.setTitle(getResources().getString(R.string.startup_dialog_title))
.setCancelable(false)
.setMessage(getResources().getString(R.string.startup_dialog_message))
.setPositiveButton(getResources().getString(R.string.startup_dialog_pos), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// User is a backer, take to watch chooser screen, then it takes to login screen
// Also look at Timer with TimerTask
new Thread(new Runnable() {
#Override
public void run() {
try {
Intent i = new Intent(StartupActivity.this, WatchChooserActivity.class);
i.putExtra("from", "StartupActivityBacker");
startActivity(i);
} finally {
finish();
}
}
}).start();
}
})
.setNegativeButton(getResources().getString(R.string.startup_dialog_neg), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// User is not a backer, take to MainActivity
new Thread(new Runnable() {
#Override
public void run() {
try {
Intent i = new Intent(StartupActivity.this, WatchChooserActivity.class);
i.putExtra("from", "StartupActivityNonBacker");
startActivity(i);
} finally {
finish();
}
}
}).start();
}
}).show();
askDialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(Color.RED);
askDialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(Color.RED);
}
Here is the code for FirstStartupObserver.'
public class FirstStartupObserver implements Observer {
private StartupActivity startupActivity;
public FirstStartupObserver(StartupActivity startupActivity) {
this.startupActivity = startupActivity;
}
// Called when the observable is done loading purchase detail
// (Only called when user runs app first time)
#Override
public void update(Observable observable, Object data) {
// Set default first-time watch
// Query product data (the Watchfaces purchased in the form of a WatchFace object)
PurchaseRetriever mPurchases = PurchaseRetriever.getInstance(startupActivity);
if (mPurchases.hasSuccess()) {
ArrayList<DynamicLoader.WatchFace> facesOwned = mPurchases.getPurchasedFaces();
for (DynamicLoader.WatchFace f : facesOwned) {
f.setPurchased(true);
}
// Check if coming from v1.4
if (UpgradeManager.isUpgrading(startupActivity)) {
// Then it calls the code below, but after the async task.
String accessCode = UpgradeManager.getOldAccessCode(startupActivity);
String accessToken = UpgradeManager.getOldAccessToken(startupActivity);
UpgradeManager.migrateBacker(startupActivity, accessCode, accessToken);
} else {
// Ask if they want to see tutorial.
// This is when the exception occurs!!!
startupActivity.showTutorialDialog();
}
return;
} else {
Log.d("TAG", "Showing fail dialog");
DialogUtils.showIabFailDialog(startupActivity, this);
}
}
}
token android.os.BinderProxy#1989547c is not valid; is your activity
running?
This means that you're trying to show your popup while your activity is being destroyed or after it's destroyed.
You can check if your activity isDestroyed like below:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && !isDestroyed()) {
showTutorialDialog();
}
If you're supporting below api 17 devices you can try to use isFinishing in else case. I did not test if it's working as expected. (If i'm wrong please correct me.)
else {
if (!isFinishing()) {
showTutorialDialog();
}
}
Or for a quick fix you can surround with try catch
This is usually caused by doing something in an AsyncTask or other background task which holds a reference to the Activity and tries to display the dialog when the work is done. In this case, it sounds like your FirstStartupObserver is holding a reference to the activity and trying to show a dialog, but the activity may have been destroyed by the time PurchaseRetriever completes its work.
Don't try to test the activity state, and don't catch the BadTokenException. That just masks the problem. The simplest solution would be to cancel the PurchaseRetriever when the activity is paused. If you want the background work to survive configuration changes like rotations but still be restricted to the user-perceived lifetime of the activity, do the work in a retained fragment. Finally, if the background work should continue when the user navigates between activities or puts the app in the background, do the work in a Service and save the result where the activity can retrieve it.
token android.os.BinderProxy#1989547c is not valid; is your activity
running?
You are trying to load the AlertDialog too early, when the Activity doesn't exist! In my apps I load a little tutorial when the activity lifecycle is completed:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
...
...
...
showTutorialDialog();
}

Returning a result from multi-use dialog android

So in my android application, I have a helper class which can create a dialog box using the following code:
public void CreateAlert(String title, String message)
{
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which) { }
});
// Showing Alert Message
alertDialog.show();
}
In my registrar activity, I have an ASyncTask that runs a particular task, following which it processes a boolean variable with the below function:
private void Process(boolean Success)
{
if(Success)
{
appHelper.CreateAlert("Success!", "Well Done!");
// Progress to the activity
startActivity( new Intent(context, Menu.class) );
getActivity().finish();
}
else
{
appHelper.CreateAlert("Failure!", "Please try again.");
}
}
However as you can see from the above code, I am wanting to start an activity based on a succesful result. However, I need the application to wait for the user to click the okay button on the dialog before progressing to the next activity.
What is the best way for this to be done?
EDIT: I should note that the two functions are in different classes, CreateAlert is in a class called AppHelper where as Process is inside Registrar.class, an activity.
Check again the status of boolean success in the click listener of alertDialog's OK button
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which) {
if(Success)
{
// Progress to the activity
context.startActivity( new Intent(context, Menu.class) );
context.getActivity().finish();
}
else
{
// Don't do anything
}
});
and update your Process like below
private void Process(boolean Success)
{
if(Success)
{
appHelper.CreateAlert("Success!", "Well Done!");
}
else
{
appHelper.CreateAlert("Failure!", "Please try again.");
}
}

Categories