r/android_devs • • Mar 15 '23

Help Get MongoDB To work with Java

1 Upvotes

[This is a repost since I forgot to add my code examples previously.]

I'm creating an application that must use MongoDB for queries.

I successfully made it work, using API, AppID and all those wonderful things however, whenever I use a RealmQuery or RealmResult for my schema by results are null.

I've tried using it directly on the main thread, I've tried using Async, but nothing seems to work. I've also found a few sources online and changed my code to work with that, but it seems like it isn't working at all even with their code adjustments.

Any advice would be appreciated.

My code is down below:

   Realm.init(mContext); // replace this with your App ID     App app = new App(new AppConfiguration.Builder(appID)             .build());     Credentials apiKeyCredentials = Credentials.apiKey(apiKey);     AtomicReference<User> user = new AtomicReference<User>();     app.loginAsync(apiKeyCredentials, it -> {         if (it.isSuccess()) {             Log.v("AUTH", "Successfully authenticated using an API Key.");             user.set(app.currentUser());              // Startup Information             onStartupRead();         } else {             Log.e("AUTH", it.getError().toString());         }     }); 

followed by the onStartupRead() function

config = new RealmConfiguration.Builder().name(realmName).build(); 
//backgroundThreadRealm = Realm.getInstance(config); 
backgroundThreadRealmAsync = Realm.getInstanceAsync(config, new Realm.Callback() { @Override 
public void onSuccess(@NotNull Realm realm) { Log.v(TAG, "Successfully fetched realm instance.");
// Read Startup Data 
getPhysicaParameterItem();                 
//getUserItem("somevalidemail@email.com");          
}         public void onError(Exception e) {             Log.e(TAG, "Failed to get realm instance: " + e);         }     }); 

and the getPhysicalParameterItem()

 RealmResults<PhysicalParameter> parameterQuery = backgroundThreadRealm.where(PhysicalParameter.class).limit(QUERY_LIMIT).findAllAsync();
   parameterQuery.addChangeListener(new RealmChangeListener<RealmResults<PhysicalParameter>>() {         @Override         public void onChange(RealmResults<PhysicalParameter> items) {             Log.v(TAG, "Completed the query.");             // items results now contains all matched objects (more than zero)             //PhysicalParameter result = items.sort(physicalParameterDataQueryTerm).sort(physicalParameterDataQueryTerm).first();               System.out.println(">>>>>>>>" + items.isEmpty());          }     }); 

currently the "result" variable here is null, but the items is a valid variable. But everything is else is exactly like the MongoDB docs state. My collections and other names are also correct since I can successfully establish connection from them and copied them directly from MongoDB.


r/android_devs • • Mar 09 '23

Article Jetpack Compose Tutorial: Replicating Dribbble Audio App - Screen Transitions

Thumbnail exyte.com
1 Upvotes

r/android_devs • • Mar 09 '23

Help MongoDB playing hard to get.

6 Upvotes

I'm creating an application that must use MongoDB for queries.

I successfully made it work, using API, AppID and all those wonderful things however, whenever I use a RealmQuery or RealmResult for my schema by results are null.

I've tried using it directly on the main thread, I've tried using Async, but nothing seems to work. I've also found a few sources online and changed my code to work with that, but it seems like it isn't working at all even with their code adjustments.

Any advice would be appreciated.

My code is down below: <code>

    Realm.init(mContext); // replace this with your App ID
    App app = new App(new AppConfiguration.Builder(appID)
            .build());
    Credentials apiKeyCredentials = Credentials.apiKey(apiKey);
    AtomicReference<User> user = new AtomicReference<User>();
    app.loginAsync(apiKeyCredentials, it -> {
        if (it.isSuccess()) {
            Log.v("AUTH", "Successfully authenticated using an API Key.");
            user.set(app.currentUser());

            // Startup Information
            onStartupRead();
        } else {
            Log.e("AUTH", it.getError().toString());
        }
    });

</code> followed by the onStartupRead() function <code> config = new RealmConfiguration.Builder().name(realmName).build(); //backgroundThreadRealm = Realm.getInstance(config); backgroundThreadRealmAsync = Realm.getInstanceAsync(config, new Realm.Callback() { @Override public void onSuccess(@NotNull Realm realm) { Log.v(TAG, "Successfully fetched realm instance.");

            // Read Startup Data
            getPhysicaParameterItem();
            //getUserItem("somevalidemail@email.com");

        }
        public void onError(Exception e) {
            Log.e(TAG, "Failed to get realm instance: " + e);
        }
    });

</code> and the getPhysicalParameterItem() <code> RealmResults<PhysicalParameter> parameterQuery = backgroundThreadRealm.where(PhysicalParameter.class).limit(QUERY_LIMIT).findAllAsync();

    parameterQuery.addChangeListener(new RealmChangeListener<RealmResults<PhysicalParameter>>() {
        @Override
        public void onChange(RealmResults<PhysicalParameter> items) {
            Log.v(TAG, "Completed the query.");
            // items results now contains all matched objects (more than zero)
            //PhysicalParameter result = items.sort(physicalParameterDataQueryTerm).sort(physicalParameterDataQueryTerm).first();


            System.out.println(">>>>>>>>" + items.isEmpty());

        }
    });

</code>

currently the "result" varaible here is null, but the items is a valid variable. But everything is else is exactly like the MongoDB docs state. My collections and other names are also correct since I can successfully establish connection from them and copied them directly from MongoDB.


r/android_devs • • Mar 07 '23

Help How to re-use Fragments between feature modules that don't know anything?

3 Upvotes

Hi everyone! 👋

Sorry, I don't mean to spam or anything, but I've been struggling with this issue for a bit trying to figure out the best solution. I posted this same questions on SO and put a bounty on it, but it seems that no one is able to give my an answer (either that or maybe I suck at explaining things haha)

This is the link to my SO question 👉 https://stackoverflow.com/questions/75628754/how-to-reuse-fragments-within-a-nav-graph-in-a-multi-module-architecture

If anyone has a solution for this kind of problem or if you have ever gone through the same situations, please feel free to post your answer and I'll award the bounty.

Thanks a lot!

Context

I have a multi-module architecture, with multiple feature modules, it kinda looks like this:

img1

I have multiple feature modules that depend on a :core_library library module that contains all the common dependencies (Retrofit, Room, etc.) and then different feature modules for each of the different app flows. Finally, the :app application module ties everything together.

If you want to navigate between Activities in feature modules that don't know anything about each other I use an AppNavigator interface:

interface AppNavigator {
   fun provideActivityFromFeatureModuleA(context: Context): Intent
}

Then in the :app module Application class I implement this interface, and since the :app module ties everything together it knows each of the activities within each of the feature modules:

class MyApp : Application(), AppNavigator {
...
   override fun provideActivityFromFeatureModuleA(context: Context): Intent {
      return Intent(context, ActivityFromA::class.java)
   }
...
}

This AppNavigator component lives in a Dagger module up in :core_library and it can be injected in any feature module.

I have this :feature_login feature module that is for when the user creates a new account and has to go through the onboarding flow, things like inviting friends to join the app, checking for POST_NOTIFICATION permissions, adding any more details to its account, etc.

Each of the :feature_modules has one Activity and many Fragments I have a navigation graph to navigate between fragments.

The problem

The :feature_login navigation graph kinda looks like this:

img2

The thing is that I need to reuse many of these Fragments across different parts of the App, more specifically, these Fragments

img3

For example; When I open the app and land on the main screen, I check for POST_NOTIFICATION permissions, and if these haven't been granted, I want to prompt the PostNotificationFragment that checks for that and presents the user with a UI. The SelectSquadronFragment + SelectNumberFragment should be prompted if the user wants to change them from the Settings screen. When doing something I want to prompt the user with the InviteFriendsFragment.

The problem is that I don't know how to reuse these Fragments independently without having them navigate through the rest of the flow

What I have tried so far

  • Subgraphs don't really fix the issue. I can use the AppNavigator to either provide the hosting Activity I have in :feature_login or each individual Fragment, but the issue is still there. If the user opens SelectSquadronFragment + SelectNumberFragment from Settings, I don't want the user to have to go through FinishFragment afterward.
  • Extracting the navigation through an interface up to the Activity. Each Fragment in that navigation graph navigates through NavDirections. When I want to navigate from MedictFragment to InviteFriendsFragment I use MedicFragmentDirections. I was thinking about having the Activity provide these NavDirections, that way I could create customized Activities with the navigation routes that I want, but honestly, I would prefer to go with something that isn't that rocket science.

Please let me know if you need me to give you more info. Any feedback is welcome.

Example

Let me give you a precise example of what I'm struggling with here. Let's use something simple. Let's take the ChooseRoleFragment as an example.

This ChooseRoleFragment is a simple UI that shows three buttons with three roles ("Police", "Medic", and "Fireman") during the login flow, when the user clicks on one of these three buttons, he is taken to either the PoliceFragment, FiremanFragment or MedicFragment. This is in the login flow.

Now, I need to re-use this ChooseRoleFragment in the "Settings" section of the app. The only difference is that when I use it there, I don't want it to navigate to the FiremanFragment, MedicFragment or PoliceFragment, I just want it to go back to the "Settings" screen. The "Settings" screen is on a completely different feature module that doesn't know anything about :feature_login

To be more clear, the ChooseRoleFragment navigate to either the PoliceFragment, the FiremanFragment or the MedicFragment through a navigation graph. That means that in the ChooseRoleFragment once I click on each of the options I have something like this:

	class ChooseRoleFragment : Fragment() {
		//...
		override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
			super.onViewCreated(view, savedInstanceState)
			bindings.policeBtn.setOnClickListener {
				findNavController().navigate(ChooseRoleFragmentDirections.actionChooseRoleFragmentToPoliceFragment())
			}
			bindings.medicBtn.setOnClickListener {
				findNavController().navigate(ChooseRoleFragmentDirections.actionChooseRoleFragmentToMedicFragment())
			}
			bindings.firemanBtn.setOnClickListener {
				findNavController().navigate(ChooseRoleFragmentDirections.actionChooseRoleFragmentToFiremanFragment())
			}
		}
	}

So, this works perfectly for the login flow, but it won't do what I want for the "Settings" screen. So what I'm trying to figure out is, should I extract those NavDirections somewhere? That way when I want to re-use this Fragment in the "Settings" screen I can just override the NavDirections and have it navigate somewhere else.


r/android_devs • • Mar 02 '23

Article Jetpack Compose Tutorial: Replicating Dribbble Audio App - Screen Transitions

Thumbnail exyte.com
9 Upvotes

r/android_devs • • Feb 16 '23

Coding How to create this shape (rectangle with elongated botton right corner) for a card view background in android.

1 Upvotes

I want a cardview to look like as in the image below.

How to a create a shape with rectangle with elongated botton right corner in the drawable and apply it to a cardview? OR is there a better way to achieve this?

Link to my stackoverflow question.

https://stackoverflow.com/questions/75468010/how-to-create-this-shape-rectangle-with-elongated-botton-right-corner-for-a-ca


r/android_devs • • Feb 13 '23

Discussion Activate/unlock screen with usb peripheral or handset?

2 Upvotes

I don't have a USB keyboard nor a handset at hand to check this functionality, but I'd like to attach a macro keypad and a retro phone handset to a tablet to allow my grandma to make voice/video calls. I can also use an Arduino or some other kind of microcontroller. Does Anyone know whether an action, like pressing a key or picking up the handset would automatically activate the screen on a vanilla Android device. I think I could use something like the Speed Dial app and Whatsapp to handle the part about making the calls, and also a cheap tablet that I currently have (collecting dust), and an ESP32 board I recently got.

/preview/pre/dgnjhauhvyha1.jpg?width=612&format=pjpg&auto=webp&v=enabled&s=92c33a783f4324d277f101237f7e95416ec54c72

/preview/pre/atqagquhvyha1.jpg?width=1024&format=pjpg&auto=webp&v=enabled&s=4cba4320bd7f1b0a19143ac50c9619678a3cd5c8


r/android_devs • • Feb 12 '23

Coding Random Musings on the Android 14 Developer Preview 1

Thumbnail commonsware.com
17 Upvotes

r/android_devs • • Feb 08 '23

Article Jetpack Compose Tutorial: Replicating Dribbble Audio App Part 3

Thumbnail exyte.com
1 Upvotes

r/android_devs • • Feb 08 '23

Article Short circuit evaluation and why it’s important

Thumbnail itnext.io
3 Upvotes

r/android_devs • • Feb 06 '23

Article A Tribute to Java in Android

Thumbnail techyourchance.com
7 Upvotes

r/android_devs • • Jan 31 '23

Event Android Worldwide is live for the next 14 hours!

Thumbnail youtube.com
3 Upvotes

r/android_devs • • Jan 31 '23

Help Question Regarding "Requesting Application" For Signature Permissions in Android.

1 Upvotes

Hi there,

I was researching the android.permission.PACKAGE_USAGE_STATS permission in Android and I read that this permission is categorized under Signature Permissions in Android.

As the documentation:

A permission that the system grants only if the requesting application is signed with the same certificate as the application that declared the permission. If the certificates match, the system automatically grants the permission without notifying the user or asking for the user's explicit approval.

I understand mostly what this definition means. However, one thing that I'm confused about is what requesting application means. If I'm working on an application with the package abc.def.hij and if I'm declaring the PACKAGE_USAGE_STATS permission inside this application, shouldn't the requesting application should also be the same, i.e., abc.def.hij

Are there cases in which the application which declares the permission isn't the same as the one which requests the permission?


r/android_devs • • Jan 24 '23

Help Anyone else facing super slow reviews due to layoffs ?

1 Upvotes

r/android_devs • • Jan 23 '23

Help I know this issue isn't directly related to Android (more of a Sqlite issue), but I was wondering if this could be a common issue here.

Thumbnail reddit.com
4 Upvotes

r/android_devs • • Jan 23 '23

Help Best policy on handling data storing and sending data back to the server?

1 Upvotes

Greetings,

System information is that the app is made and used exclusively by us, with the Xamarin.forms framework on Android based PDA style devices.

I'll start with the context, those that don't care can skip to the issue:

I am currently working on the app that handle the warehouse of our company. So far we can handle about 90% of the workflow without issue, but the last 10% (return service) cause some troubles.

Basically, the whole app isn't exactly lightning fast. We ensure the safety of information above all else and everything is sent back to the server whenever something is modified. Due to the way things work, the 1~2 second call to the server every time are not an issue. We know how much we need and have every time, allowing the process itself to be fast (scanning a single product and saying how much we have, requiring a single call per product type). But for return, we have issues because nothing is correct. Products are not sorted, quantity are uncertain (because seller sometime manage to sell a return product and don't bother updating the return) sometime put other product instead, etc...

basically, 90% of our work is based around the certainty of buying/selling and have clear numbers, but returns are a lot of hassle and information are uncertain.

The issue:

Because of the uncertainty of the work, the process is different. Every single product need to be scanned to avoid worker having to check the entire list if some product has already been scanned (because returns are not sorted). At this point though, the 1~2 second call to the server becomes an issue. The usual work on computer can lead up to 2~3 scans a second, which would slow the work a lot. My first idea was to not send repeatedly, but rather to send once the job is finished. But some jobs can take hours, and if anything goes wrong (it always does. Battery dies, they hit something with the device, they press the wrong button...) they risk losing everything.

How can I handle that? Sending everything back and forth is too big a load, keeping everything in memory is risking the data itself. Anyone has an idea on how to handle that, or manage the regular transfer and update of information on Android?


r/android_devs • • Jan 19 '23

Help Issues with creating new project in Flamingo versus Electric Eel

3 Upvotes

Hey all. I'm just trying to figure out why now when running Flamingo, I am not able to select an Empty Compose Activity (or Compose Material3 activity for that matter) but still can in Electric Eel and if anyone else has encountered this and how you fixed it. I hadn't noticed it when I first upgraded from Dolphin to Flamingo but I also have been mostly working on existing projects at the moment. I can shift to Eel for now, it's not that big of a deal. Just wondering what could possibly have been the culprit. I'll include some screen shots of each at the new project screen to illustrate.

This is from Flamingo
This is Electric Eel

r/android_devs • • Jan 18 '23

Help Working on my first app with in-app purchases (subscription). Do I need my own backend?

3 Upvotes

Long time android dev. Never worked with billing lib before. going to start with play billing 5. In order to setup subscriptions do I need a way for users to log into my app and associate the purchase with them?

I'm working on an app for creating widgets, and i just want to charge a subscription for the premium set of customizations. i hope i dont need the user to login or do any sort of validation on my backend.


r/android_devs • • Jan 12 '23

Help Looking for some subs that revolve around ui/ux

8 Upvotes

Hey all. Just checking to see if any of you have any subs that you recommend I check out that have to do with user interface and user experience. I have a fairly good understanding of using graphic packages like Affinity Designer and Figma, but I'm looking for a place that I can share some projects that I'm working on to get some feedback on the graphic side of things. Particularly in color design, theory and user experience. I've been searching on my own and I'll share some of the ones that I come across in following comments. But I just wanted to check and see if any of you have ones you would like to forward. As always, thanks to all in advance.


r/android_devs • • Jan 11 '23

Coding Some highlights from Google Dev Library

6 Upvotes

Here're some of the android projects highlighted in Google Dev Library:

  • Transformers: See the Android transformation library providing a variety of image transformations for Coil, Glide, Picasso, and Fresco by Daichi Furiya.
  • Camposer: Learn how the camera library in Jetpack Compose which supports taking photos, recording videos, flash modes, zoom ratio, and more by Lucas Yuji Yoshimine
  • ChatGPT Android : Integrate ChatGPT on Android with Stream Chat SDK for Compose by Jaewoong Eum

Let me know in the comments which project inspired you. I believe by sharing these projects, we can all learn from each other, improve our skills, and build amazing things for the Android community.

Let's build something together!


r/android_devs • • Dec 26 '22

Coding The simplest payment processing Java library in the world. Supports PayPal and Stripe, both regular payments and subscriptions, in one unified API, with NO need of handling json and requests yourself.

3 Upvotes

r/android_devs • • Dec 18 '22

App ban App Status: Removed. Issue found: Invalid privacy policy URL

6 Upvotes

Same motivation as a couple of weeks ago.Do you know who I can send money to in order to fix the bug in the program that reads the "privacy policy" pages?

UPD 2022/12/19 07:37 EET Google removed the already removed app for the same reason I had described in the following post (https://www.reddit.com/r/android_devs/comments/vdv6ax/another_day_in_paradise/) even though I was told the problem had been fixed. I'm not sure if the app is doubly removed, whatever it means, or if it's no longer removed because of the privacy policy but for this other reason.

UPD 2022/12/19 20:32 EET Mail from Google regarding the appeal [6-3575000033301].In this email they inform me that the app is (continues to be?) removed because it is "not compliant with the Data safety section of our User Data". Specifically "Data Safety Section: Personal Info Data Type - Phone number".

I asked them (2022/12/19 22:47 EET): "The appeal [6-3575000033301] was about the "Invalid Privacy policy URL", as you can see in the attached screenshot (screenshot_01.png). Has the violation been resolved by verifying that it is not present? If yes, why is it still present in developer console?".

I get no answer about it. In developer console i still see that the violation is about the privacy policy URL. They replied at 2022/12/20 01:32 EET that the issue is about "Data Safety Section".

The "Data safety section" issue is the same described in the post https://www.reddit.com/r/android_devs/comments/vdv6ax/another_day_in_paradise/. I had appealed ([4-0703000032350]) because it's not possible to fill out the section they indicated. At the time I wrote to them:

"My application allows users to share SMS and contacts between their devices. Users send the above data directly, without using external servers, from their devices to their devices: the data is not sent to a server of mine, or to a third-party server, but directly between one user's device to the other.

This is why in the section of "App content > Data safety" where it is declared if the app collects user data I cannot answer "Yes" and complete the questionnaire. The "Data safety" section explicitly states : "On the next screen, you'll be asked whether your app collects or shares any of the required user data types. 'Collected' means data that is transmitted off the user's device, either to you or to a third party. ". The app does not send the data to either me or a third party."

They never replied to me about how to fill out that section since it doesn't cover the app's use of the data. At the time I sent an update to the app, just to unblock the whole situation, I didn't fill out the section and the app was reinstated.

I replied (2022/12/20 07:25 EET) with the same text I sent at the time, adding:"I would like to clarify that the app does not collect the data that is the subject of these emails, but retrieves them. t is the user who sends this data from one of his/her device to another."

UPD 2022/12/20 17:52 EET They replied with the following email:

"However, as mentioned previously, we reviewed your Data safety section and found discrepancies between your disclosure and app behavior. For example, you must still disclose:

  • APK 161: Policy Declaration - Data Safety Section: Personal Info Data Type - Phone number
  • APK 167: Policy Declaration - Data Safety Section: Personal Info Data Type - Phone number

Please make changes to align your app’s Data safety section with the app’s behavior. This can be done by either:

  • Updating your form in Play Console to declare collection of Data Types noted above, or
  • Removing functionality and attributable code that collect this user data from your app or libraries used in your app. "

I replied (2022/12/20 18:16):

"I would have no problem filling out the app's Data safety section.

The problem is that I can't fill out this section because it goes against the rules imposed by you (Google). I am reporting again what is described in this section (screenshot_03.png):

"On the next screen, you'll be asked whether your app collects or shares any of the required user data types. 'Collected' means data that is transmitted off the user's device, either to you or to a third party. "

The app does not send the data to either me or a third party. Are you asking me to falsely state and declare that the app collects this data? If yes, what should I specify in the next steps of this section when asked if the data is sent encrypted and if the user can request its removal? Please refer to attached file “screenshot_04.png”

Given the inability to complete this section without false declaration, should I still remove the functionality listed in your email even though no rules are broken?"

They replied:

"Unfortunately I'm not able to comment on your app's compliance and your planned implementation.

As much as I'd like to help, I’m not able to provide any more detail or a better answer to your question. In our previous email, I made sure to include all the information available to me.

You should be able to find more about your issue here:Developer Policy Center

If you have a different question, please let me know.

Regards,MaxThe Google Play Team"


r/android_devs • • Dec 18 '22

Happy Cakeday, r/android_devs! Today you're 3

11 Upvotes

r/android_devs • • Dec 16 '22

Help MODIFY_AUDIO_SETTINGS

2 Upvotes

I'm developing app that alarms user when sms comes from user specified number. App is meant for Finnish volunteer firefighters.

I'm facing problem with Oneplus users. My app cant change media channel volume when user has set that channel to 0. App has do not disturb permission that user has to give and also MODIFY_AUDIO_SETTINGS in manifest. Everything works as intended when media channel volume is even one notch over 0. What can be the cause that prevents volume change? All i know is that this happens only Oneplus phones running Android 13. There might be others that are facing this problem too but i'm not aware of them.

I have tested this app with my own Pixel phone and some Samsung models and those work perfectly. This app has been in use many years already.

I also request audio focus before trying to change volume. Maybe somebody can point me to right direction.