Is SharedPreferences suitable, or is there a better alternative? - java

I am trying to become familiar with android application development. I am trying to make a simple app to learn the basic skills, but I am not sure how to handle this part of the app. Therefore I need advice about how to go further.
I have a simple app with a button and a textview with 0 on it: the score. When the button is clicked, score goes up by 1 (by simple java code). When I close the app and restart, the score is 0 again.
What I want: When closing the app, the score must be saved, so that the same score appears on restart. For example, like that egg that you have to click on a million times. If several users had the app, everyone should have their own score (of course). The number should therefore really be linked to phone/account.
I already read about sharedpreferences. It sounds like what I'm looking for: Storing variables. However, I don't know if this is suitable for what I want to use it for. The score should never be lost for that specific phone/account. It may not be possible for the user to adjust the score himself (except by clicking on the button).
My question: Is sharedpreferences suitable for what I want to use it for, or is there a better alternative?

SharedPreferences is used to store small pieces of data locally on your device. So, if the user Uninstall the app or Clears App data, the the data you store in SharedPreferences will be cleared.
If you are okay about data being lost on Uninstall/ Clear Data, SharedPreferences is surely the best way to store such small piece of information as using an Online database is quite an overkill for such small piece of data.
The score should never be lost for that specific phone/account.
But according to this, it seems like don't want to lose the data even if the user Uninstall/Clear Data, clearly you have to use a Cloud Database like Firebase Real-time database/ Firestore.
If you want users to Login/Sign Up, you have to use Firebase Auth otherwise, you can simply store data as PhoneNumber : Score key-value pairs on Firestore.
Hope it helps

Related

So am building an app and it has this feature that i dont know exactly how to go about it

I hope this makes a bit sense, basically, I have this feature in my app for tracking calories which consists of having this page that only appears the first time you use the feature and it asks you to add personal details (so it can make the right calculations), after that you get faced with a simple page that tracks your nutrition with a button for the user to insert the meals he has eaten, this page has to save the inserted data (via firebase) and then restart from 0 each and every day.
my first problem is I don't know how I make the page that only appears one time to save personal data(to be more precise I don't know how to make only appears the first time). and the second problem is how do I make the app automatically sends the given data at the end of each day?
interface in normal state, interface when adding the meals
hopefully, this 2 images will help you get a better grasp of what am trying to explain
don't worry am not looking for someone to straight up solve it all for me, I just need some orientation about what type of things/functions I need to do to solve these 2 problems
While #Narendra_Nath's answer might work, please note that is not a bulletproof solution. Why? Because a SharedPreferences doesn't persist across app uninstalls. This means that your user can install and uninstall the app and see the page as much as they want. So if you indeed want a user to see a screen only once, then you should consider storing that data in a database. Please note that SQLite isn't also a solution because when a user uninstalls the app, everything that is stored locally is wiped out. So what's the solution?
The best way to solve this would be to store the data in the cloud, either in Cloud Firestore or in the Realtime Database. So you can set a boolean variable and always check against it.
If you however intend to implement Firebase Authentication, then another solution would be to display the screen when your users are authenticated for the first time. So even if they will try to sign in on another device, install and uninstall the app, they won't be able to see the screen again.
Regarding the second problem, you should consider using Cloud Function for Firebase. It's the most elegant solution. If you want to somehow schedule an operation, then you should consider using Cloud Scheduler, as explained in my answer in the following post:
Is it not possible to have a code in the background who will be called every 24h?
Make the page that only appears one-time -> store a value in the shared preferences "isInfoShownToUser -> false" then do a check when the app starts to check if this value is false or true. If it is false show the "take the info" page .. then turn the value to false in the shared preferences.
How do I make the app automatically send data -> Use a Workmanager implementation to send data to the server (Firebase) at a particular time ..
Or use a implementation like the first one which uploads the data to the server just once everyday

Saving multiple bits of data to be later retrieved on demand?

Trying to make an app in android studio that works as a fitness helper/tracker. On a daily basis and multiple times a day, the user enters data regarding their diet/exercise. Prior to doing so, the user selects which day they're currently on, making the data they input specific to the chosen date. I want to give users the ability to retrieve any available data for a specific day on demand.
I don't quite think sharedPreferences would work, so I was thinking about just saving to internal storage as a text file. The problem is that 1) with all the different files that would be created for even a single day, I feel that it would get messy and 2) I'm not sure how how to retrieve the specific file I'd need, parse it, then output the parsed data graphically if I'm only using a single constructor to make each text file.
I haven't yet delved deeply into using a SQLite DB, it seemed somewhat excessive for this, so I'm hoping someone can either help me figure out a better way to solve the problem or enlighten me as to a more efficient method.
Thanks in advance!

How can I keep track of a "like" system on android?

I am currently making an android app for a friend who is a photographer where he will display his images in a RecyclerView. We would like to have sort of like a "like" feature where they can like his pictures. My question is, how would I keep track of the "likes"? What I mean is, how can I make it so that if someone already liked it, they cannot exit the app, come back and like it again? I thought about adding a +1 every time there was a like to the image properties in a database, but how can I keep them from exiting the app, coming back, and liking it again? TIA!
your problem is just a matter of identity. To achieve your goal, you should have a way to identify every piece of the pictures and each of the person who will give up-votes to these pictures.
If you can identify different pictures and different users, you can achieve your goal by either of the following ways:
For each of the pictures store all the users that have liked it. And every time a user want to like a picture, you should check whether he is in this collection or not. Only add the identity of the user to this collection if he is not in this set which means he did not like this picture before
Or you can store all the pictures that are liked by the user.
Which way is better depends on your other use cases.
To identify your pictures you can just assign a distinct name for each of the picture.
So you can see the key problem it how to identify your users.
Since you do not provide a detailed use case of the like action, I will describe some general ideas.
If you have a server
If the user must login, you can identify your users by their login id
If your user do not need to login, you can use some other information to identify your user for example their device id, MAC address or other device-specific indentity.
If you do not have a server, then how can you identify all the users that use the same device? The only way I can come up with is that, you must implement a local user system and ask the user to log in before they want to like a photo.
If you have so signing in users my guess is that you can't. You could save on a hidden file on the device the ids of the photos the device "liked" but this can be easily deleted if the user deletes the apps cache files or uninstall/reinstall.
Not an android expert here, just mho
With login:
In your Database there are "User", "Image" and "User_like_image"
You just have to check if this user didnt already upvoted the image
without login:
You locally store the ID of every images he upvoted
A rough idea: with each item that can be liked store a list of ids that liked it on the server. Your like count is equals to the list length.
On each device generate a random device id token (UUID.randomUUID() is always a good candidate), persist it locally on the device (e.g. in SharedPreferences - wiping the app data will kill it but that can't be solved reliably) and send it to the server with each request.
The server can now
tell you whether you already liked an image which is nice to see on the device and
reject multiple likes from the same device
A simpler approach: store locally in e.g. SharedPreferences that you liked the item. Then behave nicely and don't send another like request to your server backend when you see that you already did. Can be abused because it relies no the client software to be nice but I doubt a small photographer app needs to care too much about that.
A more elaborate approach: require user accounts. That works accross devices and persists through app uninstalls. People that go far enough to create multiple accounts to vote multiple times can't be stopped anyways. The big downside is that people will most likely not want to have another account just to like some photos. Would not recommend if avoidable.
What I did to avoid having people like the same item twice was:
Have 2 states with the same button. If you clicked on "like" the button state changes to "Remove Like" Save the state of the button in shared prefs and check the state before a click is given.
Example:
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
String ButtonText = button.getText().toString();
if(ButtonText.equals("Like"){
//code for Like
button.setText("Remove Like");
}
else{
//code for remove Like
button.setText("Like");
}
}
});

How to store and read user usage data of my application in Android using java?

I have created a an application for a project - it's very basic... what I would like to do next is see how users are using my application e.g. buttons pressed, which page is viewed the most, for how long etc.
I am new to java and I do not understand how I can implement such thing; I have an idea but do not know whether it is efficient;
I would add a counter for each of the buttons in my app, whenever a button is pressed the counter increases by 1 and so on and so forth;
To see how long a user stays on a page, I could add a timer when the user enters the page, timer starts and stops when user exits.
...
Would something like this is viable and efficient? are there better ways of implementing such algorithm.
Not sure if there are, I searched but couldn't find any, does google offer such service like they do for websites with google analytic.
I am sorry, I've no to show this, as I haven't actually starting doing it. Wanted to get a grasp of it before I do and find out whether it is the correct strategy.
I would really appreciate your help.
https://developers.google.com/analytics/devguides/collection/android/v4/
Analytics for android apps maybe its what u are looking for
Start here: http://www.google.com/analytics/mobile/
https://developers.google.com/analytics/devguides/collection/android/v4/
You could also go with that you stated already, and add those values to an array. Just note that this will require you to turn on some permissions which might make your app unpalatable for some individuals.

Since when is the phone charging/discharging

I wanted to learn more about the Android Services / Broadcasts, so I started a simple project, to create a battery monitoring app. It turned out pretty good, I'm using it for a few days now, but I want to add a new function: to show since when is the phone charging/discharging.
First I thought that I would create two static fields in my BoradcastReciever extension class, where I get and publish the data about the battery, one for the actual state (charging/discharging), and one for the time, when the change in state happened. This way, I could just subtract from the current time the last change, and know exactly since when is the phone charging/discharging.
But there is a problem with this solution: It won't show the correct data at first, when a user starts the app. I wouldn't make a big deal of it, but I saw that Android tracks this data somewhere, because inside my phone settings I found this information, so why take the hard way.
So my question is: is there an easy way to get from the Android system the date/time (no matter what format) of the last charging state change?
I looked at the BatteryManager reference but there are no constants named after what I seek, and which I could use, to get the information from the Intent of my receiver.
The Android OS tracks the connect/disconnect of a power source, but does not make this data accessible to apps. You have to record this all yourself, using intent filters.
The two intent filters to use are android.intent.action.ACTION_POWER_CONNECTED and android.intent.action.ACTION_POWER_DISCONNECTED; with these, you can monitor when the power source is connected and disconnected.
You can find information about this process explained incredibly clearly here. Another blog describing the process can be found here.

Categories

Resources