I just asked a question about this but I want to go at it a different way. When a user edits his/her profile and hits the save button, I want to be able to generate a random number using UUID. I want this ID to stay the same if the user goes back and edits their profile a second time (if they press 'save' again I want to retain the ID that was generated the first time they pressed 'save'). I have the following code working to save other data, but I'm not sure how to include a check that can find out if an ID has already been generated. Here is my code:
public void save(View view) {
String firstnameText = firstname.getText().toString();
String lastnameText = lastname.getText().toString();
String phoneText = phone.getText().toString();
String cityText = city.getText().toString();
String zipText = zip.getText().toString();
String uuid = UUID.randomUUID().toString(); //Generate random ID but I
think this would generate a
new ID each time the data is
saved
if (firstnameText != null)
PreferenceConnector.writeString(this, PreferenceConnector.FIRSTNAME,
firstnameText);
if (lastnameText != null)
PreferenceConnector.writeString(this, PreferenceConnector.LASTNAME,
lastnameText);
if (phoneText != null && !phoneText.equals(""))
PreferenceConnector.writeLong(this, PreferenceConnector.PHONE,
Long.parseLong(phoneText));
if (cityText != null)
PreferenceConnector.writeString(this, PreferenceConnector.CITY,
cityText);
if (zipText != null && !zipText.equals(""))
PreferenceConnector.writeInteger(this, PreferenceConnector.ZIP,
Integer.parseInt(zipText));
if (uuid != null) //what next?
startActivity(new Intent(PreferencesActivity.this, Main.class));
}
You can set a Boolean SharedPreference that is initialy set to false and then set to true the foirst time an ID is generated, then you check this boolean before generating and ID and only generate if it is false so basicly
//get idHasBeenGenerated from prefs with default false
if(!idHasBeenGenerated)
{
//generate ID
//change value of idHasBeenGenerated to true and save in shared prefs.
}
Edit:
SharedPreferences prefs =PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
boolean idHasBeenGenerated = prefs.getBoolean("idgenerated", false);
if(!idHasBeenGenerated){
String uuid = UUID.randomUUID().toString();
//do your thing with PreferenceConnector
Editor editor=prefs.edit();
editor.putBoolean("idgenerated", true);
editor.commit();
}else{
//Do nothing ID has already been generated
}
Related
I'm trying to validate two strings via TextUtils.isEmpty but i'm failing everytime.
Following is my code:
private void addArtist() {
//getting the values to save
String email = editTextName.getText().toString().trim();
String mobileno = editTextName1.getText().toString().trim();
//checking if the value is provided
if (TextUtils.isEmpty(email)){
//if the value is not given displaying a toast
Toast.makeText(this, "Please enter email.", Toast.LENGTH_LONG).show();
}
else{
//getting a unique id using push().getKey() method
//it will create a unique id and we will use it as the Primary Key for our Artist
String id = databaseArtists.push().getKey();
//creating an Artist Object
Artist artist = new Artist(id, email, mobileno);
//Saving the Artist
databaseArtists.child(id).setValue(artist);
Toast.makeText(this, "Successful...", Toast.LENGTH_LONG).show();
}
}
Currently this code is working on string email, i want it to work with string mobileno also.Any help is appreciated.
Why don't you just try to use try catch block and inside it try to convert this string after you read from TextField control object into number if "Mobileno" variable should be int type? If it fails then you can in catch block make some other instructions to prevent from inserting it to field of specific object. Have you tried that?
before voting down please read my question , which I have searched a lot but I couldn't find the answer yet, so I would appreciate if you give me hand to overcome the problem.
Actually I need to update a tuple in a table named "Demographics". But it seems my code does not work correctly, and in fact after running the app , I got the result "0" for updating which means nothing get updated.
12-21 12:34:54.190 2351-2367/? D/Update Result:: =0
I guess my problem is due to not pointing to the right row of the table based on Primary key. Actually when a user Register to my app the following things should happen:
1- Create a tuple in "Demographics" table --> username, password and email will be inserted. An auto increment primary key also constructed and inserted.
2- user logins , then he can complete rest of information in "Demographics" table. --> this MODIFICATION is the "update" process which I', asking.
Would you please tell me if the following codes are wrong or have any implicit error?
DemographicsCRUD.java
public long UpdateDemographics(Demographics_to demoId) {
//SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DataBaseHelper.lastName, demoId.getD_lastName());
values.put(DataBaseHelper.firstName, demoId.getD_firstName());
values.put(DataBaseHelper.dateOfBirth, demoId.getD_dateOfBirth())
long result = database.update(dbHelper.Demographics_Table, values,
WHERE_ID_EQUALS,
new String[]{String.valueOf(demoId.getD_patientID())});
Log.d("Update Result:", "=" + result);
// db.close();
return result;
}
here is where I call the above code:
private void updateDemographicsTable()
{
ep_demoId = new Demographics_to();
String ep_na = ep_name.getText().toString();
String ep_fa = ep_family.getText().toString();
.
.
.
ep_demoId.setD_dateOfBirth(ep_bd);
ep_demoId.setD_firstName(ep_na);
ep_demoId.setD_lastName(ep_fa);
}
#Override
protected Long doInBackground(Void... arg0) {
long result = ep_demoCRUD.UpdateDemographics(ep_demoId);
return result;
}
#Override
protected void onPostExecute(Long result) {
if (activityWeakRef.get() != null
&& !activityWeakRef.get().isFinishing()) {
if (result != -1)
Toast.makeText(activityWeakRef.get(), "Information Updated!",
Toast.LENGTH_LONG).show();
}}
Looks like whatever you are passing in as the patientID does not have a matching record in the database or the dataobject "Demographics_to" has the patient ID set incorrectly.
Hey guyz check it out what I am missing here cause of I am not able to fetch all my data from Shared Preferences.
I am making such an tasklist application in which I am saving my data(means mytask) with a certain key and storing it in the shared Preferences and increments a variable for total count.
Check my Code(Whenever I click on addTask button the following code gets executed).
private void saveToSharedPreference(){
sharedPre = getSharedPreferences("todoPref",Context.MODE_PRIVATE);
editor = sharedPre.edit();
String myKey = "key"+a;
String myValue = et.getText().toString();
editor.putString(myKey,myValue);
// editor.putInt("totalTask", a);
editor.commit();
}
Now when I close the application and open it again the following code gets executed in order to load the data from shared preferences.
private void loadData(){
sharedPre = getSharedPreferences("todoPref",Context.MODE_PRIVATE);
int p = 1;
String myKey = "key"+p;
while(sharedPre.getString(myKey,"") != null){
Toast.makeText(this, sharedPre.getString(myKey,""),Toast.LENGTH_SHORT).show();
}
}
but the problem is all it always returning null on all indexes. I don't know why I am getting this error. Please help me
Thanks in advance
Sarosh Madara
to load all saved values just use the following code:
private void loadData() {
SharedPreferences sharedPre = getSharedPreferences("todoPref",android.content.Context.MODE_PRIVATE);
Map<String,?> keys = sharedPre.getAll();
for(Map.Entry<String,?> entry : keys.entrySet()){
if (entry.getValue().toString().length() > 0) {
Log.d("map values",entry.getKey() + ": " + entry.getValue().toString());
}
}
}
I found it here but added a check to ignore null values.
to save values to Shared Preference I suggest using an instance of the current time for the key. no need to save any integer key values:
private void saveToSharedPreference(String myValue){
SharedPreferences sharedPre = getSharedPreferences("todoPref",android.content.Context.MODE_PRIVATE);
Editor editor = sharedPre.edit();
String key = String.valueOf(Calendar.getInstance().getTimeInMillis());
editor.putString(key,myValue);
editor.commit();
}
so whenever you want to add values to Shared Preferences use:
saveToSharedPreference("myValue");
and to load them all use:
loadData();
The Map Interface
A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value. read more...
SharedPreferences: Class Overview
Do like this -
1) save in shared preference like this -
private void saveToSharedPreference(){
sharedPre = getSharedPreferences("todoPref",Context.MODE_PRIVATE);
editor = sharedPre.edit();
String myKey = "key"; // removed +a
String myValue = et.getText().toString();
editor.putString(myKey,myValue);
// editor.putInt("totalTask", a);
editor.commit();
}
2) load it like this -
private void loadData() {
sharedPre = getSharedPreferences("todoPref",Context.MODE_PRIVATE);
int p = 1;
String myKey = "key"; // removed "+p"
String value = sharedPre.getString(myKey, "");
}
Don't compare with != null in while loop. Use below code and see if the problem solves:-
private void loadData(){
sharedPre = getSharedPreferences("todoPref",Context.MODE_PRIVATE);
int p = 1;
String myKey = "key"+p;
String value = sharedPre.getString(myKey,"");
if(!value.equalsIgnoreCase("")){
Toast.makeText(this, sharedPre.getString(myKey,""),Toast.LENGTH_SHORT).show();
}
}
I am an apprentice to Android. I need to make random UUID and store to the database as a primary key. I am utilizing UUID.randomUUID.toString() this code in Button click event. The UUID has been effectively made interestingly. Yet, in the event that I click the button once more, I need to make another UUID. In any case, my code is not making new UUID. Somebody, please help me to make an irregular UUID when I click catch.
Here is my code :
String uniqueId = null;
showRandomId = (Button)findViewById(R.id.showUUID);
showRandomId.setOnClickListener(new View.OnClickListener() {
public void OnClick(View v) {
if(uniqueId == null) {
uniqueId = UUID.randomUUID().toString();
}
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(getBaseContext(), uniqueId, duration);
toast.show();
}
});
First time it intialise the variable and next time when you click button it doesn't get null value
Remove if condition from this
if(uniqueId == null) {
uniqueId = UUID.randomUUID().toString();
}
Use this
uniqueId = UUID.randomUUID().toString();
You are explicitly avoiding the new UUID creation by:
if(uniqueId == null) {
uniqueId = UUID.randomUUID().toString();
}
Remove the check.
Your null check for uniqueId causes the problem.
when you click the button for the first time uniqueId is null and a new UUID is generated. But when you click it next time uniqueId is not null, So no new UUID is generated.
I found out a common way to store data is Android's SharedPreferences. So I went out and tried to implement it with my application.
What I want to do:
My application retrieves weather details from the users current location, if the user desires he/she can add the location by pressing add to favorites. They can have up to 10 favorite locations. So I want to store the location description (exp: Dayton, OH), the latitude and longitude (So I may fetch the details when they want to see that weather). So Shared Preferences seem to fit my need.
What I did:
- I created a loop that would cycle through 10 keys (for 10 locations) an as long as the keys were null the location information would be saved. If the key was not null, it means the key has already been created.
My code:
public void writeNewLocation(String stringLat, String stringLon, String location) {
this.latitude = stringLat;
this.longitude = stringLon;
this.location = location;
pref = mContext.getSharedPreferences("favoritelocations", 0); // 0 - for private mode
Editor editor = pref.edit();
//Loop through all the favorite keys to find an open spot:
for(int i = 1; i <= 10; i++) {
//Test for current favorite key:
String value = pref.getString("favorite"+ i +"_location",null);
if (value == null) {
//The key does not exist so it can be created and written to:
//First write the location description:
editor.putString("favorite" + i + "_location", location);
//Next the write the latitude and lonitude values:
editor.putString("favorite" + i + "_latitude", latitude);
editor.putString("favorite" + i + "_longitude", longitude);
editor.commit();
i = 11;
} else {
//If at end of loop; Inform user:
if(i == 10) {
//Display an error:
//Instantiate an AlertDialog.Builder with its constructor
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
//Create the AlertDialog characteristics:
builder.setMessage("You can only have up to 10 favorite locations. Delete some to make room.");
builder.setTitle("Message");
//Show the AlertDialog:
msgDialog = builder.create();
editor.commit();
i = 11;
} else {
//Back to top of loop.
}
}
}
//Commit to changes:
editor.commit(); // commit changes
}
So I loop through ten possible keys, if it hits 10, and all spots are taken, I alert the user. But when I call this method to create a favorite location, then call 1 of the 10 getters to display the information that should've been saved, I get a null. :( Is it too early in the morning over here or am I doing something wrong...
Thanks c: