how to create random UUID in Android when button click event happens? - java

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.

Related

Get a Place Object From String Address where User Clicks on Map

Some background:
I have a map where I allow the user to click and select a place. Then I am getting the address from the place where they clicked.
What I want to do: Using that address, which is a String, I want to get details about that place by using the new Google Map Places API.
I'm attempting to do this with the code below
//Make the Autocomplete request builder with the String address
FindAutocompletePredictionsRequest.Builder requestBuilder =
FindAutocompletePredictionsRequest.builder()
.setQuery(address)
.setTypeFilter(TypeFilter.ADDRESS);
placesClient = Places.createClient(getApplicationContext());
//Create the Autocomplete Task
Task<FindAutocompletePredictionsResponse> task =
placesClient.findAutocompletePredictions(requestBuilder.build());
task.addOnSuccessListener(new OnSuccessListener<FindAutocompletePredictionsResponse>() {
#Override
public void onSuccess(final FindAutocompletePredictionsResponse findAutocompletePredictionsResponse) {
//Use the response to get a list of Predictions
List<AutocompletePrediction> list = findAutocompletePredictionsResponse.getAutocompletePredictions();
if (list.isEmpty() || list == null) {
} else {
//Get the first Autocomplete prediction and later, it's ID.
AutocompletePrediction ap = list.get(0);
//Provide a list of Place Fields that I want to retrieve.
List<Place.Field> placeFields = Arrays.asList(Place.Field.ID, Place.Field.NAME, Place.Field.ADDRESS);
//Make the request to fetch the place using the Place ID obtained from the Autocomplete prediction.
FetchPlaceRequest request = FetchPlaceRequest.builder(ap.getPlaceId(), placeFields).build();
placesClient = Places.createClient(getApplicationContext());
//Using the Place ID from the Autocomplete prediction, make a request to fetch places.
placesClient.fetchPlace(request).addOnSuccessListener(new OnSuccessListener<FetchPlaceResponse>() {
#Override
public void onSuccess(FetchPlaceResponse fetchPlaceResponse) {
//Use the response to get the Place Object
Place place = fetchPlaceResponse.getPlace();
//Display the results from the Place Object
displayResults("\n-----------------\nName: " + place.getName() + "\nAddress: " + place.getAddress());
}
}).addOnFailureListener(new OnFailureListener() {
//......
});
}
}
});
task.addOnFailureListener(new OnFailureListener() {
//......
});
Problem: The problem is that when I do this and use place.getName(), instead of displaying the location's name, as it should, it displays the first part of the address like the street number and name. Additionally, other Fields like the phone number and opening hours are null.
Does anybody know how I can get the Place Object from the String address?
Getting details about the place where the user clicks is the most important feature of my Android app.
I am using the new Places API since the Place Details and Place Picker are now deprecated.

Validating two strings

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?

updating a tuple in a sqlite table in android studio

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.

Android using SharedPreferences

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:

Saving User ID in Shared Preferences Android

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
}

Categories

Resources