Getting a list of Bluetooth devices Android Studio/Kotlin - android-studio

Tell me how to write additional permissions or how to write it differently. I created such a small function to get a list of already paired devices. I did it according to the guide and everything works that way for a person there, but it highlights me in red and asks me to specify some permissions, and I can't find information on this. Below I will attach the function itself and the proposed solution.
P.S. I have registered Bluetooth and bluetooth_connect permissions in AndroidManifest.
private fun getPairedDevises(){
val pairedDevices: Set<BluetoothDevice>? = btAdapter?.bondedDevices
val tempList = ArrayList<ListItem>()
pairedDevices?.forEach {
tempList.add(ListItem(it.name, it.address))
Log.d("MyLog", "Name: ${it.name}")
}
adapter.submitList(tempList)
}
And this is shown if you click on the hint
private fun getPairedDevices(){
val pairedDevices: Set<BluetoothDevice>? = btAdapter?.bondedDevices
val tempList = ArrayList<ListItem>()
pairedDevices?.forEach {
if (ActivityCompat.checkSelfPermission(
this,
Manifest.permission.BLUETOOTH_CONNECT
) != PackageManager.PERMISSION_GRANTED
) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return
}
tempList.add(ListItem(it.name, it.address))
Log.d("MyLog", "Name: ${it.name}")
}
adapter.submitList(tempList)
}
If I restart the project, it compiles, but the list of devices is not displayed

Related

How can I share Intent contents using a link?

I want to share something (like a text, image, etc) using a link with Android Intents.
For example:
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, someTextView.getText());
sendIntent.setType("text/plain");
Intent shareIntent = Intent.createChooser(sendIntent, null);
startActivity(shareIntent);
This code allows me to share a text. But I want that this content will be shared with a link, like this:
https://my-aplication/someText
And then, when the user enters in the page, gets the current shared text.
How can I do that? I investigated about using Android App Links, but I didn't understand very well.
Also I tried to search in other places but I didn't find anything.
Thanks for helping!
After investigating about this topic, I found Google Firebase Dynamic Links. I watched some videos about this topic. This code generates a key which can be shared by a link. First, you must create a dynamic link in you firebase console. Then, you add these methods. Here's the first method to get Dynamic link data:
FirebaseDynamicLinks.getInstance().getDynamicLink(getIntent()).addOnSuccessListener(this, new OnSuccessListener<PendingDynamicLinkData>() {
#Override
public void onSuccess(PendingDynamicLinkData pendingDynamicLinkData) {
// getting deep link
Uri deeplink = null;
if(pendingDynamicLinkData != null){
deeplink = pendingDynamicLinkData.getLink();
}
// getting deeplink content
if(deeplink != null)
{
String sharedList = deeplink.getQueryParameter("sharedList");
userReference[0] = database.getReference(sharedList);
}
else userReference[0] = database.getReference().push();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, "Ooops, we couldn't get the link data :(", Toast.LENGTH_SHORT).show();
}
});
And here's the second one, to generate a link:
// generating dynamic link
private void GenerateLink(String listId) {
System.out.println("Generating link: " + listId);
DynamicLink dynamicLink = FirebaseDynamicLinks.getInstance().createDynamicLink()
.setLink(Uri.parse("https://www.your_dynamic_link.com/?your_variable_to_share=" + value))
.setDomainUriPrefix("https://your_short_url.page.link")
.setAndroidParameters(
new DynamicLink.AndroidParameters.Builder("com.example.your_package")
.setMinimumVersion(1)
.build())
.buildDynamicLink();
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "I share you my list: " + dynamicLink.getUri());
sendIntent.setType("text/plain");
startActivity(sendIntent);
}

Release invoice on new screen

I need your help.
I have created a new screen, where I am calling all invoices pending release.
I have problems to release, I send a message where you request (you want to release).
It shows me the infinite message.
Only once should you ask me, then you should go out and follow the normal process.
public ProcessDocNew()
{
// Acuminator disable once PX1008 LongOperationDelegateSynchronousExecution [Justification]
Document.SetProcessDelegate(
delegate (List<ARInvoice> list)
{
List<ARRegister> newlist = new List<ARRegister>(list.Count);
foreach (ARInvoice doc in list)
{
newlist.Add(doc);
}
ProcessDoc(newlist, true);
}
);
Document.SetProcessCaption(ActionsMensje.Process);
Document.SetProcessAllCaption(ActionsMensje.ProcessAll);
}
public virtual void ProcessDoc(List<ARRegister> list, bool isMassProcess)
{
string title = "Test";
string sms = "¿Stamp?";
var Graph = PXGraph.CreateInstance<ARInvoiceEntry>();
ARInvoice document = Document.Current;
PEFEStampDocument timbrar = new PEFEStampDocument();/*This is a class where it is, all my method*/
if (isMassProcess == true)
{
Document.Ask(title, sms, MessageButtons.YesNo, MessageIcon.Question);
{
PXLongOperation.StartOperation(Graph, delegate
{
timbrar.Stamp(document, Graph); /*here I have my release method*/
});
}
}
}
public static class ActionsMensje
{
public const string Process = "Process";
public const string ProcessAll = "Process All";
}
I await your comments
Only once should you ask me, then you should go out and follow the
normal process.
That is not how the processing pattern works. The process delegate is called for each record and is therefore not a valid location to display a message that should be shown only once.
You would need to add a custom action to achieve that behavior. The scenario you're looking for should be implemented with a processing filter checkbox and processing filter to comply with best practices:
Documentation on processing screens implementation is available here:
https://help-2019r2.acumatica.com/Help?ScreenId=ShowWiki&pageid=a007b57b-af69-4c0f-9fd1-f5d98351035f

How to remove the Effective Permission in Orchard CMS

I dont want to set the Effective permission when creating the role permissions. I want to set only for the allow checkbox selection.
When i check the "Site Owner Permissions" , automatically selected to all the Effective checkbox. I dont want to select the Effective selection.
Please refer the attached image.
Role-Effective checkbox image:
Any suggestion on what i might be doing wrong? Thanks.
Each module can define it's own permissions and the effective permission is determined based on the permission definitions:
http://docs.orchardproject.net/en/latest/Documentation/Custom-permissions/
Orchard supports so called ImpliedBy permissions and there are also hardcoded stuff like Administator role can do anything.
I struggled with this issue too and i solved it by using a custom authorization event handler to avoid the hardcoded Administator role handling:
public abstract class ExplicitPermissionAuthorizationEventHandler : Orchard.Security.IAuthorizationServiceEventHandler
{
// public
public ExplicitPermissionAuthorizationEventHandler(Orchard.Data.IRepository<Orchard.Roles.Models.UserRolesPartRecord> aUserRolesPartRecords)
{
mUserRolesPartRecords = aUserRolesPartRecords;
}
public void Checking(Orchard.Security.CheckAccessContext aContext) {}
public void Adjust(Orchard.Security.CheckAccessContext aContext) {}
public void Complete(Orchard.Security.CheckAccessContext aContext)
{
if (aContext.Granted && IsModulePermission(aContext.Permission) && aContext.User != null)
{
var lIsAdministrator = mUserRolesPartRecords.Fetch(r => r.UserId == aContext.User.ContentItem.Id && r.Role.Name == "Administrator").Any();
if (lIsAdministrator)
{
// check whether permission is explicitly assigned as Orchard grants all permissions by default when user is in role "Administrator"
var lHasPermissionExplicitly = mUserRolesPartRecords.Fetch(r => r.UserId == aContext.User.ContentItem.Id &&
r.Role.RolesPermissions.Any(p => p.Permission.FeatureName == ModuleName && p.Permission.Name == aContext.Permission.Name)).Any();
if (!lHasPermissionExplicitly)
aContext.Granted = false;
}
}
}
// protected
protected abstract bool IsModulePermission(Orchard.Security.Permissions.Permission aPermission);
protected abstract string ModuleName { get; }
// private
private Orchard.Data.IRepository<Orchard.Roles.Models.UserRolesPartRecord> mUserRolesPartRecords;
}
This should get you an idea how to use authorization handlers.

"Location not available"?

In my android app that I want to develope, I would like the users can find their position. To do this I have this code in the MainActivity but on the device (when i run it) it can't find latitute longitude and the address.Why?
public class MainActivity extends Activity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private TextView addressField; //Add a new TextView to your activity_main to display the address
private LocationManager locationManager;
private String provider;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
latituteField = (TextView) findViewById(R.id.TextView02);
longitudeField = (TextView) findViewById(R.id.TextView04);
addressField = (TextView) findViewById(R.id.TextView05); //Make sure you add this to activity_main
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
latituteField.setText("Location not available");
longitudeField.setText("Location not available");
}
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
double lat = location.getLatitude();
double lng = location.getLongitude();
Geocoder geoCoder = new Geocoder(this, Locale.getDefault());
StringBuilder builder = new StringBuilder();
try {
List<Address> address = geoCoder.getFromLocation(lat, lng, 1);
int maxLines = address.get(0).getMaxAddressLineIndex();
for (int i=0; i<maxLines; i++) {
String addressStr = address.get(0).getAddressLine(i);
builder.append(addressStr);
builder.append(" ");
}
String fnialAddress = builder.toString(); //This is the complete address.
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
addressField.setText(fnialAddress); //This will display the final address.
} catch (IOException e) {}
catch (NullPointerException e) {}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
Note: This is an old answer which did not help solve the particular problem. However, it is valuable information so I don't delete it.
The blinking GPS icon is a good sign. It means that your app is asking the operating system for the location and the operating system tries to fetch it.
The blinking indicates that the operating system did not complete fetching the location via GPS. If this problem persists for, e.g. more than 1 or 2 minutes, it can have the following reasons:
You do not receive the GPS signal (e.g. because you are in a building with too thick walls).
You do not have a data connection to the internet (on some versions of phones and/or android, GPS doesn't work without data connection. Sounds stupid, but it's true. I am a proud owner of such a phone.)
There is some other bug that causes your GPS to be in a state where it does not generate any more location updates. This happened for me sometimes and I do not know any more background info. After a reboot of the phone, it always worked again.
My guess would be that the best provider is not enabled.
try calling getBestProvider(criteria, true)
also Log.d the provider and you can use isProviderEnabled(provider) to see if the provider is enabled.
I've compiled your example and tested it on a Galaxy S2. Here are my findings:
You have code in your examples for two different approaches of getting the location. One approach is to use LocationManager.getLastKnownLocation(...) to fetch the location directly and the other approach is to implement the LocationListener interface and registering for location updates to get notified about new location updates later.
Upfront info: I got the second approach work fine, but I did not get the approach with the getLastKnownLocation method to work reliably.
The location fetching does not work because as provider, "network" is returned. This happens although GPS is on. The subsequent effect is that, because I have the network location provider switched off, the getLastKnowLocation method returns null as documented there: "If the provider is currently disabled, null is returned." (from getLastKnownLocation )
You can fix this by changing
provider = locationManager.getBestProvider(criteria, false);
to
provider = locationManager.getBestProvider(criteria, true);
.
This will give you the GPS provider, if it is available (switched on). However, the getLastKnownLocation(...) method still returns null for me, although the correct provider (gps) is selected and the provider is available. That means that the documentation of the getLastKnownLocation method is lacking information about another case when it returns null. This seems to be because no last known location was saved for this provider. You can not know if this is the case when starting your application, so you can not rely on this method returning a non-null value at application startup.
And here is the good news: Now that we got the correct location provider, the location updates through the second approach (the registering for future location update notifications) works as expected through the gps provider. Updates are coming in and the locations are shown and updated in the textfields on my test phone.

ContentManager.Create does nothing

I am trying to build a service in Orchard that allows me to create content through a custom form on a page. The service and the content type definitions look fine to me, but somehow, eventhough I don't get any errors or other signs in the Orchard log files, creating new content using the IContentManager does nothing for me.
Parts involved
The controller accepting the form values
[HttpPost]
public ActionResult Create(CreateSopViewModel viewModel)
{
if(!ModelState.IsValid)
{
var shape = _shape.CreateContent();
shape.Header = _shape.Parts_Title(Title: "New item");
// Add the original fields to the shape.
shape.Title = viewModel.Title;
shape.Description = viewModel.Description;
shape.InitialComments = viewModel.InitialComments;
return new ShapeResult(this, shape);
}
// Store the new procedure in the database
_service.CreateContentItem(
viewModel.Title,viewModel.Description,viewModel.InitialComments);
// Redirect the user back to the homepage.
return Redirect("~/");
}
The service that contains the CreateContentItem method:
public void CreateContentItem(string title, string description, string initialComments)
{
// Initialize a new content item based on the SOP type
var customPart = _services.ContentManager.New<MyCustomPart>("CustomContentType");
customPart.Description = description;
customPart.Identifier = BuildIdentifier(title);
customPart.ContentItem.As<TitlePart>().Title = title;
_services.ContentManager.Create(customPart.ContentItem);
}
The content part + record
public class MyCustomPart: ContentPart<MyCustomPartRecord>
{
[Required]
public string Identifier
{
get { return Record.Identifier; }
set { Record.Identifier = value; }
}
[Required]
public string Description
{
get { return Record.Description; }
set { Record.Description = value; }
}
}
public class MyCustomPartRecord: ContentPartRecord
{
public virtual string Identifier { get; set; }
public virtual string Description { get; set; }
}
The migration
SchemaBuilder.CreateTable(typeof(MyCustomPartRecord).Name, table => table
.ContentPartRecord()
.Column<string>("Description")
.Column<string>("Identifier"));
ContentDefinitionManager.AlterPartDefinition("StandardOperationalProcedurePart", builder => builder
.Attachable(true));
ContentDefinitionManager.AlterTypeDefinition("CustomContentType", builder => builder
.DisplayedAs("Custom Content Type")
.WithPart("TitlePart")
.WithPart("MyCustomPart")
.Creatable(true));
Question
Again, I don't get any errors, not in the log and not in Visual Studio. However, my new content item doesn't get created or at least, I can't see it in the admin section of the site under Content.
What is going on and how can I debug this behavior?
I had a similar problem, which was solved when I used the overloaded Create method taking a VersionOptions enum value:
content.Create(customPart.ContentItem, VersionOptions.Published);
This should work even if the content item is not creatable, as mine isn't.
I had a similar issue. In my case the item did appear eventually, but not right away.
The solution for me was to do:
_contentManager.Flush();
I was having this issue, in my case it was that I actually had an error in the database (trying to put 100+ characters into a field that would only hold 100!).
I found the error I was getting (null id in Orchard.Indexing.Models.IndexingTaskRecord entry (don't flush the Session after an exception occurs) ), actually masked the issue. I had to go hunt in the logs to find the real problem.
So anyway, my advice is if you see that contentmanager.create seems to be doing nothing, and any errors don't seem to help, check the logs carefully. They can be found in the logs sub-folder of the appdata folder in the main Orchard.Web project. Because as I've found in the last 48 hours, often the answer is there.

Resources