My query is straight forward, couldn't find answer across google:
For Example:
Repository 1 -> username1
-> password1
Repository 2 -> username2
-> password2
Repository 3 -> username3
-> password3
As mentioned above, I have a dialog box with three repositories. When user selects a repository automatically another dialog box pops up to enter username and password.
So, what i am trying to achieve is to save repository name, username and password in a shared preference with a single key.
I know how to create a shared pref object with a single key and value. What i am looking for is a shared pref obj with a single key and 3 values.
Is it really possible? If yes, you can show me some direction.
You can't store three values with a single key in the same SharedPreferences file, at least not on the abstraction level of the SharedPreferences object.
What you can do is store a JSON representation of the n 3-tuples (I think that's what you need). In other words, store a String which is made from a JSONArray of JSONObjects. This way, you need not care about separators, escaping and other such annoyances.
SharedPreferences prefs = getSharedPreferences(getPathForUser(username, password) + PREF_RESOURCES_NAME, MODE_PRIVATE);
public static String getPathForUser(String username, String password) {
String sUsername = null;
String sPassword = null;
// sUsername
if (username != null && username.trim().length() > 0) {
sUsername = username.trim();
} else {
sUsername = "defaultUsername";
}
// sPassword
if (password != null && password.trim().length() > 0) {
sPassword = password.trim();
} else {
sPassword = "defaultPassword";
}
try {
return URLEncoder.encode(sUsername, "UTF-8") + "__" + URLEncoder.encode(sPassword, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return "";
}
}
Related
So I am trying to send data back to my Firebase Database with only users that have signed up and logged in. I have written a code to send the data but i am trying to write an else if statement that a message in this case a Toast appears if they have not signed up. I am struggling to write a code for that.
private void sendScore() {
String userName = name.getText().toString();
String userScore = BenchScore.getText().toString();
if(!TextUtils.isEmpty(userName) && !TextUtils.isEmpty(userScore)) {
String id = databaseReference.push().getKey();
ScoreProfile scoreProfile = new ScoreProfile(id, userName, userScore);
databaseReference.child(FirebaseAuth.getInstance().getUid()).setValue(scoreProfile);
name.setText("");
BenchScore.setText("");
} else if(FirebaseAuth.getInstance().) {
Toast.makeText(Score.this, "You need to sign up in order to use this", Toast.LENGTH_SHORT).show();
}
}
If you want to check if an user is logged in you can use :
...
else if( FirebaseAuth.getInstance().getCurrentUser() == null )
{
// Call your toast here
}
Replace ur code with this one:
private void sendScore() {
String userName = name.getText().toString();
String userScore = BenchScore.getText().toString();
if(FirebaseAuth.getInstance().getUid() != null && !TextUtils.isEmpty(userName) && !TextUtils.isEmpty(userScore)){
String id = databaseReference.push().getKey();
ScoreProfile scoreProfile = new ScoreProfile(id, userName, userScore);
databaseReference.child(FirebaseAuth.getInstance().getUid()).setValue(scoreProfile);
name.setText("");
BenchScore.setText("");
} else if (FirebaseAuth.getInstance().getUid() == null) {
Toast.makeText(Score.this, "You need to sign up in order to use this", Toast.LENGTH_SHORT).show();
}
}
I've just included a check for whether getUid() is non null in the if statement and in else if, I've checked whether getUid() is null. This would serve your purpose, hopefully.
I am getting group of words as output, is there any way to fetch email id's from that group.
My output will be like this.
Lakshman Kumar,D/no:45/24/d4,USA,Android app devoloper,lakshman#gmail.com
If there are one or more email addresses, split the text and match the pattern of email as below:
String[] tokens = yourText.split(",");
for (String token : tokens) {
if (Patterns.EMAIL_ADDRESS.matcher(token).matches()) {
String email = token;
//use this email
}
}
you need to use regex for fetching email id from text like this
Pattern p = Pattern.compile("\\b[A-Z0-9._%+-]+#[A-Z0-9.-]+\\.[A-Z]{2,4}\\b",
Pattern.CASE_INSENSITIVE);
Matcher matcher = p.matcher("your text will be here ");
Set<String> emails = new HashSet<String>();
while(matcher.find()) {
emails.add(matcher.group());
}
if you are sure that "#" will always be used only inside email addresses, you could do this:
String output = "Lakshman Kumar,D/no:45/24/d4,USA,Android app devoloper,lakshman#gmail.com";
public String getEmail(){
// Splitting your output by ','
String[] splittedOutput = output.split(",");
for (String s : splittedOutput){
// Checking to see if '#' exists in string
if (s.indexOf("#") >= 0){
return s;
}
}
return "email not found";
}
Try this .
String response = "Lakshman Kumar,D/no:45/24/d4,USA,Android app devoloper,lakshman#gmail.com";
String[] strings = response.split(",");
String email = strings[strings.length - 1];
Log.e("TAG", email);
NOTE
Use split in your code
Use strings[strings.length - 1] to get value of email
I am grabbing a String from text file on a url and saving it to sharedPreferences ... then the next time it grabs the String, it compares it against the old one stored in shared preference and if its different it notifies the user.
I am getting the string from url fine and its saving in sharedPreferences, but when I try to compare them with an if (x == y) statement it always results as not the same;
Here is the onPostExecute()
protected void onPostExecute(String result) {
String Input;
String oldInput;
Input = result.toString();
oldInput = currentSavedSettings();
if (Input == oldInput){
Toast.makeText(MainActivity.this, "fixed", Toast.LENGTH_LONG).show();
} else {
savePrefs("CURRENT_SETTINGS_FILE", Input);
//the toasts were used to ensure that neither were returning null
Toast.makeText(MainActivity.this, oldInput, Toast.LENGTH_LONG).show();
Toast.makeText(MainActivity.this, Input, Toast.LENGTH_LONG).show();
// the following is commented out until I fix this issue
//createNotification();
}
}
and the currentSavedSettings which is getting the old CURRENT_SETTINGS_FILE
private String currentSavedSettings() {
SharedPreferences sp =
PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
String result = sp.getString("CURRENT_SETTINGS_FILE", null);
return result;
}
and for good measure here is what i am using to save the SharedPreference
private void savePrefs(String key, String value) {
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(MainActivity.this);
Editor edit = sp.edit();
edit.putString(key, value);
edit.commit();
}
Use .equals or .equalsIgnoreCase to compare strings.
For more info
How do I compare strings in Java?
Did you try this,
passcode == pref_passcode // is not the same according to Java
String passcode;
pref_passcode.contentEquals(passcode); //try this or
pref_passcode.equals(passcode)
You should always use one of these to compare string. do not use equal signs (==)
I am trying to make a basic app that allows a user to create an account and sign in. How do I save this information in a file that is globally accessible to all classes?
I tried using SharedPreferences, and was able to store the information but could not figure out how to retrieve it:
public void onClick(View v) {
// TODO Auto-generated method stub
EditText username = (EditText)findViewById(R.id.editText1);
EditText password = (EditText)findViewById(R.id.editText2);
EditText email = (EditText)findViewById(R.id.editText3);
String usernameData = username.toString();
String passwordData = password.toString();
String emailData = email.toString();
//How do I store data in java?
if (username != null && password != null && email != null){
savePreferences("usernameKey", usernameData);
savePreferences("passwordKey", passwordData);
savePreferences("emailKey", emailData);
Intent nextpage =new Intent(accountcreation.this, information.class);
startActivity(nextpage);
}
To obtain shared preferences, use the following method In your activity:
SharedPreferences prefs = this.getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);
To read preferences:
String dateTimeKey = "com.example.app.datetime";
// use a default value using new Date()
long l = prefs.getLong(dateTimeKey, new Date().getTime());
To edit and save preferences
Date dt = getSomeDate();
prefs.edit().putLong(dateTimeKey, dt.getTime()).commit();
Take from: How to use SharedPreferences in Android to store, fetch and edit values
I'm creating Shared Preferences as follows
preferences = getSharedPreferences("text", 0);
final Editor editor = preferences.edit();
String s1 = serverIP.getText().toString();
String s2 = serverPort.getText().toString();
String s3 = syncPass.getText().toString();
String s4 = proxyServer.getText().toString();
String s5 = proxyPort.getText().toString();
editor.putString("SERVERIP", s1);
editor.putString("SERVERPORT", s2);
editor.putString("SYNCPASS", s3);
editor.putString("PROXYSERVER", s3);
editor.putString("PROXYPORT", s3);
and onCreate I want to display the values in a new set of TextViews, but the first time I don't have any values stored in the shared preferences and will get a NULL Pointer exception.
I want to know if there is any built-in method which can check if the SharedPreferences contains any value or not, so that I can check if the key exists and if not, then replace the new set of TextViews with the preferences value.
Try contains(String key) Accorting to the Javadocs,
Checks whether the preferences contains a preference. Returns true if
the preference exists in the preferences, otherwise false.
Every method for fetching values from SharedPreferences has default value which is returned in case the key does not exist
preferences = getSharedPreferences("text", 0);
String value = preferences.getString("unknown_key",null);
if (value == null) {
// the key does not exist
} else {
// handle the value
}
Try out
SharedPreferences shf = getSharedPreferences("NAME_SharedPref", MODE_WORLD_READABLE);
String strPref = shf.getString("SERVERIP", null);
if(strPref != null) {
// do some thing
}
I know this is a late answer but for those who want to know if a shared preference is either empty or zero size, you can check it two ways.
preferences = getSharedPreferences("text", 0);
Map<String, ?> entries = preferences.getAll();//get all entries from shared preference
Set<String> keys = entries.keySet();//set all key entries into an array of string type
//first option
if(keys.isEmpty()){
//do your staff here
}
//second option
if(keys.size()==0){
//this shows that it is empty as well
//do your staff here
}
//Below is extra
//If you want to get the names of each keys also, you can use
//For each loop as well
//Go through the set of keys
for (String key : keys) {
String keyName = key;//get each key name
}
LoadRuns();
if (loadedruns == 1) {
Toast.makeText(MainActivity.this, "First run", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(MainActivity.this, "No. runs: " + loadedruns,
Toast.LENGTH_SHORT).show();
}
loadedruns++;
SaveRuns("runs", loadedruns);
public void SaveRuns(String key, int value){
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(key, value);
editor.commit();
}
public void LoadRuns(){
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
loadedruns = sharedPreferences.getInt("runs", 1);
}