android nullpointer exception on hashSet - android

this is my MainActivity class:
package com.example.alon.a2018_17_12_userloginexhomework;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
public static final String USERNAME = "username";
public static final String SP_LOGGED_USER = "spLoggedUser";
public static final String PREFS = "prefs";
public static final int REQUEST_CODE = 123;
public static final String DESTINATION = "destination";
public static final String REGISTERED_USERS_SET = "registeredUsersSet";
EditText etUsername, etPassword;
Button btnLogin, btnSignup;
public static HashMap<String, User> hashMap;
public static SharedPreferences sharedPreferences;
Set<String> registeredUsersSet;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
checkDestination();
checkForLoggedOrRegisteredUsers();
}
private void checkDestination() {
int destination = getIntent().getIntExtra(DESTINATION, -1);
if (destination == 0)
finish();
}
private void checkForLoggedOrRegisteredUsers() {
String loggedInUser = getSharedPreferences(PREFS, MODE_PRIVATE)
.getString(SP_LOGGED_USER, null);
if (loggedInUser != null){
User user = new User(loggedInUser);
Intent intent = new Intent(this, ActivityUserLoggedIn.class);
intent.putExtra(USERNAME, user.getUsername());
startActivityForResult(intent,REQUEST_CODE);
}
try {
registeredUsersSet = getSharedPreferences(PREFS, MODE_PRIVATE)
.getStringSet(REGISTERED_USERS_SET, null);
}catch (NullPointerException e){
e.printStackTrace();
}
if (registeredUsersSet != null){
for (String s : registeredUsersSet){
User u = new User(s);
hashMap.put(u.getUsername(),u);
}
}
}
private void init() {
registeredUsersSet = new HashSet<>();
etUsername = findViewById(R.id.etUsername);
etPassword = findViewById(R.id.etPassword);
btnLogin = findViewById(R.id.btnLogin);
btnSignup = findViewById(R.id.btnSignup);
hashMap = new HashMap<>();
sharedPreferences = getSharedPreferences(PREFS,MODE_PRIVATE);
btnLogin.setOnClickListener(this);
btnSignup.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btnSignup:
signUp();
break;
case R.id.btnLogin:
login();
break;
}
}
private void login() {
String user = etUsername.getText().toString();
String password = etPassword.getText().toString();
//logic check:
if (user.length() < 1 || password.length() < 1){
Toast.makeText(this,
"user or pass must be above 1 chars",
Toast.LENGTH_SHORT).show();
}
//username check
if (hashMap.containsKey(user)){
//password check:
if (Objects.requireNonNull(hashMap.get(user)).getPassword().equals(password)){
//all checks are okay, logging in:
Intent intent = new Intent(this, ActivityUserLoggedIn.class);
intent.putExtra(USERNAME, user);
sharedPreferences.edit().putString(SP_LOGGED_USER,user).apply();
startActivityForResult(intent, REQUEST_CODE);
} else {
//password error:
Toast.makeText(this,
"password does not match, please retry"
, Toast.LENGTH_SHORT).show();
etPassword.setText("");
}
} else {
//username error:
Toast.makeText(this,
"User does not exists, please try again"
, Toast.LENGTH_SHORT).show();
clearEditTexts();
}
}
private void signUp() {
String user = etUsername.getText().toString();
String password = etPassword.getText().toString();
if (user.length() < 1 || password.length() < 1){
Toast.makeText(this,
"user or pass must be above 1 chars",
Toast.LENGTH_SHORT).show();
} else if (hashMap.containsKey(user)){
Toast.makeText(this,
"user already exists, please choose a different usename",
Toast.LENGTH_SHORT).show();
clearEditTexts();
} else {
User newUser = new User(user,password);
hashMap.put(user,newUser);
registeredUsersSet.add(newUser.toString());
Toast.makeText(this,
"successfully registered used name " + user,
Toast.LENGTH_SHORT).show();
clearEditTexts();
}
}
private void clearEditTexts(){
etUsername.setText("");
etPassword.setText("");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK){
if (data != null) {
int destination = data.getIntExtra(DESTINATION, -1);
if (destination == 0)
finish();
}
}
}
#Override
protected void onStop() {
super.onStop();
sharedPreferences.edit().putStringSet(REGISTERED_USERS_SET, registeredUsersSet).apply();
}
}
every time I click on the sign up button I get NPE on the HashSet object. can anyone point the reason for it? it seems like the HashSet object initialize is way before the click method so I really have no idea why it goes null.
the error I get:
java.lang.NullPointerException: Attempt to invoke interface method 'boolean java.util.Set.add(java.lang.Object)' on a null object reference
at com.example.alon.a2018_17_12_userloginexhomework.MainActivity.signUp(MainActivity.java:144)

In the onCreate method, you call:
init() - > here you initialize your registeredUsersSet
but soon after that, you call:
checkForLoggedOrRegisteredUsers() -> here you initialize again registeredUsersSet, but this time from sharedPreferences, which probably returns null in your case.
(registeredUsersSet = getSharedPreferences(PREFS, MODE_PRIVATE)
.getStringSet(REGISTERED_USERS_SET, null);)
You are missing this:
if (registeredUsersSet ==null)
registeredUsersSet = new HashSet<>();

Related

Android If statement not breaking when condition is true

In this activity I am creating an account for users. I am using mobsandgeeks.saripaar API for validation features. To allow the activity to work I currently print the errors to an invisible text field, if this textfield has text, the activity does not go onto the next activity (i.e. there is an issue with user input).
I am having a problem with the if statement that checks if the username or email already exists in the database. When condition is true (checked in logs), the account is not created, but the 'Account created' message is still displayed and the application still goes to the next activity.
Any help on this would be much appreciated. Thanks
CreateAccount.java
DatabaseHelper myDb;
private static final String TAG = "CreateAccount";
//http://learningprogramming.net/mobile/android/form-validation-in-android/
#NotEmpty
#Length(min = 3, max = 10)
private EditText etUsername;
#NotEmpty
private EditText etUserAddress;
#NotEmpty
private EditText etFirstName;
#NotEmpty
private EditText etLastName;
#NotEmpty
#Email
private EditText etEmail;
#NotEmpty
#Pattern(regex = "(^\\(?([0-9]{3})\\)?[-.\\s]?([0-9]{3})[-.\\s]?([0-9]{4})$)")
private EditText etPhone;
#NotEmpty
private EditText etPaypal;
//Valid = abcABC123!
#NotEmpty
#Password(scheme = Password.Scheme.ALPHA_NUMERIC_SYMBOLS)
private EditText etPassword;
#ConfirmPassword
EditText etConfirmPassword;
Button btnCreateAccount;
TextView check;
//https://www.youtube.com/watch?v=rt-8PgncIio
ImageView profileImageView;
Button btnProfilePic;
private static final int SELECT_PHOTO = 1;
private static final int CAPTURE_PHOTO = 2;
ProgressDialog progressBar;
int progressBarStatus;
Handler progressBarHandler = new Handler();
Bitmap thumbnail;
private Validator validator;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_account);
myDb = new DatabaseHelper(this);
validator = new Validator(this);
validator.setValidationListener(this);
etUsername = findViewById(R.id.etUsername);
etFirstName = findViewById(R.id.etFirstName);
etLastName = findViewById(R.id.etLastName);
etUserAddress = findViewById(R.id.etAddress);
etEmail = findViewById(R.id.etEmail);
etPassword = findViewById(R.id.etPasswordLogin);
etConfirmPassword = findViewById(R.id.etConfirmPasswordLogin);
etPhone = findViewById(R.id.etPhoneNo);
etPaypal = findViewById(R.id.etPaypalName);
btnCreateAccount = findViewById(R.id.btnCreateAccount);
check = findViewById(R.id.tvCheck);
btnProfilePic = findViewById(R.id.btnProfilePicture);
profileImageView = findViewById(R.id.imageProfile);
btnProfilePic.setOnClickListener(this);
//(https://www.youtube.com/watch?v=rt-8PgncIio) Image
//had to change permissions in the Android Manifest file to allow for camera to be used
if (ContextCompat.checkSelfPermission(CreateAccount.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
profileImageView.setEnabled(false);
ActivityCompat.requestPermissions(CreateAccount.this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
} else {
profileImageView.setEnabled(true);
}
createAccount();
}
public void createAccount() {
btnCreateAccount.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validator.validate();
//(https://www.youtube.com/watch?v=rt-8PgncIio) Image
profileImageView.setDrawingCacheEnabled(true);
profileImageView.buildDrawingCache();
Bitmap bitmap = profileImageView.getDrawingCache();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] data = baos.toByteArray();
String email1 = etEmail.getText().toString().trim();
Log.d(TAG, "onClick: email " + email1);
String username = etUsername.getText().toString().trim();
Log.d(TAG, "onClick: username " + username);
boolean emailExists = myDb.checkIfEmailAlreadyExists(email1);
Log.d(TAG, "onClick: emailExists " + emailExists);
boolean usernameExists = myDb.checkIfUsernameAlreadyExists(username);
Log.d(TAG, "onClick: usernameExists " + usernameExists);
//https://stackoverflow.com/questions/6290531/check-if-edittext-is-empty
if (etUsername.getText().toString().matches("") | etFirstName.getText().toString().matches("") | etLastName.getText().toString().matches("")
| etEmail.getText().toString().matches("") | etUserAddress.getText().toString().matches("") | etPassword.getText().toString().matches("")|
etConfirmPassword.getText().toString().matches("") | etPhone.getText().toString().matches("") | etPaypal.getText().toString().matches(""))
{
Toast.makeText(CreateAccount.this, "Please fill empty fields", Toast.LENGTH_LONG).show();
}
else if(check.getText().toString().matches("") == false) {
Toast.makeText(CreateAccount.this, "Please enter correct details", Toast.LENGTH_SHORT).show();
}
else {
if (usernameExists){
Log.d(TAG, "onClick: userExists " + usernameExists);
Toast.makeText(CreateAccount.this, "This username is already registered", Toast.LENGTH_LONG).show();
check.setText("TEXT");
}
else if (emailExists){
Log.d(TAG, "onClick: emailExists" + emailExists);
Toast.makeText(CreateAccount.this, "This email is already registered", Toast.LENGTH_LONG).show();
check.setText("TEXT");
}
else if (usernameExists == false | emailExists == false) {
boolean checktext = check.getText().equals("");
// original CRUD video - https://www.youtube.com/watch?v=kDZES1wtKUY&list=PLS1QulWo1RIaRdy16cOzBO5Jr6kEagA07&index=8
boolean isInserted = myDb.insertUserData(etUsername.getText().toString(), etUserAddress.getText().toString(), etFirstName.getText().toString(), etLastName.getText().toString(),
etEmail.getText().toString(), etPassword.getText().toString(), etPhone.getText().toString(),
etPaypal.getText().toString(), data);
if (isInserted == true) {
if (checktext == true) {
onValidationSucceeded();
}
else if (checktext == false){
Toast.makeText(CreateAccount.this, "Account not Created", Toast.LENGTH_LONG).show();
}
}
} else {
Toast.makeText(CreateAccount.this, "Account not Created", Toast.LENGTH_LONG).show();
}
}
}
});
}
//http://learningprogramming.net/mobile/android/form-validation-in-android/
#Override
public void onValidationFailed(List<ValidationError> errors) {
for (ValidationError error : errors) {
View view = error.getView();
//TextView check = findViewById(R.id.tvCheck);
String message = error.getCollatedErrorMessage(this);
// Display error messages
if (view instanceof EditText) {
((EditText) view).setError(message);
} else {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
check.setText(errors.toString());
}
}
//http://learningprogramming.net/mobile/android/form-validation-in-android/
#Override
public void onValidationSucceeded() {
Toast.makeText(CreateAccount.this, "Account Created, Please sign in", Toast.LENGTH_LONG).show();
Intent intent = new Intent(CreateAccount.this, Login.class);
startActivity(intent);
}
You have a problem in your condition:
Instead of:
else if (usernameExists == false | emailExists == false)
It should be:
else if (usernameExists == false && emailExists == false)
which means user/email not exist, insert them in DB and navigate to next activity.

Trying to keep user loggedIn in my android app after first login but not working

I am developing an android app, my app have a login activity. What i want to do is once a user is logged in for the first time it will remain logged in even if the app is closed.
I tried a way out but it didn't worked well.
Any help will b appreciated.
Thanks!
1) Login.java
private Snackbar snackbar;
private ProgressDialog pd;
private TextInputLayout mTiEmail;
private TextInputLayout mTiPassword;
private CompositeSubscription mSubscriptions;
private SharedPreferences mSharedPreferences;
private Boolean loggedIn = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mSubscriptions = new CompositeSubscription();
mSubscriptions = new CompositeSubscription();
loginUserName = (EditText) findViewById(R.id.email_edit);
loginPassword = (EditText) findViewById(R.id.pass_edit);
pd = new ProgressDialog(Login.this);
mTiEmail = (TextInputLayout) findViewById(R.id.email1);
mTiPassword = (TextInputLayout) findViewById(R.id.password);
loginButton = (TextView)findViewById(R.id.btn_login);
initSharedPreferences();
loginButton.setOnClickListener(view -> login());
}
#Override
protected void onResume() {
super.onResume();
//In onresume fetching value from sharedpreference
SharedPreferences sharedPreferences = getSharedPreferences(Constants.SHARED_PREF_NAME, Context.MODE_PRIVATE);
//Fetching the boolean value form sharedpreferences
loggedIn = sharedPreferences.getBoolean(Constants.LOGGEDIN_SHARED_PREF, false);
//If we will get true
if (loggedIn) {
//We will start the Profile Activity
Intent intent = new Intent(Login.this, Dashboard.class);
startActivity(intent);
}
}
private void initSharedPreferences() {
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(Login.this);
}
private void login() {
setError();
String email = loginUserName.getText().toString();
String password = loginPassword.getText().toString();
int err = 0;
if (!validateEmail(email)) {
err++;
mTiEmail.setError("Email should be valid !");
}
if (!validateFields(password)) {
err++;
mTiPassword.setError("Password should not be empty !");
}
if (err == 0) {
loginProcess(email,password);
} else {
Toast.makeText(this, "Enter valid details", Toast.LENGTH_SHORT).show();
}
}
private void setError() {
loginUserName.setError(null);
loginPassword.setError(null);
}
private void loginProcess(String email, String password) {
mSubscriptions.add(NetworkUtil.getRetrofit(email,password).login()
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(this::handleResponse,this::handleError));
}
private void handleResponse(Response response) {
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.putString(Constants.TOKEN,response.getToken());
editor.putString(Constants.EMAIL,response.getMessage());
editor.apply();
loginUserName.setText(null);
loginPassword.setText(null);
Intent in = new Intent(Login.this,Dashboard.class);
startActivity(in);
Toast.makeText(this, "REGISTERED-->>", Toast.LENGTH_LONG).show();
}
private void handleError(Throwable error) {
if (error instanceof HttpException) {
Gson gson = new GsonBuilder().create();
try {
String errorBody = ((HttpException) error).response().errorBody().string();
Response response = gson.fromJson(errorBody,Response.class);
Toast.makeText(this, response.getMessage(), Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
} else {
Toast.makeText(this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
Here in my onResume() method i tried a way out but didn't work, Any Suggestions?
2) Constants.java
public class Constants {
public static final String BASE_URL = "http://192.168.2.145:8080/api/v1/";
public static final String TOKEN = "token";
public static final String EMAIL = "email";
//This would be the name of our shared preferences
public static final String SHARED_PREF_NAME = "myloginapp";
//This would be used to store the email of current logged in user
public static final String EMAIL_SHARED_PREF = "email";
//We will use this to store the boolean in sharedpreference to track user is loggedin or not
public static final String LOGGEDIN_SHARED_PREF = "loggedin";
}
UPDATE
Login.java
public class Login extends AppCompatActivity {
TextView loginButton;
EditText loginUserName, loginPassword;
private Snackbar snackbar;
private ProgressDialog pd;
private TextInputLayout mTiEmail;
private TextInputLayout mTiPassword;
private CompositeSubscription mSubscriptions;
private SharedPreferences mSharedPreferences;
private Boolean loggedIn = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mSubscriptions = new CompositeSubscription();
mSubscriptions = new CompositeSubscription();
loginUserName = (EditText) findViewById(R.id.email_edit);
loginPassword = (EditText) findViewById(R.id.pass_edit);
pd = new ProgressDialog(Login.this);
mTiEmail = (TextInputLayout) findViewById(R.id.email1);
mTiPassword = (TextInputLayout) findViewById(R.id.password);
loginButton = (TextView)findViewById(R.id.btn_login);
initSharedPreferences();
loginButton.setOnClickListener(view -> login());
}
#Override
protected void onResume() {
super.onResume();
//In onresume fetching value from sharedpreference
mSharedPreferences = getSharedPreferences("login", Context.MODE_PRIVATE);
if(mSharedPreferences.getBoolean("LoggedIn", false)){
Intent intent = new Intent(Login.this,Dashboard.class);
startActivity(intent);
} else {
loginButton.setOnClickListener(view -> login());
//Do other stuff
}
}
private void initSharedPreferences() {
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(Login.this);
}
private void login() {
String username = loginUserName.getText().toString();
String password = loginPassword.getText().toString();
loginProcess(username,password);
int err = 0;
if (!validateFields(username)&& !validateFields(password)) {
err++;
mTiEmail.setError("Username should not be empty !");
}
if (err == 0) {
loginProcess(username,password);
} else {
Toast.makeText(this, "Enter valid details", Toast.LENGTH_SHORT).show();
}
}
private void loginProcess(String username,String password){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
RetrofitInterface requestInterface = retrofit.create(RetrofitInterface.class);
User user = new User();
user.setUsername(username);
user.setPassword(password);
ServerRequest request = new ServerRequest();
request.setOperation(Constants.LOGIN_OPERATION);
request.setUser(user);
Call<ServerResponse> response = requestInterface.operation(request);
response.enqueue(new Callback<ServerResponse>() {
#Override
public void onResponse(Call<ServerResponse> call, retrofit2.Response<ServerResponse> response) {
if(response.isSuccessful()) {
ServerResponse serverResponse = response.body();
if(serverResponse.getMessage().equals(Constants.SUCCESS)) {
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.putBoolean("LoggedIn",true);
//editor.putString(Constants.EMAIL,serverResponse.getUser().getEmail());
editor.putString(Constants.USERNAME,serverResponse.getUser().getUsername());
editor.putString(Constants.BUSINESSNAME,serverResponse.getUser().getBusinessname());
editor.apply();
Toast.makeText(Login.this, response.body().getMessage(), Toast.LENGTH_SHORT).show();
goToProfile();
} else {
Toast.makeText(Login.this, serverResponse.getMessage(), Toast.LENGTH_SHORT).show();
}
} else {
Gson gson = new Gson();
ServerResponse errorResponse = null;
try {
errorResponse = gson.fromJson(response.errorBody().string(), ServerResponse.class);
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(Login.this, errorResponse.getMessage(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<ServerResponse> call, Throwable t) {
Log.d(Constants.TAG,"failed");
Toast.makeText(Login.this,t.getLocalizedMessage() , Toast.LENGTH_SHORT).show();
}
});
}
private void goToProfile(){
Intent intent = new Intent(this,Dashboard.class);
startActivity(intent);
}
}
Put this code in your onCreate()
SharedPreferences pref = getSharedPrefrences("login", Context.MODE_PRIVATE); //Opening 'login' sharedPreference
if(pref.getBoolean("LoggedIn", false)){ //checking if 'LoggedIn' exist in SharedPreference if no exist it returns false. if it exist fetches its value
//Move to Next Screen
} else {
loginButton.setOnClickListener(view -> login());
//Do other stuff
}
Then in your handleResponse().. Add these lines
//Lets suppose if User is logging in for the First time.. Below lines will add 'LoggedIn' to shared preference so user logged in directly next time
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("LoggedIn", true);
editor.apply();
Set LOGGEDIN_SHARED_PREF in your void handleResponse() as below :
editor.putBoolean(Constants.LOGGEDIN_SHARED_PREF,true);
Set your sharedPreferences globally
SharedPreferences sharedPreferences = getSharedPreferences(Constants.SHARED_PREF_NAME, Context.MODE_PRIVATE);
And edit on the same in your handleReponse()
SharedPreferences.Editor editor = sharedPreferences.edit();
I updated your code:
private Snackbar snackbar;
private ProgressDialog pd;
private TextInputLayout mTiEmail;
private TextInputLayout mTiPassword;
private CompositeSubscription mSubscriptions;
private SharedPreferences sharedPreferences;
private Boolean loggedIn = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mSubscriptions = new CompositeSubscription();
mSubscriptions = new CompositeSubscription();
loginUserName = (EditText) findViewById(R.id.email_edit);
loginPassword = (EditText) findViewById(R.id.pass_edit);
pd = new ProgressDialog(Login.this);
mTiEmail = (TextInputLayout) findViewById(R.id.email1);
mTiPassword = (TextInputLayout) findViewById(R.id.password);
loginButton = (TextView)findViewById(R.id.btn_login);
loginButton.setOnClickListener(view -> login());
}
#Override
protected void onResume() {
super.onResume();
//In onresume fetching value from sharedpreference
sharedPreferences = getSharedPreferences(Constants.SHARED_PREF_NAME, Context.MODE_PRIVATE);
//Fetching the boolean value form sharedpreferences
loggedIn = sharedPreferences.getBoolean(Constants.LOGGEDIN_SHARED_PREF, false);
//If we will get true
if (loggedIn) {
//We will start the Profile Activity
Intent intent = new Intent(Login.this, Dashboard.class);
startActivity(intent);
}
}
private void login() {
setError();
String email = loginUserName.getText().toString();
String password = loginPassword.getText().toString();
int err = 0;
if (!validateEmail(email)) {
err++;
mTiEmail.setError("Email should be valid !");
}
if (!validateFields(password)) {
err++;
mTiPassword.setError("Password should not be empty !");
}
if (err == 0) {
loginProcess(email,password);
} else {
Toast.makeText(this, "Enter valid details", Toast.LENGTH_SHORT).show();
}
}
private void setError() {
loginUserName.setError(null);
loginPassword.setError(null);
}
private void loginProcess(String email, String password) {
mSubscriptions.add(NetworkUtil.getRetrofit(email,password).login()
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(this::handleResponse,this::handleError));
}
private void handleResponse(Response response) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(Constants.TOKEN,response.getToken());
editor.putString(Constants.EMAIL,response.getMessage());
editor.putBoolean(Constants.LOGGEDIN_SHARED_PREF,true);
editor.apply();
loginUserName.setText(null);
loginPassword.setText(null);
Intent in = new Intent(Login.this,Dashboard.class);
startActivity(in);
Toast.makeText(this, "REGISTERED-->>", Toast.LENGTH_LONG).show();
}
private void handleError(Throwable error) {
if (error instanceof HttpException) {
Gson gson = new GsonBuilder().create();
try {
String errorBody = ((HttpException) error).response().errorBody().string();
Response response = gson.fromJson(errorBody,Response.class);
Toast.makeText(this, response.getMessage(), Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
} else {
Toast.makeText(this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}

How to get user data with SharedPreferences from RegisterActivity

i programmed my register activity to get my user details and store it with SharePreferences
Now , im trying to get those values stored in the data to log in in my app but it seems im missing something, when i put anything in my edittexts in my login layout it logs in without checking the user
RegisterActivity.class
public class RegistrarUsuario extends AppCompatActivity {
private Button mBtnRegistrarUsuario;
private TextView mRegistrarTxt;
private EditText mUsername,mPassword,mSecondPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registrar_usuario);
mRegistrarTxt = (TextView) findViewById(R.id.titulo2);
mUsername = (EditText) findViewById(R.id.nombreUsuario);
mPassword = (EditText) findViewById(R.id.primeraContraseña);
mSecondPassword = (EditText) findViewById(R.id.segundaContraseña);
Typeface fuente = Typeface.createFromAsset(getAssets(),"fonts/MrDafoe-Regular.ttf");
mRegistrarTxt.setTypeface(fuente);
mBtnRegistrarUsuario = (Button) findViewById(R.id.btnRegistrarUsuario);
mBtnRegistrarUsuario.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences preference = getSharedPreferences("Reg",MODE_PRIVATE);
String username = mUsername.getText().toString().trim();
String password = mPassword.getText().toString().trim();
String secondpassword = mSecondPassword.getText().toString().trim();
if(username.length()<=0){
Toast.makeText(RegistrarUsuario.this, "Ingrese un usuario.", Toast.LENGTH_SHORT).show();
}
else if(password.length()<=0){
Toast.makeText(RegistrarUsuario.this, "Ingrese contraseña.", Toast.LENGTH_SHORT).show();
}
else if(secondpassword.length()<=0){
Toast.makeText(RegistrarUsuario.this, "Confirme su contraseña.", Toast.LENGTH_SHORT).show();
}
else if(password.equals(secondpassword)){
SharedPreferences.Editor editor = preference.edit();
editor.putString("Username",username);
editor.putString("Password",password);
editor.putString("SecondPassword",secondpassword);
editor.commit();
finish();
Toast.makeText(RegistrarUsuario.this, "Usuario creado con exito!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(RegistrarUsuario.this,PantallaPrincipal.class);
startActivity(intent);
}
else{
Toast.makeText(RegistrarUsuario.this, "No coinciden las contraseñas.", Toast.LENGTH_SHORT).show();
}
}
});
}
}
** LoginActivity.class**
public class MainActivity extends AppCompatActivity {
private EditText mUsername,mPassword;
private Button mLoginBtn,mBtnRecuperar,mBtnRegistrar;
private TextView mTextView;
private static String usuario ="admin";
private static String contraseña="123";
private final String KEY_USERNAME = "username";
private final String KEY_PASSWORD = "password";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mUsername = (EditText) findViewById(R.id.usuario);
mPassword = (EditText) findViewById(R.id.contraseña);
mLoginBtn = (Button) findViewById(R.id.btnIngresar);
mTextView = (TextView) findViewById(R.id.titulo);
Typeface fuente = Typeface.createFromAsset(getAssets(),"fonts/MrDafoe-Regular.ttf");
mTextView.setTypeface(fuente);
mBtnRecuperar = (Button) findViewById(R.id.btnRecuperar);
mBtnRecuperar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,RecuperarContrasenia.class);
startActivity(intent);
}
});
mBtnRegistrar = (Button) findViewById(R.id.btnRegistrar);
mBtnRegistrar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,RegistrarUsuario.class);
startActivity(intent);
}
});
mLoginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences preference = getSharedPreferences("Reg",MODE_PRIVATE);
String username = mUsername.getText().toString();
String password = mPassword.getText().toString();
String userDetails = preference.getString(username + password + "data","No information on that user.");
SharedPreferences.Editor editor = preference.edit();
editor.putString("display",userDetails);
editor.commit();
if(mUsername.getText().toString().trim().length() == 0 && mPassword.getText().toString().trim().length() == 0 ){
Toast.makeText(MainActivity.this, "Los campos estan vacios", Toast.LENGTH_SHORT).show();
}else
{
if(mUsername.getText().toString().trim().equals(username) && mPassword.getText().toString().trim().equals(password)){
Toast.makeText(MainActivity.this, "Bienvenido", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MainActivity.this,PantallaPrincipal.class);
startActivity(intent);
}else{
Toast.makeText(MainActivity.this, "Los campos son incorrectos", Toast.LENGTH_SHORT).show();
}
}
}
});
}
}
i dont know what im missing that it dont verify the user if exists or login with the credentials i make in RegisterActivity.class
thanks
You are never retrieving the username and password from SharedPreferences. And at the end you are checking the information the user puts in the TextEdits against itself so the validation always returns true to any non empty value.
Change this:
SharedPreferences preference = getSharedPreferences("Reg",MODE_PRIVATE);
String username = mUsername.getText().toString();
String password = mPassword.getText().toString();
To this:
SharedPreferences preference = getSharedPreferences("Reg",MODE_PRIVATE);
String username = preference.getString("Username", "");
String password = preference.getString("Password", "");

How to: store image in sdcard, store and get imagepath in sharedpreferences for Profile Pic

Profile pic can be selected and set for a while but what we generally want (first object) is when user re-launch that page, there should be an image previously set by the user and if user has not set that image, there should be default image. I have used sharedpreferences for text views but it is said that for the image views, generally it is good practice to store the selected image first in sdcard, then get that Uri, make it string and then use it for sharedpreferences. i dont know if it can be done through onPause and onResume as well! if it is so, then which way should be prefer? and How to do that? Another thing is (Second object) i have an activity namely user profile where i want to inflate the data (Here, profile pic selected by the user) from edit profile activity. Here is the same case as of edit profile where if the user have not set custom profile pic then there should be default pic. Following is my edit profile activity:
public class EditUserProfile extends AppCompatActivity {
private CoordinatorLayout coordinatorLayout;
public static final String Uimage = "Uimage";
public static final String Name = "nameKey";
public static final String UContact = "UContact";
public static final String Uemail = "Uemail";
private TextInputLayout inputLayoutName, inputLayoutEmail, inputLayoutContact;
private EditText usernameTextView, userEmailTextView, userContactTextView;
private ImageView userImageView;
SharedPreferences sharedpreferences;
private int PICK_IMAGE_REQUEST = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_user_profile);
Toolbar userProfileToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(userProfileToolbar);
inputLayoutName = (TextInputLayout) findViewById(R.id.input_layout_username);
inputLayoutEmail = (TextInputLayout) findViewById(R.id.input_layout_useremail);
inputLayoutContact = (TextInputLayout) findViewById(R.id.input_layout_usercontact);
userImageView = (ImageView) findViewById(R.id.userImage );
usernameTextView = (EditText) findViewById(R.id.username);
userContactTextView = (EditText) findViewById(R.id.usercontact);
userEmailTextView = (EditText) findViewById(R.id.useremail);
Button btnSave = (Button) findViewById(R.id.action_save);
sharedpreferences = getSharedPreferences(Uimage, Context.MODE_PRIVATE);
sharedpreferences = getSharedPreferences(Name, Context.MODE_PRIVATE);
sharedpreferences = getSharedPreferences(UContact, Context.MODE_PRIVATE);
sharedpreferences = getSharedPreferences(Uemail, Context.MODE_PRIVATE);
if (sharedpreferences.contains(Name)) {
usernameTextView.setText(sharedpreferences.getString(Name, ""));
}
if (sharedpreferences.contains(UContact)) {
userContactTextView.setText(sharedpreferences.getString(UContact, ""));
}
if (sharedpreferences.contains(Uemail)) {
userEmailTextView.setText(sharedpreferences.getString(Uemail, ""));
}
usernameTextView.addTextChangedListener(new MyTextWatcher(usernameTextView));
userEmailTextView.addTextChangedListener(new MyTextWatcher(userEmailTextView));
userContactTextView.addTextChangedListener(new MyTextWatcher(userContactTextView));
coordinatorLayout = (CoordinatorLayout) findViewById(R.id
.coordinatorLayout);
final ImageButton button = (ImageButton) findViewById(R.id.editImage);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
Intent intent = new Intent();
// Show only images, no videos or anything else
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
// Always show the chooser (if there are multiple options available)
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri uri = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
// Log.d(TAG, String.valueOf(bitmap));
userImageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* Validating form
*/
private boolean submitForm() {
if (!validateName()) {
return false;
}
if (!validateContact()) {
return false;
}
if (!validateEmail()) {
return false;
}
Snackbar snackbar = Snackbar
.make(coordinatorLayout, "Saved!", Snackbar.LENGTH_LONG);
snackbar.show();
return true;
}
private boolean validateName() {
if (usernameTextView.getText().toString().trim().isEmpty()) {
inputLayoutName.setError(getString(R.string.err_msg_name));
requestFocus(usernameTextView);
return false;
} else {
inputLayoutName.setError(null);
}
return true;
}
private boolean validateEmail() {
String email = userEmailTextView.getText().toString().trim();
if (email.isEmpty() || !isValidEmail(email)) {
inputLayoutEmail.setError(getString(R.string.err_msg_email));
requestFocus(userEmailTextView);
return false;
} else {
inputLayoutEmail.setError(null);
}
return true;
}
private boolean validateContact() {
if (userContactTextView.getText().toString().trim().isEmpty()) {
inputLayoutContact.setError(getString(R.string.err_msg_contact));
requestFocus(userContactTextView);
return false;
} else {
inputLayoutContact.setError(null);
}
return true;
}
private static boolean isValidEmail(String email) {
return !TextUtils.isEmpty(email) && android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
private void requestFocus(View view) {
if (view.requestFocus()) {
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
}
private class MyTextWatcher implements TextWatcher {
private View view;
private MyTextWatcher(View view) {
this.view = view;
}
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
public void afterTextChanged(Editable editable) {
switch (view.getId()) {
case R.id.username:
validateName();
break;
case R.id.useremail:
validateEmail();
break;
case R.id.usercontact:
validateContact();
break;
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.editprofile_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_save:
if (!submitForm()){
return false;
}
TextView usernameTextView = (TextView) findViewById(R.id.username);
String usernameString = usernameTextView.getText().toString();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, usernameString);
editor.apply();
TextView ucontactTV = (TextView) findViewById(R.id.usercontact);
String uContactS = ucontactTV.getText().toString();
editor.putString(UContact, uContactS);
editor.apply();
TextView uEmailTV = (TextView) findViewById(R.id.useremail);
String uEmailS = uEmailTV.getText().toString();
editor.putString(Uemail, uEmailS);
editor.apply();
Snackbar snackbar = Snackbar
.make(coordinatorLayout, "Saved!", Snackbar.LENGTH_LONG);
snackbar.show();
Intent userProfileIntent = new Intent(EditUserProfile.this, UserProfile.class);
userProfileIntent.putExtra(Name, usernameString);
userProfileIntent.putExtra(UContact, uContactS);
userProfileIntent.putExtra(Uemail, uEmailS);
setResult(RESULT_OK, userProfileIntent);
finish();
}
return true;
}
}
Following is the user profile activity where i want to inflate default or custom profile pic from edit profile activity as same as i am able to inflate rest of text views:
public class UserProfile extends AppCompatActivity {
SharedPreferences sharedpreferences;
public static final String Uimage = "Uimage";
public static final String Name = "nameKey";
public static final String UContact = "UContact";
public static final String Uemail = "Uemail";
public static final int Edit_Profile = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_profile);
Toolbar userProfileToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(userProfileToolbar);
sharedpreferences = getSharedPreferences(Uimage, MODE_PRIVATE);
sharedpreferences = getSharedPreferences(Name, MODE_PRIVATE);
sharedpreferences = getSharedPreferences(UContact, MODE_PRIVATE);
sharedpreferences = getSharedPreferences(Uemail, MODE_PRIVATE);
displayMessage(sharedpreferences.getString(Name, ""));
displayUContact(sharedpreferences.getString(UContact, ""));
displayUEmail(sharedpreferences.getString(Uemail, ""));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.userprofile_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_editProfile:
Intent userProfileIntent = new Intent(UserProfile.this, EditUserProfile.class);
startActivityForResult(userProfileIntent, Edit_Profile);
return true;
}
return true;
}
// Call Back method to get the Message form other Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case Edit_Profile:
if (resultCode == RESULT_OK) {
String name = data.getStringExtra(Name);
String Result_UContact = data.getStringExtra(UContact);
String Result_UEmail = data.getStringExtra(Uemail);
displayMessage(name);
displayUContact(Result_UContact);
displayUEmail(Result_UEmail);
}
break;
}
}
public void displayMessage(String message) {
TextView usernameTextView = (TextView) findViewById(R.id.importProfile);
usernameTextView.setText(message);
}
public void displayUContact(String contact) {
TextView userContactTextView = (TextView) findViewById(R.id.importContact);
userContactTextView.setText(contact);
}
public void displayUEmail(String email) {
TextView userEmailTextView = (TextView) findViewById(R.id.importEmail);
userEmailTextView.setText(email);
}
}
Please consider that i have no experience in programming, coding or android development and i have just started to learn that!
You are right. You can store the image in your sd card and use the uri to load the image subsequently.
You can consider to save the image uri in the stored preference. With that you will just need to handle two cases.
In your onCreate() method
- Check if the image uri is valid (image exist)
- If it does, load it and make it the display image
- If it is missing, load the default image
* Alternatively, you can set the default image as the image for the imageview
Whenever the user updates the image
- Store the image into the sd card
- Update your shared preference
As such, you should not need to handle these in your onPause() and onResume() methods.
Hope it helps!
I have no much timer to write the entire answer, but here is how to store some Strings into the application shared Preferences:
1. storing some strings, it makes sense to store them when your "save"-button is clicked:
// assume a,b,c are strings with the information from ur edittexts to be saved:
String a,b,c;
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sp.edit();
editor.putString("namekey",a);
editor.putString("UContact", b);
editor.putString("UEmail", c);
editor.commit();
now these 3 things are saved.
2. loading these values (e.g. in ur onCreate() method after setting the content):
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
// check if the namevalues "namekey", "UContact", "UEmail" have values saved in the sharedPreferences. If not, load defaultvalue
String user_name = sp.getString("namekey", "no name entered yet");
String user_email = sp.getString("UEmail", "no email entered yet");
String user_contact = sp.getString("UContact", "no Contact entered yet");
displayMessage(user_name);
displayUContact(user_contact);
displayUEmail(user_email);
Loading a value from the sharedPreferences always needs a 2nd parameter, which will be the result when there is nothing saved for this key. For example, if your application is started for the first time, and the user did not have entered anything in the edittexts, then "no name entered yet", and so on are loaded from the sharedPreferences.
and.. thats it so far.
Why did i not provide information on how to store a bitmap in the sharedPreferences?
- sharedPreferences can only store basic Types such as Float, Integer, String, Boolean
- You could save the image into the sd card, but remember: not every device is using a sd card. If your application uses the camera-intent instead, your foto is already saved in the gallery automatically. You can store this path as a String in the sharedPrefs.
We can have method to retrieve the Uri for selected image as below:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri uri = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
// CALL THIS METHOD TO GET THE ACTUAL PATH
File finalFile = new File(getRealPathFromURI(uri));
outputFileUri = Uri.fromFile(finalFile);
stringUri = outputFileUri.toString();
// Log.d(TAG, String.valueOf(bitmap));
userImageView.setImageBitmap(bitmap);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Uimage, stringUri);
editor.apply();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public String getRealPathFromURI(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
So now we have String that represents or has been stored with value of Uri for our selected image.
Next is to use this string for sharedpreferences as below:
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Uimage, stringUri);
editor.apply();
Uimage is the key and it has string value stringUri with it! Each time user change the profile pic, we will have updated Uimage and associated stringUri at the same time.
Now, in onCreate method, we will check if there is sharedpreferences available with this value and if so, then we want to display the selected image. It should be noted here that sharedpreferences is used to save and keep the primitive data across re-launching of the app. Editor.putString is used to store some value and sharedpreferences.getString is used to read that value.
if (sharedpreferences.contains(Uimage)){
String imagepath = sharedpreferences.getString(Uimage, "");
uriString = Uri.parse(imagepath);
userImageView.setImageURI(uriString);
}
uriString is Uri!
And it worked!
Next is to send this profile pic to the user profile activity. We will use intent to send the selected pic to user profile activity and sharedpreferences in onCreate method of user profile activity to save and keep that pic there across re-launch as below:
1. Sending pic to the user profile activity using intent in edit profile activity as below:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_save:
Snackbar snackbar = Snackbar
.make(coordinatorLayout, "Saved!", Snackbar.LENGTH_LONG);
snackbar.show();
Intent userProfileIntent = new Intent(EditUserProfile.this, UserProfile.class);
if (sharedpreferences.contains(stringUri)){
userProfileIntent.putExtra(Uimage, stringUri);
}
setResult(RESULT_OK, userProfileIntent);
finish();
}
return true;
}
….and read and handle this intent at user profile activity as below:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case Edit_Profile:
if (resultCode == RESULT_OK) {
String imageIntent = data.getStringExtra(Uimage);
displayUimage(imageIntent);
}
break;
}
}
Where:
public void displayUimage (String imageString){
ImageView importImage = (ImageView) findViewById(R.id.importImage);
imageString = sharedpreferences.getString(Uimage, "");
uriString = Uri.parse(imageString);
importImage.setImageURI(uriString);
}
Intent is used to get the pic from edit profile activity to user profile activity. If we press back or exit the app and re-launch it, user profile activity will lose that pic. In order to save and keep that pic there across re-launching of app, we need to use sharedpreferences there.
Save and Keep that pic there at user profile activity using sharedpreferences as below:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_profile);
Toolbar userProfileToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(userProfileToolbar);
importImage = (ImageView) findViewById(R.id.importImage);
importImage.setImageResource(R.drawable.defaultprofilepic);
sharedpreferences = getSharedPreferences(Uimage, MODE_PRIVATE);
if (sharedpreferences.contains(Uimage)){
String imagepath = sharedpreferences.getString(Uimage, "");
uriString = Uri.parse(imagepath);
importImage.setImageURI(uriString);
}
}
We first have initialized our importImage with the default one but then we check if there is sharedpreferences with special key is available.
That simply means, if the sharedpreferences contains Uimage (which is possible only if the user have changed the profile pic and the Uimage will be always updated as soon as user change the profile pic) then we will get Uri for that image and set it to importImage so that we will have same profile pic as user have selected at edit profile activity.
Below is the complete Edit profile activity:
public class EditUserProfile extends AppCompatActivity {
private CoordinatorLayout coordinatorLayout;
public static final String Uimage = "Uimagepath";
public static final String Name = "nameKey";
public static final String UContact = "UContact";
public static final String Uemail = "Uemail";
private TextInputLayout inputLayoutName, inputLayoutEmail, inputLayoutContact;
private EditText usernameTextView, userEmailTextView, userContactTextView;
private ImageView userImageView;
SharedPreferences sharedpreferences;
private int PICK_IMAGE_REQUEST = 1;
String stringUri;
Uri outputFileUri;
Uri uriString;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_user_profile);
Toolbar userProfileToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(userProfileToolbar);
inputLayoutName = (TextInputLayout) findViewById(R.id.input_layout_username);
inputLayoutEmail = (TextInputLayout) findViewById(R.id.input_layout_useremail);
inputLayoutContact = (TextInputLayout) findViewById(R.id.input_layout_usercontact);
userImageView = (ImageView) findViewById(R.id.userImage );
usernameTextView = (EditText) findViewById(R.id.username);
userContactTextView = (EditText) findViewById(R.id.usercontact);
userEmailTextView = (EditText) findViewById(R.id.useremail);
Button btnSave = (Button) findViewById(R.id.action_save);
sharedpreferences = getSharedPreferences(Uimage, Context.MODE_PRIVATE);
sharedpreferences = getSharedPreferences(Name, Context.MODE_PRIVATE);
sharedpreferences = getSharedPreferences(UContact, Context.MODE_PRIVATE);
sharedpreferences = getSharedPreferences(Uemail, Context.MODE_PRIVATE);
if (sharedpreferences.contains(Uimage)){
String imagepath = sharedpreferences.getString(Uimage, "");
uriString = Uri.parse(imagepath);
userImageView.setImageURI(uriString);
}
if (sharedpreferences.contains(Name)) {
usernameTextView.setText(sharedpreferences.getString(Name, ""));
}
if (sharedpreferences.contains(UContact)) {
userContactTextView.setText(sharedpreferences.getString(UContact, ""));
}
if (sharedpreferences.contains(Uemail)) {
userEmailTextView.setText(sharedpreferences.getString(Uemail, ""));
}
usernameTextView.addTextChangedListener(new MyTextWatcher(usernameTextView));
userEmailTextView.addTextChangedListener(new MyTextWatcher(userEmailTextView));
userContactTextView.addTextChangedListener(new MyTextWatcher(userContactTextView));
coordinatorLayout = (CoordinatorLayout) findViewById(R.id
.coordinatorLayout);
final ImageButton button = (ImageButton) findViewById(R.id.editImage);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
Intent intent = new Intent();
// Show only images, no videos or anything else
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
// Always show the chooser (if there are multiple options available)
startActivityForResult(Intent.createChooser(intent, "Select Pic from"), PICK_IMAGE_REQUEST);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri uri = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
// CALL THIS METHOD TO GET THE ACTUAL PATH
File finalFile = new File(getRealPathFromURI(uri));
outputFileUri = Uri.fromFile(finalFile);
stringUri = outputFileUri.toString();
// Log.d(TAG, String.valueOf(bitmap));
userImageView.setImageBitmap(bitmap);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Uimage, stringUri);
editor.apply();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public String getRealPathFromURI(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
/**
* Validating form
*/
private boolean submitForm() {
if (!validateName()) {
return false;
}
if (!validateContact()) {
return false;
}
if (!validateEmail()) {
return false;
}
Snackbar snackbar = Snackbar
.make(coordinatorLayout, "Saved!", Snackbar.LENGTH_LONG);
snackbar.show();
return true;
}
private boolean validateName() {
if (usernameTextView.getText().toString().trim().isEmpty()) {
inputLayoutName.setError(getString(R.string.err_msg_name));
requestFocus(usernameTextView);
return false;
} else {
inputLayoutName.setError(null);
}
return true;
}
private boolean validateEmail() {
String email = userEmailTextView.getText().toString().trim();
if (email.isEmpty() || !isValidEmail(email)) {
inputLayoutEmail.setError(getString(R.string.err_msg_email));
requestFocus(userEmailTextView);
return false;
} else {
inputLayoutEmail.setError(null);
}
return true;
}
private boolean validateContact() {
if (userContactTextView.getText().toString().trim().isEmpty()) {
inputLayoutContact.setError(getString(R.string.err_msg_contact));
requestFocus(userContactTextView);
return false;
} else {
inputLayoutContact.setError(null);
}
return true;
}
private static boolean isValidEmail(String email) {
return !TextUtils.isEmpty(email) && android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
private void requestFocus(View view) {
if (view.requestFocus()) {
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
}
private class MyTextWatcher implements TextWatcher {
private View view;
private MyTextWatcher(View view) {
this.view = view;
}
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
public void afterTextChanged(Editable editable) {
switch (view.getId()) {
case R.id.username:
validateName();
break;
case R.id.useremail:
validateEmail();
break;
case R.id.usercontact:
validateContact();
break;
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.editprofile_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_save:
if (!submitForm()){
return false;
}
SharedPreferences.Editor editor = sharedpreferences.edit();
TextView usernameTextView = (TextView) findViewById(R.id.username);
String usernameString = usernameTextView.getText().toString();
editor.putString(Name, usernameString);
editor.apply();
TextView ucontactTV = (TextView) findViewById(R.id.usercontact);
String uContactS = ucontactTV.getText().toString();
editor.putString(UContact, uContactS);
editor.apply();
TextView uEmailTV = (TextView) findViewById(R.id.useremail);
String uEmailS = uEmailTV.getText().toString();
editor.putString(Uemail, uEmailS);
editor.apply();
Snackbar snackbar = Snackbar
.make(coordinatorLayout, "Saved!", Snackbar.LENGTH_LONG);
snackbar.show();
Intent userProfileIntent = new Intent(EditUserProfile.this, UserProfile.class);
userProfileIntent.putExtra(Name, usernameString);
userProfileIntent.putExtra(UContact, uContactS);
userProfileIntent.putExtra(Uemail, uEmailS);
if (sharedpreferences.contains(stringUri)){
userProfileIntent.putExtra(Uimage, stringUri);
}
setResult(RESULT_OK, userProfileIntent);
finish();
}
return true;
}
}
Below is the complete User Profile Activity that shows saved profile:
public class UserProfile extends AppCompatActivity {
SharedPreferences sharedpreferences;
public static final String Uimage = "Uimagepath";
public static final String Name = "nameKey";
public static final String UContact = "UContact";
public static final String Uemail = "Uemail";
ImageView importImage;
Uri uriString;
public static final int Edit_Profile = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_profile);
Toolbar userProfileToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(userProfileToolbar);
importImage = (ImageView) findViewById(R.id.importImage);
importImage.setImageResource(R.drawable.defaultprofilepic);
sharedpreferences = getSharedPreferences(Uimage, MODE_PRIVATE);
sharedpreferences = getSharedPreferences(Name, MODE_PRIVATE);
sharedpreferences = getSharedPreferences(UContact, MODE_PRIVATE);
sharedpreferences = getSharedPreferences(Uemail, MODE_PRIVATE);
if (sharedpreferences.contains(Uimage)){
String imagepath = sharedpreferences.getString(Uimage, "");
uriString = Uri.parse(imagepath);
importImage.setImageURI(uriString);
}
displayMessage(sharedpreferences.getString(Name, ""));
displayUContact(sharedpreferences.getString(UContact, ""));
displayUEmail(sharedpreferences.getString(Uemail, ""));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.userprofile_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_editProfile:
Intent userProfileIntent = new Intent(UserProfile.this, EditUserProfile.class);
startActivityForResult(userProfileIntent, Edit_Profile);
return true;
case R.id.action_dos:
Intent coffeeIntent = new Intent(UserProfile.this, Dos.class);
UserProfile.this.startActivity(coffeeIntent);
return true;
case R.id.action_13:
Intent teaIntent = new Intent(UserProfile.this, thirteen.class);
UserProfile.this.startActivity(teaIntent);
return true;
}
return true;
}
// Call Back method to get the Message form other Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case Edit_Profile:
if (resultCode == RESULT_OK) {
String imageIntent = data.getStringExtra(Uimage);
String name = data.getStringExtra(Name);
String Result_UContact = data.getStringExtra(UContact);
String Result_UEmail = data.getStringExtra(Uemail);
displayUimage(imageIntent);
displayMessage(name);
displayUContact(Result_UContact);
displayUEmail(Result_UEmail);
}
break;
}
}
public void displayMessage(String message) {
TextView usernameTextView = (TextView) findViewById(R.id.importProfile);
usernameTextView.setText(message);
}
public void displayUContact(String contact) {
TextView userContactTextView = (TextView) findViewById(R.id.importContact);
userContactTextView.setText(contact);
}
public void displayUEmail(String email) {
TextView userEmailTextView = (TextView) findViewById(R.id.importEmail);
userEmailTextView.setText(email);
}
public void displayUimage (String imageString){
ImageView importImage = (ImageView) findViewById(R.id.importImage);
imageString = sharedpreferences.getString(Uimage, "");
uriString = Uri.parse(imageString);
importImage.setImageURI(uriString);
}
}
Hope this helps someone!

Sinch mobile verification Skipping

I have made an app in which first the user verifies its number with the help of sinch verification and then after succesfull verification it goes to the gameactivity but the problem is that every time the user opens the app he or she has to verify again which is a very bad out come.
i dont how o skip the verification process after again opening the app
Main Activity
public class MainActivity extends Activity {
public static final String SMS = "sms";
public static final String FLASHCALL = "flashcall";
public static final String INTENT_PHONENUMBER = "phonenumber";
public static final String INTENT_METHOD = "method";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TelephonyManager manager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
TextView phoneNumber = (TextView) findViewById(R.id.phoneNumber);
phoneNumber.setText(manager.getLine1Number());
}
private void openActivity(String phoneNumber, String method) {
Intent verification = new Intent(this, VerificationActivity.class);
verification.putExtra(INTENT_PHONENUMBER, phoneNumber);
verification.putExtra(INTENT_METHOD, method);
startActivity(verification);
}
private boolean checkInput() {
TextView phoneNumber = (TextView) findViewById(R.id.phoneNumber);
if (phoneNumber.getText().toString().isEmpty()) {
Toast.makeText(this, "Please input a phone number.", Toast.LENGTH_LONG).show();
return false;
}
return true;
}
public void onButtonClicked(View view) {
if (checkInput()) {
TextView phoneNumber = (TextView) findViewById(R.id.phoneNumber);
if (view == findViewById(R.id.smsVerificationButton)) {
openActivity(phoneNumber.getText().toString(), SMS);
} else if (view == findViewById(R.id.callVerificationButton)) {
openActivity(phoneNumber.getText().toString(), FLASHCALL);
}
}
}
}
Verification Activity
public class VerificationActivity extends Activity {
private static final String TAG = Verification.class.getSimpleName();
private final String APPLICATION_KEY = "af23************************";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_verification);
ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressIndicator);
progressBar.setVisibility(View.VISIBLE);
Intent intent = getIntent();
if (intent != null) {
String phoneNumber = intent.getStringExtra(MainActivity.INTENT_PHONENUMBER);
String method = intent.getStringExtra(MainActivity.INTENT_METHOD);
TextView phoneText = (TextView) findViewById(R.id.numberText);
phoneText.setText(phoneNumber);
createVerification(phoneNumber, method);
}
}
void createVerification(String phoneNumber, String method) {
Config config = SinchVerification.config().applicationKey(APPLICATION_KEY).context(getApplicationContext())
.build();
VerificationListener listener = new MyVerificationListener();
Verification verification;
if (method.equalsIgnoreCase(MainActivity.SMS)) {
verification = SinchVerification.createSmsVerification(config, phoneNumber, listener);
} else {
TextView messageText = (TextView) findViewById(R.id.textView);
messageText.setText(R.string.flashcalling);
verification = SinchVerification.createFlashCallVerification(config, phoneNumber, listener);
}
verification.initiate();
}
class MyVerificationListener implements VerificationListener {
#Override
public void onInitiated() {
Log.d(TAG, "Initialized!");
}
#Override
public void onInitiationFailed(Exception exception) {
Log.e(TAG, "Verification initialization failed: " + exception.getMessage());
hideProgress(R.string.failed, false);
}
#Override
public void onVerified() {
Log.d(TAG, "Verified!");
hideProgress(R.string.verified, true);
}
#Override
public void onVerificationFailed(Exception exception) {
Log.e(TAG, "Verification failed: " + exception.getMessage());
hideProgress(R.string.failed, false);
}
}
void hideProgress(int message, boolean success) {
if (success) {
ImageView checkMark = (ImageView) findViewById(R.id.checkmarkImage);
checkMark.setVisibility(View.VISIBLE);
}
ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressIndicator);
progressBar.setVisibility(View.INVISIBLE);
TextView progressText = (TextView) findViewById(R.id.progressText);
progressText.setVisibility(View.INVISIBLE);
TextView messageText = (TextView) findViewById(R.id.textView);
messageText.setText(message);
}
}
I just want that on re opening verification process should not be again called.
You can use SharedPreferences. add a key to your SharedPreferences object and initialize with value 0. You can do something like below
SharedPrefences prefences = PrefenceManager.getSharedPreferences("TAG",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
Now on successfull verification :
preferences.putInt("key",1);
so on next launch check for this key value, if its 1 skip the VerificationActivity and start GameActivtiy i.e
int value = preferences.getInt("key",0);
if(value == 0){
// Verify
}else{
// Skip Verification
}

Categories

Resources