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.
Related
Ok, so i need to display some of my product's database data on the scanner builder window(as shown in the image) when this product gets scanned. Scanner window results
As you can see in the image, the barcode scanner is displayed, my question is: is it possible to print in this windows some other data except from the product's barcode? if yes how should i move?
this is my windows builder code
public void handleResult(Result result) {
//myResult= barcode text
myResult = result.getText();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Scan Result");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
scannerView.resumeCameraPreview(addquantityactivity.this);
updateData();
}
});
builder.setNeutralButton("Visit(if url)", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(myResult));
startActivity(browserIntent);
}
});
builder.setMessage(result.getText());
AlertDialog alert1 = builder.create();
alert1.show();
}
Do you see where it says builder.setMessage(result.getText()); <--?
This is where you'd set the result. At the moment you're just putting in the result text which is the number. If you want something more, there is where you would put it.
EDIT:
I'm terrible at writing answers. The method you are using is defined here. It takes in a Character Sequence and will display it. Or it can take in an Int and show that.
EDIT2:
As an example of concatenating the barcode with some other information I would do this:
String myMessage = result.getText() + " and some other amazing information about this barcode";
builder.setMessage(myMessage);
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();
I want to check for internet connection and if it's available call getData() but if it's not available show a dialog with RETRY and CANCEL options.
If RETRY is clicked check for internet connection; if available call getData but if it isn't available, show the dialog again (something like looping).
Alternatively, if CANCEL is clicked exit the app altogether.
I'm using this class to check for network availability and internet connection:
public class NetworkCheck {
public static boolean isAvailableAndConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
boolean isNetworkAvailable = cm.getActiveNetworkInfo() != null;
boolean isNetWorkConnected = isNetworkAvailable && cm.getActiveNetworkInfo().isConnected();
return isNetWorkConnected;
}
}
And in MainActivity I do this:
if (NetworkCheck.isAvailableAndConnected(this)) {
//Caling method to get data
getData();
} else {
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle("No Internet Connection");
alertDialogBuilder.setMessage("Failed to load. Please ensure ypu're connected to the internet and try again");
alertDialogBuilder.setPositiveButton("Retry", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (!NetworkCheck.isAvailableAndConnected(context)) {
alertDialogBuilder.show();
} else {
getData();
}
}
});
alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alertDialogBuilder.show();
}
From the above codes, I have three questions:
In line if (!NetworkCheck.isAvailableAndConnected(context)) { context is being highlighted in red and when I hover it, I see Cannot resolve symbol 'context'. If I leave the method empty or type this or getActivity; Android Studio complains. Which parameter show I pass the method?
Calling finish() will only kill the activity. Shoudn't the whole app be killed and how?
What else am I doing wrong?
1) If you're not using fragments, on the place of context you could do a workaround like this (first you declare):
final Context mContext;
mContext = this;
Then you substitute context to mContext
2) Killing the activity is not a recommendation (you probably already read about Activity Lifecycle), but you could try android.os.Process.killProcess(android.os.Process.myPid());
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();
}
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.