Create products Google play and in-app billing
Asked Answered
J

9

4

I'm doing an app that have a RecyclerView with many items (some of them are fixed and are by default for everyone), but I'd like to make some of them "not free", means that you have to pay (if possible using Google Play) to unlock those items, can you guide to me how do I figure out this scenario? How do I know that the user has items that has paid for them, and when I know that he paid for them.

I do not want to use a Database because I only need two tables I guess, for example;

TABLE USER

Where I'll will store an id (I guess it will be the email if I finally create a Login GMAIL,FACEBOOK)

TABLE BOX

Where I'll put the BOX that are free and not free and as a Foreign Key I'll put the user.id to get references what BOX's he/she owns.

Right?

But, If I have to choose this way, because if the user pays for a box on my APP and then he want to use it in other device, it won't have the box unless he logs in on the new device, correct? So, If I had had to choose a Database and Hosting to do it, what will be your recommendation? (From start, I won't have too much data, so I don't need the best one, I only want to communicate with my Android app).

I hope it's clear now, otherwise, put a comment and I'll try to explain it better.

EDIT

Reading the answers I see that I can use Firebase, as @Haris Qureshi said, well what I'm confused is :

How do I store the product? I mean, I've read and watched videos on YouTube and I have to do it in Console of Google Play but do I need to send the .apk and then add the products?

If I do not need to create a Database, and I have to end up using Firebase, using the Storage stuff from Firebase will store my products? But I can assign it as a PURCHASED, PAID, AVAILABLE? Also I'll need to integrate the Authentication, right? Because he said that once you buy a product, it stores the gmail that has paid for it and you know who paid and not paid, so if he uses another device it will have the same products boughts (if he still with the same gmail).

The products can be dynamics? I mean, you can create for example an "event" and put that product only for x days, as I'll need an Image to show the product, I mean the product will have also an Image to show on the UI, but I see in the Console of Google Play I only can create an id for the product and if I'd have to create it dynamic I could do that, because I have to store the Images on /res/mipmap right?

EDIT2

What I need is what @Alex Mamo told to me :

You cannot store images in your Firebase database. You need to store them in Firebase Storage. In Firebase database you need to store only the urls of those images.

The flow is like this: upload image to Firebase Storage -> get the url of the corresponding image (when uploading) -> store the url in Firebase Database -> use the reference to display the image

I've created the products on google console developer, and I have to connect my app to in-app billing

Jammie answered 12/11, 2017 at 17:59 Comment(26)
do you try use firebase?Waterfowl
Ya i have read about this, but this is for login, right?Absentminded
In general I think you should implement In-App Billing. This will allow you to more easily manage payment and also to retrieve the list of purchased items. In general I guess the list of "products" should in any case come from backend. Firebase is a solution you can setup in few time, but of course it's important to know if you have constraints on your architecture (e.g. you cannot include new libraries in your app, you want to use a db solution allowing to eventually migrate to another cloud service).Odalisque
@thetonrifles So, your guess is to use a basic system as create a db, create an API and do stuff with that?Absentminded
@Skizo-ozᴉʞS Yep. Firebase can be a solution or just something to use for prototyping quickly. In general you also need to think about your vision. Firebase means using a specific storage that you can have just there... ok, you can export your data but at the same time Firebase automatically creates some API for you and if you migrate in most cases you need to reimplement everything. I think you can start with Firebase for understanding if backend with data is what you really want / need.Odalisque
@thetonrifles I'll check it out, did you work with Firebase? or have any knowledge about it?Absentminded
@Skizo-ozᴉʞS mostly worked exactly for these kind of stuffs... prototyping :) ... it's easy to create your storage and probably the best approach is to define the json you want and import there. Services are automatically created but by default require authentication / authorization. There's an Android library for simplifying all these stuffs, but if you want just to call the api and receive a json without Firebase library I suggest you just to disable the authentication / authorization part and just play with data in this phase.Odalisque
@thetonrifles Haris said that I do not need a login page, with Firebase I can save who bought this stuff, and he can use the the same app in other device and he still with the items boughts. Another thing is, do I have to upload the apk, to create an item?Absentminded
@Skizo-ozᴉʞS you don't maybe need a login page but by default the data stored in Firebase are not public. The app should be authorized to access the data (it's not strictly a matter of user authentication but for the app). The whole flow is managed by the Firebase Android SDK but maybe you don't want to include it in your app. I'm quite sure you need your apk to be on Play Store. Keep in mind by the way that you can distribute it to a restricted set of people using for example Beta channel. I can check this.Odalisque
@Skizo-ozᴉʞS in general what I think is that the question is quite broad and focus on Firebase might be misleading. Firebase is a possible backend to use and could be a fast way for prototyping what you need. The solution should be ideally designed regardless of cloud service you will use.Odalisque
@Skizo-ozᴉʞS was you able at the end to find a solution / make some tests?Odalisque
@thetonrifles no I was not, I did not find a good video/tutorial to start with, I mean, to create the "db" know if I can know if user has paid or not, if user can be stored on that DB, and the less important is to get all of those products, the main is to store it and know if user that pays with gmail acc, can get the same products on differents devicesAbsentminded
I understand that you have some items listed in recycler view by the help of an adapter, and you want to check if an item is purchased according to some stored state. The best approach for you is to store states in a database and retrieve accordingly. Comments suggested you to use Firebase, I suggest the same thing. Do you have any idea about how to use firebase ?Haskins
@svi.data No, I'd like to get an example or a tutorial to create products and get them from the buyer gmail accAbsentminded
What is the data source of your recycler view, from where do you populate it ? and with what ?Haskins
@svi.data still don't have any data, frist I need to create the products on Firebase I guess and then populate it into my listAbsentminded
okay I am asking to understand your question, I want to know what you are able to do and what you are not. first of all do you know how to apply the in app billing before we worry about firebase?Haskins
@svi.data what do you mean? I think I've implemented it allready, but I don't remember now, how do I check it?Absentminded
It seems like you're going to need to use Firebase Authentication, Database and Storage modules together with Google Play Store in-app purchases. However, your question is quite broad, so you might want to start by creating a plan of what you want your app to achieve and then you can work out what your requirements would be. For example: you'd need a database to store details about a product, a storage bucket to store images for a product, authentication to separate (and secure) different user's choices or interactions, and in-app purchases to allow to you charge for certain products.Warble
@Warble Yes, that's what I wantAbsentminded
@Skizo-ozᴉʞS Ok, so have you started to develop an app for this or are you starting this with a clean slate? As it currently stands the question may be too broad to give a complete & useful answer without collaboratively working with you to create the app. I think this is why you've struggled to receive an answer that you're happy with thus far. I'm happy to try and help, but you may need to narrow it down to a specific problem. Or do you just need some guidance on linking all of the required modules (auth, database, storage, purchases) together?Warble
@Warble I understand you, yes, my app is done, what I'd like to know is, do I have to integrate a login (with firebase) to know what user has paid or not? Also, I'd like to create products for example with (name, image, price, state(free,notFree)), and then once I have those products created I'd like to buy it from my app. But I'm not looking for example this is the documentantion from auth, this from database, etc... I'm looking for someone who has faced this issue before and can do an example (not necessary working) of this.Absentminded
it's called FireStore (beta) firebase.google.com/docs/firestore ...while I do not understand the requirement for Firebase, at all... simply because Google Play already indicates which product had been purchased; adding some more complexity won't change that (I actually have a RecyclerView, but with subscriptions - while the source of data does not matter, while the SKU exists on the store).Mcferren
Not getting you @MartinZeitlerAbsentminded
@Skizo-ozᴉʞS the products loaded do not matter to the store, simply because the store might not know them. if you want to add them dynamically, you insert them through the API (and then into Firebase, to make them appear): developers.google.com/android-publisher/api-ref/inappproductsMcferren
@MartinZeitler do you have experience of it? If so, feel free to put an answer....Absentminded
S
1

Regarding firebase you have to do this:

First Firebase is a nosql database so it uses JSON to add values to the database. Also Firebase is a service that has realtime database,storage,cloud functions,authentication.So its your best option.

Now Regarding the way to store, you can do this:

In realtime Database

{
  Users:{
    push_id_here{
          name:peter
          password:a_password_here
          email: email_here
              }
    push_id_here{
          name:john
          password:a_pass_here
          email: email_here
       }
     }

     Box:{
        push_id_here{
              productname: productx
              availability: available
              image: image_url_here
                     }
         push_id_here1{
                 productname: producty
                 availability:free
                 image: image_url_here
                     }
             }

First yes authenticate the user, regarding image send it to storage and add it in database, this is probably your best option.

Push_id_here: is basically a random id generated for each node, its like a primary key.

You do it like this:

DatabaseReference ref=getInstance().getReference().child("Users").push();

the Push() will create a random id. The above is the realtime database, to create it you have to connect to firebase in the android studio.

In android studio go to Tools>Firebase>realtime database and connect to database.

to send data to database you can do this:

 DatabaseReference ref=getInstance().getReference().child("Users").push();
 ref.child("name").setValue(name) //name that you can get from `Editext`
 ref.child("email").setValue(email)

Regarding authenticate, you have to also connect to firebase authenticate, go to Tools>Firebase> firebase authenticate and enable.

Authentication means it will be authenticated in firebase, usually it authenticate email and password, there is also phone authentication. To authenticate you can add this in your code:

firebaseAuth.signInWithEmailAndPassword(email,password)
        .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {


                if(task.isSuccessful()){
                    //code here
                }else{
                    Log.e("ERROR",task.getException().toString());
                    Toast.makeText(LoginActivity.this, task.getException().getMessage(),Toast.LENGTH_LONG).show();
                }
            }
        });

example:

Sample db

In this db Klx0N4pxsBHGVkhYuY0 is a push id and channels is like Users in the JSON I gave

Stilwell answered 21/11, 2017 at 13:43 Comment(14)
tell me what else you need @Skizo-ozᴉʞSStilwell
Thanks for your answer @Peter Haddad, but let me see... what's push_id_here? This is what I have to send from the APP? How do I create the db itself, and what about the products on Google Play? And if I need authenticate user, how do I authenticate from my app? Other guys said that buying an item it's like loggin, because it stores the email, right?Absentminded
@Skizo-ozᴉʞS check edit please, the above JSON is the db in firebase its not like sql , its nosql, authentication is a service provided by firebase, so it will authenticate your users, about authenticate firebase.google.com/docs/authStilwell
but what's that name push_id_here?Absentminded
@Skizo-ozᴉʞS oh nothing its random id, generated by firebase we cant know its name.. but we can retrieve it from the database doing this String key=ref.getKey(); check image in answerStilwell
@Skizo-ozᴉʞS here in the image(from google) chatchat-15e82 is a root node, then channels is like Users node and its child of root node the push ids are below, these random ids are like primary key to identify the name:values inside of itStilwell
But I mean I do not know how many users I'll have, I have to send it from my app, right?Absentminded
yes the push id is made through this code push(), its just to seperate records like primary key, so yes from the code, everytime a user is created a push id is done for him also @Skizo-ozᴉʞSStilwell
But I have to create the db? first?Absentminded
And this name and email, from where I get? Do I have to implement the Authentication aswell?Absentminded
You create the db from your code and email and password are the text in the edit text.. Then you authenticate themStilwell
I do not need to sign in with Gmail?Absentminded
Noo it depends what sign in method you choose when authenticing, there is email and password/google sign in / phone number/githubStilwell
Let us continue this discussion in chat.Absentminded
H
3

There are good answers here but because you have asked me, i'll try to give you some more details. The best practice for Implementing In-app Billing is the official documentation. Please se below my my answer for some of your questions.

As many other users have advised you, so do I, use Firebase as your database for your app. It's a NoSQL database and it's very easy to use.

How do you store the product?

Please see below a database structure that i recomand you to use for your app.

Firebase-root
    |
    --- users
    |     |
    |     --- uid1
    |          |
    |          --- //user details (name, age, address, email and so on)
    |          |
    |          --- products
    |                |
    |                --- productId1 : true
    |                |
    |                --- productId2 : true
    |
    --- products
    |     |
    |     --- productId1
    |     |     |
    |     |     --- productName: "Apples"
    |     |     |
    |     |     --- price: 11
    |           |
    |           |
    |           --- users
    |                |
    |                --- uid1: true
    |                |
    |                --- uid2: true
    |
    --- purchasedProducts
         |      |
         |      --- uid1
         |           |
         |           --- productId1: true
         |           |
         |           --- productId2: true
         |
         --- paidProducts
         |      |
         |      --- uid2
         |           |
         |           --- productId3: true
         |
         --- availableProducts
         |      |
         |      --- uid3
         |           |
         |           --- productId4: true

Using this database structure you can query your database for:

  1. All products (purchased, paid or available) that belong to a single user
  2. All users that have bought a particular product
  3. All purchased products that belong to a single user
  4. All paid products that belong to a single user
  5. All available products that belong to a single user

Every time a product is bought, you only need to move the product to the coresponding category. As AL. said, you could set your app to get the products by using the Firebase SDK. That would not be a problem.

This is called in Firebase denormalization is very normal with the Firebase Database. For this, i recomand see this video. If you want something more complex, i recomand you read this post, Structuring your Firebase Data correctly for a Complex App.

Using the Storage stuff from Firebase will store my products?

Yes, you can use Firebase Cloud Storage which is built for app developers who need to store and serve user-generated content, such as photos or videos.

Also I'll need to integrate the Authentication, right?

Yes, you need to use Firebase Authentication because you need to know the identity of a user. Knowing a user's identity allows an app to securely save user data in the cloud and provide the same personalized experience across all of the user's devices. Firebase Authentication provides backend services, easy-to-use SDKs, and ready-made UI libraries to authenticate users to your app. It supports authentication using passwords, phone numbers, popular federated identity providers like Google, Facebook and Twitter, and more.

The products can be dynamics? I mean, you can create for example an "event" and put that product only for x days?

Yes, you can do that using Cloud Functions For Firebase which lets you automatically run backend code in response to events triggered by Firebase features and HTTPS requests. Your code is stored in Google's cloud and runs in a managed environment. There's no need to manage and scale your own servers.

This is how you can query the database to display the product name and the price of all products.

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference yourRef = rootRef.child("products");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String productName = ds.child("productName").getValue(String.class);
            double price = ds.child("price").getValue(Double.class);
            Log.d("TAG", productName + price);
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
yourRef.addListenerForSingleValueEvent(eventListener);

And this how you can query your database to see all purchasedProducts that belong to a specific user:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("purchasedProducts").child("uid1");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String productKey = ds.getKey();
            Log.d("TAG", productKey);
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
uidRef.addListenerForSingleValueEvent(eventListener);
Hake answered 21/11, 2017 at 16:5 Comment(11)
Thanks for your answer @Alex Mamo, can you put an example to query all products for example? And by the way, do I have to create the products on my google play console? And then add those products on firebase database?Absentminded
Thanks, but if I do not know what child is? I mean your .child("uid1")Absentminded
Sure, please see my updated answer. In the same way you can query the database for the other values. And yes, indeed, but first you need to add them to your Firebase database and after that to Google Play Console.Hake
To get the uid you need to use this two lines of code: FirebaseUser firebaseUser = firebaseAuth.getCurrentUser(); and String uid = firebaseUser.getUid();. that's it!Hake
How do I can connect my products from google play console to put them as a products?Absentminded
So having the uid, you can use it in your DatabaseReference.Hake
I mean, I have a products added on my google console developer (what I want to user buy), so I'd like to get them and insert them to products, is what I have to do?Absentminded
First i suggest you read the offical doc for a better understanding. It's very well explained. Here is also a super-short video walkthrough on adding an in-app purchase to Google Play's Developer Console. It's a very simple operation.Hake
Let us continue this discussion in chat.Absentminded
hello I have one little question, if I want a simple game for instance user (to store users) and I want to have different levels and I want to store like a ranking by levels how would be the structure? I mean, I've thought about have an user table, then a lvl table and then I'm stuck on there, I don't know how to link them to make a query for instance all ranking for all users by level and do it okAbsentminded
This is basically another question. In order to follow the rules of this comunity, please post another fresh question, so me and other users can help you.Hake
S
2

For each row of the RecyclerView define a TextView to indicate the three status (i.e. :- "Free" ,"Pay", "PAID") of this particular item on the side of the row. You can make the TextView with the status of "Pay" clickable dynamically if you want the user navigate to purchase screen.

Now define an Adapter for the RecyclerView and within that have an enum with three status (i.e. :- "FREE","NOT_PAID", "PAID") to indicate the status of the current item and a property to hold the enum value. When the Activity starts fill up that property (enum type) according to the back-end data for particular items dynamically. Based on the value you can change the status of the TextView (i.e. :- "Free" ,"Pay", "PAID") dynamically. That logic also should goes on the Adapter.

Hope you can have the implementation based on the above suggestion. I can provide an implementation if you need further help.

Subnormal answered 12/11, 2017 at 18:52 Comment(5)
Ya, that I know but I'm more focused on the question that how to figure out if user has paid or not, do I have to create a DB or something? How do I create an item payable on my adapter?Absentminded
Yes, exactly. You have to go to a DB option to save payment status of the particular item. You have to decouple the payable logic from the adapter I'd say. As my answer suggested, once the user clicks on the status TextView you can provide a separate screen (e.g. :- pop up dialog) to make the transaction and according to the result (paid or not) you can update the particular item row in the RecyclerView and at the same time update the DB.Subnormal
Could you make an skeleton (not code) a little example with links and examples please?Absentminded
What do you mean by skeleton with links and example? I can provide a rough implementation if you need.Subnormal
Like a pseudocode, but if you know how to manage this (NOT ONLY THE RECYCLER VIEW STUFF), go ahead, make an example and I'll check it out, I'm interested aswell to what db to use, how to make an item payable, etc... I'll start a bounty whenever I canAbsentminded
A
2

Add all your products in google play store as in app purchase products.

Pseudocode

  1. Create a class say Products having data members as productID, productType, price, description, tag, etc.

  2. Query for items available for purchase and save them in your Products with tag AVAILABLE.

  3. Query for purchased items and save them with tag PURCHASED.

  4. Use Firebase to get free products and store them with tag FREE.

  5. Populate your RecyclerView with given ArrayList and show your TextView accordingly in your adapter.

Google stores all purchase history but if you want to add more products you need to add products in google console as well publish new android version.

For more details see this example.

Amargo answered 16/11, 2017 at 14:12 Comment(8)
Thanks for answering, but do I have to create a DB or something? I mean, I have to create a Login on my App, right? Because if one user wants to use the same app in other device the stuff that he/she brought it won't be visible, so that's my problem aswell, I want to know if I have to create a DB or with Firebase it's okay.Absentminded
I don't think user will have to login as user will download your app from play store and will attach with user email/ID.Amargo
Yes, but if he buy something and then he swaps the device and install it on new device it will have the same products?Absentminded
Yeah if user will download the app from store using same email then it should have all the detailsAmargo
How do I have to do that, with firebase? Do you have an example (simple)?Absentminded
I don't have any example to give you but you can find many examples, just google itAmargo
I thought you know something, but yes, I'll search it and I'll let you know, b utility I have to ensure that I do not have to create a login and stuff only with firebase it's OKAbsentminded
Do I need this ones? Set up user authentication with Authentication. Store user info with Realtime Database or blob data with Cloud Storage.Absentminded
C
1

Saw your comment from here. I paid attention to the edited part. Here's my two cents:

How do I store the product? I mean, I've read and watched videos on YouTube and I have to do it in Console of Google Play but do I need to send the .apk and then add the products?

You could store it directly from the Firebase Console. Afterwards, you could set your app to get the products by using the Firebase SDK. If you already have the app uploaded on Google Play, I think you just need to upload the updated APK that could perform the data retrieval (using the Firebase SDK).

If I do not need to create a Database, and I have to end up using Firebase, using the Storage stuff from Firebase will store my products? But I can assign it as a PURCHASED, PAID, AVAILABLE? Also I'll need to integrate the Authentication, right?

If I understand your requirement correctly, you would most certainly need a database. It would be easier for you to organize the products that way. From the (Firebase) Database itself, you could also put the user details there, set if they are already PAID or just using the app for FREE, this way, it'd be easier to check which products the user could access or not.

Firebase Database would work on it's own without Firebase Auth, however, it is strongly suggested to use it together, to make use of the Security Rules.

The products can be dynamics? I mean, you can create for example an "event" and put that product only for x days, as I'll need an Image to show the product, I mean the product will have also an Image to show on the UI, but I see in the Console of Google Play I only can create an id for the product and if I'd have to create it dynamic I could do that, because I have to store the Images on /res/mipmap right?

It depends on how you implement it, but yes it is most certainly possible to create a dynamic product. You could have the product details in the DB and the image file in Cloud Storage for Firebase. You could make this dynamic by adding something like an expirationDate parameter in the product details, and when retrieving the data in your app, you could simply check if it's already expired or not.

Chloroprene answered 17/11, 2017 at 9:27 Comment(11)
With all that said. Your post seems quite broad. I would suggest splitting the questions and tackling them one by one ( divide and conquer :) ). Cheers!Chloroprene
I know it's quite broad... but I'd like to read a simple solution to how to, to help me out to start with this, I allready have the app made, I have not uploaded it on Google Console Developer I only have to add this, the simple that I want is : user opens the app(don't know if I need to create a login to store who buy and who don't), user can buy a box for example, pays for it, and then use it ALWAYS.Absentminded
So, if you know something about that, you could give me some links (not documentation) any links to how to, I mean, I followed the step by step understanding how to integrate firebase on Android Studio, I'd like the step by step if possible.Absentminded
@ Skizo-ozᴉʞS Sorry. I don't know any step-by-step guides that stick to your use-case.Chloroprene
But you know what should I start doing first? I've created my firebase acc, I implemented it on my Android app, I'm stuck now when I have to create the products and get it form dbAbsentminded
I have an idea, but like I mentioned, it would be too broad to explain it all. The thing is you just have to save the product details in your Firebase DB and simply get them as needed. You'd basically just do checks on the product availability, depending on the user's status and the product's requirements.Chloroprene
Yes, but do you have any example to how to store the products on Firebase db?Absentminded
These products that you're referring to. Aren't they just data that you could put in? Based from the previous answers and comments I've read, I got the sense that it was just data that you could put in a database. The Firebase Database Console is pretty straightforward, you could type in the details as needed. All you need is a good DB structure.Chloroprene
Yes, I mean for example, imagine I have a box on my app normal box that comes from default are wood, then I want to buy Silver,Gold,Platinum, etc... you know what I mean? I'd like to store for example the image of that box, and the name nothing elseAbsentminded
For a quick product DB structure, based from what you gave, I think it should go like thisChloroprene
Ya, that's nice, but if you know about Firebase, you know if I can avoid creating an user table to know who paid or not paid? I'll wait for more answers but i'll count with your answer :)Absentminded
L
1

If user swaps his mobile and login in Google Play Store with the same email he used to purchase the product on the previous mobile, then the product he purchased will be visible automatically on the new mobile.

Lianna answered 21/11, 2017 at 7:47 Comment(3)
That's cool, that's what I wanted to know. Using firebase could be an option? or you know other option to do that?Absentminded
@Skizo-ozᴉʞS Sorry, but I don't know the other option, but this is the simplest one.Lianna
Put an example if you wantAbsentminded
H
1

First you need to know how to create products in your google play developer console. You can check this.

You need to upload your APK but not necessarily publish it. Once you do that along with the steps mentioned in the link I provided you will be able to create products like (wood, silver, iron) give them ids, and retrieve them whenever you need to allow a purchase (and this will be the part where firebase will help us do that).

First learn how to make your in app products and how to give them details and ids.

next I will help you to make your database in firebase and know when to allow a purchase.

UPDATE

I will assume that you already linked your app to firebase, if not then you should find out how to do it.

step 1

a) make sure to go to authentication in your firebase console and enable (sign in with email and password).

b)add the following dependencies:

  compile 'com.google.firebase:firebase-auth:11.0.2'
  compile 'com.google.firebase:firebase-database:11.0.2'

STEP 2

create your register activity call it (RegisterActivity) , for simplicity add a button (called register) and two edittext fields (call them edit1 and edit2).

now we register a user like that:

    private String email;
    private String password;
    private FirebaseAuth mauth;

     //on create
    mauth=FirebaseAuth().getInstance();


    //on click of register button 

     //get what ever was typed in edit text fields and store them like that
     email=edit1.getText().toString();
     password=edit2.getText().toString();

     //create user like that 

      math.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>(){

           @Override
           public void onComplete(@NonNull Task< AuthResult> task){
             //on complete store users in database
             if(task.isSuccessful()){ 
              //get the user uid
               FirebaseUser user=FirebaseAuth.getInstance().getCurrentUser();
               String uid=user.getUid();

                //create a reference called my users in database
                DatabaseReference users=FirebaseDatabase.getInstance().getReference().child("my_users");

                 users.child(uid).setValue("user");//you can attach on complete here and if task successful go to main activity.


             }

            }

       });

Step 3

Now you can make a login activity call it (LoginActivity) also it will 1 login button and 2 edited fields. And you login like that

       private String email;
       private String password;
       private FirebaseAuth mauth;

         //on create
mauth=FirebaseAuth().getInstance();


       //on click login

         math.signInUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>(){

       @Override
       public void onComplete(@NonNull Task< AuthResult> task){
         //on complete store users in database
         if(task.isSuccessful()){ 
          //get the user uid
           FirebaseUser user=FirebaseAuth.getInstance().getCurrentUser();
           String uid=user.getUid();

            if(user!=null){
               //this means your user is registered so make intent to login activity
             }

         }

        }

   });

note: always in login or register activity get the user like I did and check if he/she is null and accordingly pass the user to either login or register.

step 4

(so until now you are able to create users and store their ids in database).

now create an activity having a recycler view displaying your items like (wood, iron, silver....) or whatever and here is the trick (keep in mind that in this activity the user has already signed in to your app).

the trick: now you listen to when user clicks an item and you listen to a node called (wood) or (iron) or (silver) and if these nodes have the current user id then the user already purchased and if not then the user didn't purchase(this is where you make a pop up of the in app purchase...)

here is how to go about this:

           //in the activity of your listed items
            private FirebaseAuth mauth;
            private String currentuser:

            //on create

            mauth=FirebaseAuth().getInstance();
            //store the id of the current logged in user
            currentuser=mauth.getCurrentUser().getUid();

           //on click of an item (wood or  silver or  iron ....)

           //I will do the wood case and you do same for others

           //on click of wood item 

            DatabaseReference wood=FirebaseDatabase.getInstance().getReference().child("Wood");

             //check if user is inside wood

              wood.addListenerForSingleValueEvent(new ValueEventListener(){

                @Override
                public void onDataChange(DataSnapShot datasnapshot){

                     //inside here you check if user is in wood
                      if(datasnapshot.hasChild(currentuser)){

                         //this means user purchased the wood item
                       }else{


                        //user didn't purchase a wood item

                        //handle payment 
                        //after payment of wood is completed

                        //store user in wood node

                  DatabaseReference wood=FirebaseDatabase.getInstance().getReference().child("Wood");

         wood.child(currentuser).setValue("purchased");




                       }

                   }

               });
Haskins answered 21/11, 2017 at 10:50 Comment(9)
okay so you are saying that you implemented the in app products?Haskins
If you don't know how to create the in app products that are needed to be purchased please follow the link in my answer. It provides step by step tutorial to make in app products and retrieve them when needed.Haskins
Bro, I allready check how to create the products, it's quite easy to follow the step by step from the video, but how do I use firebase with this?Absentminded
okay I will help you, but you should know that you must register your users.Haskins
its the only wayHaskins
Like sing in with gmail? buying the product it's not enough? No problem... well I'm glad you cna help me out on this, if we get it today at least an skeleton I'll give you the bounty :DAbsentminded
Its not about any bounty, just glad if I can help you.Haskins
I'll wait bro :DAbsentminded
Let us continue this discussion in chat.Absentminded
S
1

Regarding firebase you have to do this:

First Firebase is a nosql database so it uses JSON to add values to the database. Also Firebase is a service that has realtime database,storage,cloud functions,authentication.So its your best option.

Now Regarding the way to store, you can do this:

In realtime Database

{
  Users:{
    push_id_here{
          name:peter
          password:a_password_here
          email: email_here
              }
    push_id_here{
          name:john
          password:a_pass_here
          email: email_here
       }
     }

     Box:{
        push_id_here{
              productname: productx
              availability: available
              image: image_url_here
                     }
         push_id_here1{
                 productname: producty
                 availability:free
                 image: image_url_here
                     }
             }

First yes authenticate the user, regarding image send it to storage and add it in database, this is probably your best option.

Push_id_here: is basically a random id generated for each node, its like a primary key.

You do it like this:

DatabaseReference ref=getInstance().getReference().child("Users").push();

the Push() will create a random id. The above is the realtime database, to create it you have to connect to firebase in the android studio.

In android studio go to Tools>Firebase>realtime database and connect to database.

to send data to database you can do this:

 DatabaseReference ref=getInstance().getReference().child("Users").push();
 ref.child("name").setValue(name) //name that you can get from `Editext`
 ref.child("email").setValue(email)

Regarding authenticate, you have to also connect to firebase authenticate, go to Tools>Firebase> firebase authenticate and enable.

Authentication means it will be authenticated in firebase, usually it authenticate email and password, there is also phone authentication. To authenticate you can add this in your code:

firebaseAuth.signInWithEmailAndPassword(email,password)
        .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {


                if(task.isSuccessful()){
                    //code here
                }else{
                    Log.e("ERROR",task.getException().toString());
                    Toast.makeText(LoginActivity.this, task.getException().getMessage(),Toast.LENGTH_LONG).show();
                }
            }
        });

example:

Sample db

In this db Klx0N4pxsBHGVkhYuY0 is a push id and channels is like Users in the JSON I gave

Stilwell answered 21/11, 2017 at 13:43 Comment(14)
tell me what else you need @Skizo-ozᴉʞSStilwell
Thanks for your answer @Peter Haddad, but let me see... what's push_id_here? This is what I have to send from the APP? How do I create the db itself, and what about the products on Google Play? And if I need authenticate user, how do I authenticate from my app? Other guys said that buying an item it's like loggin, because it stores the email, right?Absentminded
@Skizo-ozᴉʞS check edit please, the above JSON is the db in firebase its not like sql , its nosql, authentication is a service provided by firebase, so it will authenticate your users, about authenticate firebase.google.com/docs/authStilwell
but what's that name push_id_here?Absentminded
@Skizo-ozᴉʞS oh nothing its random id, generated by firebase we cant know its name.. but we can retrieve it from the database doing this String key=ref.getKey(); check image in answerStilwell
@Skizo-ozᴉʞS here in the image(from google) chatchat-15e82 is a root node, then channels is like Users node and its child of root node the push ids are below, these random ids are like primary key to identify the name:values inside of itStilwell
But I mean I do not know how many users I'll have, I have to send it from my app, right?Absentminded
yes the push id is made through this code push(), its just to seperate records like primary key, so yes from the code, everytime a user is created a push id is done for him also @Skizo-ozᴉʞSStilwell
But I have to create the db? first?Absentminded
And this name and email, from where I get? Do I have to implement the Authentication aswell?Absentminded
You create the db from your code and email and password are the text in the edit text.. Then you authenticate themStilwell
I do not need to sign in with Gmail?Absentminded
Noo it depends what sign in method you choose when authenticing, there is email and password/google sign in / phone number/githubStilwell
Let us continue this discussion in chat.Absentminded
M
1

in order to handle dynamic products, you need a web application, which has no direct relation to the Android application, but it's backend system (only to control the release process), which interfaces ...

a) with the backend system of the application, whether it may be FireStore (in order to handle product images as "document") - or even Cloud Functions, loading the product feed through the Google Play Developer API and then delivering it as JSON to the end-devices (Cloud Functions would also permit inserting into Firebase)... however, the product images would need to be cached locally (in the internal storage, not the resources).

b) with the Google Play Developer API, in order to manage in-app products and/or consumables.

eg. when one launches an in-app product with the web-application, it would insert the product into the Play Store, to make it generally known & the FireStore, to make it visible and purchasable, from within the Android app (or with Cloud Functions, it would load an updated product feed from the API, with the same effect).

Mcferren answered 21/11, 2017 at 21:18 Comment(0)
K
0

you can sharedpreferences and that will be an easy way out. when the user logged in you can retrieve his paid box id (depending upon your table) from the response.when creating recyclerView you can check for the item if it is paid and is stored in sharedpreferences.

inside bindViewHolder function of recyclerview check for the following pseudocode

  1. if item == "paid" && item exist in sharedprefrences list make it clickable (or something you want)
  2. if it is not (else part) then go to payment page.
Kumquat answered 21/11, 2017 at 6:55 Comment(4)
If I use other device data I will loose the dataAbsentminded
I put it on other answer I need this I know it's quite broad... but I'd like to read a simple solution to how to, to help me out to start with this, I allready have the app made, I have not uploaded it on Google Console Developer I only have to add this, the simple that I want is : user opens the app(don't know if I need to create a login to store who buy and who don't), user can buy a box for example, pays for it, and then use it ALWAYS.Absentminded
firebase is just a realtime database.you just need to link the purchaced item to user table.Kumquat
If you know how to feel free to put an exampleAbsentminded

© 2022 - 2024 — McMap. All rights reserved.