how to save android SharedPreferences using retrofit and get id - android

I made a validation to log in using retrofit, and I have already placed sharedpreferences in the login class and in the second class. can log in, but I can't get the user ID when logging in. There have been various ways but it didn't work. anyone know the solution?
ValidationLogin Class
public void LoginUser() {
//membuat progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
pDialog.setMessage("Tunggu proses login ...");
pDialog.show();
//mengambil data dari edittext
final String username = txtusername.getText().toString();
String password = txtpassword.getText().toString();
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(50, TimeUnit.SECONDS)
.readTimeout(50, TimeUnit.SECONDS).build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BuildConfig.BASE_URL).client(client)
.addConverterFactory(GsonConverterFactory.create(new Gson())).build();
RequestInterface api = retrofit.create(RequestInterface.class);
Call<ResponseLogin> call = api.login_member(id, username , password);
call.enqueue(new Callback<ResponseLogin>() {
#Override
public void onResponse(Call<ResponseLogin> call, Response<ResponseLogin> response) {
pDialog.dismiss();
if(response.isSuccessful()){
if(response.body().getResult() != null){
// menyimpan login ke session
sharedpreferences = getSharedPreferences(my_shared_preferences, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean(session_status, true);
editor.putString(TAG_ID, id);
editor.putString(TAG_EMAIL, email);
editor.apply();
//login start main activity
Intent intent = new Intent(LoginUser.this, Second.class);
Toast.makeText(LoginUser.this, "Selamat datang "+username, Toast.LENGTH_SHORT).show();
// Toast.makeText(LoginUser.this, "Selamat datang "+id, Toast.LENGTH_SHORT).show();
intent.putExtra("email", email);
intent.putExtra("id", id);
intent.putExtra("username", username);
intent.putExtra(TAG_EMAIL, email);
startActivity(intent);
finish();
} else {
Toast.makeText(LoginUser.this, "The username or password is incorrect", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(LoginUser.this, "Error! Please try again!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<ResponseLogin> call, Throwable t) {
t.printStackTrace();
pDialog.dismiss();
Toast.makeText(LoginUser.this, "Koneksi internet terputus.", Toast.LENGTH_SHORT).show();
}
});
}
onCreate
// Cek session login jika TRUE maka langsung buka MainActivity
sharedpreferences = getSharedPreferences(my_shared_preferences, Context.MODE_PRIVATE);
session = sharedpreferences.getBoolean(session_status, false);
id = sharedpreferences.getString(TAG_ID, "id tidak ditemukan");
email = sharedpreferences.getString(TAG_EMAIL, "email tidak ditemukan");
if (session) {
Intent intent = new Intent(LoginUser.this, MenuUtama.class);
intent.putExtra(TAG_ID, id);
intent.putExtra(TAG_EMAIL, email);
intent.putExtra(TAG_USERNAME, username);
finish();
startActivity(intent);
}
btnLogin = findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String username = txtusername.getText().toString();
String password = txtpassword.getText().toString();
if (isEmpty(username))
txtusername.setError("Username harap diisi");
else if (isEmpty(password))
txtpassword.setError("Password harap diisi");
else
LoginUser();
//Intent intent = new Intent(LoginUser.this, Second.class);
///startActivity(intent);
}
});
Second Class
sharedpreferences = getApplication().getSharedPreferences(ValidationLogin.my_shared_preferences, Context.MODE_PRIVATE);
id = sharedpreferences.getString("id", "0");
Toast.makeText(getApplication(), "ini id ke-"+ id, Toast.LENGTH_SHORT).show();
And this respon json, I was struggling to get ID
{
"status": 200,
"reason": "OK",
"success": true,
"message": null,
"result": "eyJ0eXAiOiJKV1QiLCJhbGciOiJITUFDLVNIQTI1NiJ9.eyJpZCI6IjQ5OSIsImVtYWlsIjoiYmlzbWlsbGFoYmlzYUBleGFtcGxlLmNvbSIsIm1zaXNkbiI6IjA3OTc5Nzg0NjQ5NCIsInVzZXJuYW1lIjoiYmlzbWlsbGFoYmlzYSIsInZlcmlmaWVkTWVtYmVyIjpudWxsLCJwcm9maWxlIjp7ImlkIjoiMzE2IiwiaWRfZ2VvZGlyZWN0b3J5IjpudWxsLCJmdWxsbmFtZSI6ImJpc21pbGxhaGJpc2EiLCJudW1iZXIiOiIyNzQyNDciLCJpbWFnZSI6Imh0dHBzOlwvXC9kZW1vLmtyZWRpdGltcGlhbi5jb21cL3N0b3JhZ2VcL2ltYWdlc1wvZGVmYXVsdFwvYXZhdGFyLmpwZyIsInJlY29yZCI6eyJzdGF0dXMiOiJQVUJMSVNIIiwiY3JlYXRlIjp7InVzZXIiOm51bGwsInRpbWVzdGFtcCI6eyJkYXRlIjoiMjAxOS0xMi0wMyAxNTowODozMi4wMDAwMDAiLCJ0aW1lem9uZV90eXBlIjozLCJ0aW1lem9uZSI6IkFzaWFcL0pha2FydGEifX0sInVwZGF0ZSI6eyJ1c2VyIjpudWxsLCJ0aW1lc3RhbXAiOm51bGx9fSwibWV0YWRhdGEiOnsidXNlcm5hbWUiOiJiaXNtaWxsYWhiaXNhIiwiZW1haWwiOiJiaXNtaWxsYWhiaXNhQGV4YW1wbGUuY29tIiwicGhvbmUiOiIwNzk3OTc4NDY0OTQifSwic3RhdGlzdGljIjpudWxsfX0.zIEhdU5MyNjReG_9_661FWf0_R5eZuJweyl0JNFd7X0"
}

Related

How to Retrieve Shared Preferences in Same Activity, It comes Empty?

In my application's login screen, i am fetching a JSON response into the shared preferences in my retrofit2 onResponse method. I get everything as correct from the database and putting as correctly into the shared preferences. I am getting an User_Role from db as string, then based on User_Role, i am directing the user to according activity. I need to reach that User_Role in case R.id.Login: step. In my Logcat i see my response is as i want. I check with Toast after i commit preferences, if i can manage to put preferences correctly. Yes it is writes to screen response.success Organizator. So the only problem i can not retrieve it. Please help.
Because of everything works correctly in my apicall(because i checked every step with Toast.makeText.show(); on screen) i am only putting my LoginActivity.class code below,
LoginActivity.class :
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
Button bSignUp, bLogin;
EditText etPassword, etEmail;
private ProgressDialog progressDialog;
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
bSignUp = (Button) findViewById(R.id.bSignUp);
bLogin = (Button) findViewById(R.id.bLogin);
bSignUp.setOnClickListener((View.OnClickListener) this);
bLogin.setOnClickListener((View.OnClickListener) this);
etPassword = (EditText) findViewById(R.id.etPassword);
etEmail = (EditText) findViewById(R.id.etEmail);
progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Logging in");
progressDialog.setMessage("Please wait ....");
bLogin.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.bSignUp:
Intent SignUpIntent = new Intent(this, SignUpActivity.class);
startActivity(SignUpIntent);
break;
case R.id.bLogin:
String email = etEmail.getText().toString();
String password = etPassword.getText().toString();
if (!email.isEmpty() && !password.isEmpty()) {
progressDialog.show();
loginProcess(email, password);
//Here i need to obtain SharedPreferences that i filled in onResponse Method. It goes directly wrong email or password statement. Because of can't retrieve settings.getString("User_Role","")
SharedPreferences settings = getSharedPreferences("Pref", MODE_PRIVATE);
String userRole = settings.getString("User_Role","");
Toast.makeText(LoginActivity.this, userRole, Toast.LENGTH_SHORT).show();
if (userRole.equals("Organizator")) {
intent = new Intent(this, OrganizerHomeActivity.class);
startActivity(intent);
} else if(userRole.equals("Speaker") || userRole.equals("Listener")) {
intent = new Intent(this, UserHomeActivity.class);
startActivity(intent);
}
else{
Toast.makeText(LoginActivity.this, "Wrong email or password", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(LoginActivity.this, "Fields are empty", Toast.LENGTH_SHORT).show();
}
break;
default:
break;
}
}
private void loginProcess(String email, String password) {
LoginAPI loginAPI = RetrofitService.getClient().create(LoginAPI.class);
retrofit2.Call<UserList> call = loginAPI.loginUser(email,password);
call.enqueue(new Callback<UserList>(){
#Override
public void onResponse(Call<UserList> call, Response<UserList> response) {
if(response.isSuccessful()){
List<User> userLists = response.body().getUser();
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
//SharedPreferences settings = getSharedPreferences("Pref", MODE_PRIVATE);
SharedPreferences.Editor prefEditor = settings.edit();
prefEditor.putBoolean(Constants.IS_LOGGED_IN, true);
prefEditor.putString("UserName", userLists.get(0).getFirstName());
prefEditor.putString("SSN", userLists.get(0).getsSN());
prefEditor.putString("User_Role", userLists.get(0).getUserRole());
prefEditor.commit();
// In my Logcat i see my respnse is as i want, and i check with below Toast if i can manage to put preferences correctly. Yes it is writes to screen response.success Organizator. So there is no problem.
Toast.makeText(LoginActivity.this, "response.success "+settings.getString("User_Role",""), Toast.LENGTH_SHORT).show();
}
progressDialog.dismiss();
}
#Override
public void onFailure(Call<UserList> call, Throwable t) {
Toast.makeText(LoginActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
});
}
}
Put your SharedPreference logic after onResponse success. it's because it executes before your response get. that's why it empty. so Change code like this
private void checkMethod(){
SharedPreferences settings = getSharedPreferences("Pref", MODE_PRIVATE);
String userRole = settings.getString("User_Role","");
Toast.makeText(LoginActivity.this, userRole, Toast.LENGTH_SHORT).show();
if (userRole.equals("Organizator")) {
intent = new Intent(this, OrganizerHomeActivity.class);
startActivity(intent);
} else if(userRole.equals("Speaker") || userRole.equals("Listener")) {
intent = new Intent(this, UserHomeActivity.class);
startActivity(intent);
}
else{
Toast.makeText(LoginActivity.this, "Wrong email or password", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(LoginActivity.this, "Fields are empty", Toast.LENGTH_SHORT).show();
}
}
And Call this method from onResponse like below
public void onResponse(Call<UserList> call, Response<UserList> response) {
if(response.isSuccessful()){
List<User> userLists = response.body().getUser();
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
//SharedPreferences settings = getSharedPreferences("Pref", MODE_PRIVATE);
SharedPreferences.Editor prefEditor = settings.edit();
prefEditor.putBoolean(Constants.IS_LOGGED_IN, true);
prefEditor.putString("UserName", userLists.get(0).getFirstName());
prefEditor.putString("SSN", userLists.get(0).getsSN());
prefEditor.putString("User_Role", userLists.get(0).getUserRole());
prefEditor.commit();
// In my Logcat i see my respnse is as i want, and i check with below Toast if i can manage to put preferences correctly. Yes it is writes to screen response.success Organizator. So there is no problem.
Toast.makeText(LoginActivity.this, "response.success "+settings.getString("User_Role",""), Toast.LENGTH_SHORT).show();
checkMethod();
}
Try to start intent condition in the response method. No need to store value in shared preferences.

Login with facebook sdk shared preference and get information about user

i am developing an app where facebook login is there . i am trying to get user information and send that to my server.i am using sdk 4.i am trying to use shared preference to save info but i have no idea about shared preference . This is my facebook login activity . this is launcher activity.
public class LoginActivity extends AbsRuntimePermission {
private static final int REQUEST_Permission =10;
private TextView info;
private LoginButton loginButton;
private CallbackManager callbackManager;
private SparseIntArray mErrorString;
private Button facebook_button;
ProgressDialog progress;
private String facebook_id,f_name,m_name,l_name,gender,profile_image,full_name,email_id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//for permission in manifest file cause it is launch activity
requestAppPermissions(new String[]{
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.CALL_PHONE,
Manifest.permission.INTERNET},R.string.msg,REQUEST_Permission);
//facebook
info = (TextView) findViewById(R.id.info);
loginButton = (LoginButton) findViewById(R.id.login_button);
progress = new ProgressDialog(LoginActivity.this);
progress.setMessage(getResources().getString(R.string.please_wait_facebooklogin));
progress.setIndeterminate(false);
progress.setCancelable(false);
facebook_id=f_name=m_name=l_name=gender=profile_image=full_name=email_id="";
//facebook sdk
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
//register callback object for facebook result
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
progress.show();
Profile profile = Profile.getCurrentProfile();
if(profile != null){
facebook_id = profile.getId();
f_name=profile.getFirstName();
m_name=profile.getMiddleName();
l_name=profile.getLastName();
profile_image=profile.getProfilePictureUri(400,400).toString();
}
//show Toast
GraphRequest request =GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback(){
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
email_id = object.getString("email");
gender = object.getString("gender");
String Profile_name = object.getString("name");
long fb_id = object.getLong("id"); //use this for logout
//Starting a new activity using this information
Intent i = new Intent(LoginActivity.this, MainActivity.class);
i.putExtra("type", "facebook");
i.putExtra("Facebook_id", facebook_id);
i.putExtra("f_name", f_name);
i.putExtra("m_name", m_name);
i.putExtra("l_name", l_name);
i.putExtra("full_name", full_name);
i.putExtra("Profile_image", profile_image);
i.putExtra("email_id", email_id);
i.putExtra("gender", gender);
progress.dismiss();
startActivity(i);
finish();
}catch (JSONException e){
e.printStackTrace();
}
}
});
request.executeAsync();
}
#Override
public void onCancel() {
Toast.makeText(LoginActivity.this,getResources().getString(R.string.login_canceled_facebooklogin),Toast.LENGTH_SHORT).show();
progress.dismiss();
}
#Override
public void onError(FacebookException error) {
Toast.makeText(LoginActivity.this,getResources().getString(R.string.login_failed_facebooklogin),Toast.LENGTH_SHORT).show();
progress.dismiss();
}
});
//facebook button click
facebook_button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
LoginManager.getInstance().logInWithReadPermissions(LoginActivity.this, Arrays.asList("public_profile","user_friends","email"));
}
});
}
private void logoutFromFacebook(){
try{
if(AccessToken.getCurrentAccessToken()==null){
return;
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode,resultCode,data);
}
#Override
public void onPermissionGranted(int requestCode) {
//anything after permission Granted
Toast.makeText(getApplicationContext(),"Permission granted",Toast.LENGTH_LONG).show();
}
public void goTo(View view) {
Intent intent = new Intent(this, MainActivity.class);
this.startActivity(intent);
}
}
Android SharedPreferences allows us to store private primitive
application data in the form of key-value pair.For More details follow this.
To read from shared preference use something like this.
String dateFromSharedPreferences=getActivity().getPreferences(Context.MODE_PRIVATE);
sharedPref.getString("Username");
To save into shared preference
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("Username", YourUsername);
editor.putString("Password", YourPassword);
editor.apply();
You are passing the values from LoginActivity to MainActivity so code in MainActivity at onCreate function like following to get the passed values ans show in textview.
((TextView)findViewById(R.id.tv1)).setText(getIntent().getExtras().getString("full_name"));
((TextView)findViewById(R.id.tv2)).setText(getIntent().getExtras().getString("email_id"));
((TextView)findViewById(R.id.tv3)).setText(getIntent().getExtras().getString("gender"));
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
Write this code before going to intent.
sharedPreferences = getApplicationContext().getSharedPreferences("pref", MODE_PRIVATE);
editor = sharedPreferences.edit();
editor.putString("User_Name", f_name);
editor.putString("User_Email", email_id);
editor.apply();
I know this type of question so many answer but still i am give this question's answer, I hope some one got the help. It's easy if we create method to handle all data.
When receive facebook JSON object then after do as follow.
try {
Bundle bFacebookData = getFacebookData(object);
progressDialog.dismiss();
progressDialog.cancel();
setSessionData(bFacebookData);
}catch (JSONException e){
e.printStackTrace();
}
//here you can get all facebook data and store in bundle
private Bundle getFacebookData(JSONObject object)
{
try {
Bundle bundle = new Bundle();
//String id = object.getString("id");
try
{
URL profile_pic = new URL("https://graph.facebook.com/" + object.getString("id") + "/picture?width=200&height=150");
Log.i("profile_pic", profile_pic + "");
if (profile_pic.toString() != null)
{
bundle.putString("profile_pic", profile_pic.toString());
}
else
{
bundle.putString("profile_pic", "noProfilePic");
}
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
}
if (object.has("id"))
{
if (object.getString("id") != null)
{
bundle.putString("userId", object.getString("id"));
Log.i(TAG, "Info " + object.getString("id"));
}
else
{
bundle.putString("userId", "noUserId");
Log.i(TAG, "Info " + object.getString("id"));
}
}
if (object.has("first_name"))
{
if (object.getString("first_name") != null)
{
bundle.putString("first_name", object.getString("first_name"));
Log.i(TAG + "Info", object.getString("first_name"));
}
else
{
bundle.putString("first_name", "noFirstName");
Log.i(TAG + "Info", object.getString("first_name"));
}
}
if (object.has("last_name"))
{
if (object.getString("last_name") != null)
{
bundle.putString("last_name", object.getString("last_name"));
Log.i(TAG + "Info", object.getString("last_name"));
}
else
{
bundle.putString("last_name", "noLastName");
Log.i(TAG + "Info", object.getString("last_name"));
}
}
if (object.has("email"))
{
if (object.getString("email") != null)
{
bundle.putString("email", object.getString("email"));
Log.i(TAG + "Info", object.getString("email"));
}
else
{
bundle.putString("email", "noEmail");
Log.i(TAG + "Info", object.getString("email"));
}
}
//this is added dynamically
bundle.putString("phone", "noPhone");
if (object.has("gender"))
{
if (object.getString("gender") != null)
{
bundle.putString("gender", object.getString("gender"));
Log.i(TAG + "Info", object.getString("gender"));
}
else
{
bundle.putString("gender", "noGender");
Log.i(TAG + "Info", object.getString("gender"));
}
}
if (object.has("birthday"))
{
if (object.getString("birthday") != null)
{
bundle.putString("birthday", object.getString("birthday"));
Log.i(TAG + "Info", object.getString("birthday"));
}
else
{
bundle.putString("birthday", "noDateOfBirth");
Log.i(TAG + "Info", object.getString("birthday"));
}
}
if (object.has("location"))
{
if (object.getJSONObject("location").getString("name") != null)
{
bundle.putString("location", object.getJSONObject("location").getString("name"));
Log.i(TAG + "Info", object.getJSONObject("location").getString("name"));
}
else
{
bundle.putString("location", "noLocation");
Log.i(TAG + "Info", object.getJSONObject("location").getString("name"));
}
}
return bundle;
} catch (Exception e) {
e.printStackTrace();
} finally {
}
return null;
}
//here you can store data in SharedPreferences and start new activity
String userId = "", userEmail = "", userFirstName = "", userLastName = "",
userPhone = "", dateOfBirth = "", gender = "", profilePic = "";
private void setSessionData(Bundle bundle)
{
try
{
userId = bundle.getString("userId");
userEmail = bundle.getString("email");
userFirstName = bundle.getString("first_name");
userLastName = bundle.getString("last_name");
userPhone = bundle.getString("phone");
dateOfBirth = bundle.getString("birthday");
gender = bundle.getString("gender");
profilePic = bundle.getString("profile_pic");
if (userId !=null)
{
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("pref", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("userId", userId);
editor.putString("email", userEmail);
editor.putString("first_name", userFirstName);
editor.putString("last_name", userLastName);
editor.putString("phone", userPhone);
editor.putString("birthday", dateOfBirth);
editor.putString("gender", gender);
editor.putString("profile_pic", profilePic);
editor.apply();
Intent i = new Intent(activity, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(i);
}
else
{
//"Some thing went wrong Please try again"
}
}
catch (Exception e)
{
e.printStackTrach();
}
}
Your another class to receive data from SharedPreferences
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("pref", MODE_PRIVATE);
((TextView)findViewById(R.id.tv1)).setText(sharedPreferences.getString("first_name", ""));
((TextView)findViewById(R.id.tv2)).setText(sharedPreferences.getString("last_name", ""));

What is the probleme please ? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
this is all the code
public class LoginActivity extends Activity {
private static final String TAG = RegisterActivity.class.getSimpleName();
private Button btnLogin;
private Button btnLinkToRegister;
private EditText inputEmail;
private EditText inputPassword;
private ProgressDialog pDialog;
private SessionManager session;
private SQLiteHandler db;
String CK="admin";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
// SQLite database handler
db = new SQLiteHandler(getApplicationContext());
// Session manager
session = new SessionManager(getApplicationContext());
// Check if user is already logged in or not
if (session.isLoggedIn()) {
// User is already logged in. Take him to main activity
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String email = inputEmail.getText().toString().trim();
String password = inputPassword.getText().toString().trim();
// Check for empty data in the form
if (!email.isEmpty() && !password.isEmpty()) {
// login user
checkLogin(email, password);
} else {
// Prompt user to enter credentials
Toast.makeText(getApplicationContext(),
"Please enter the credentials!", Toast.LENGTH_LONG)
.show();
}
}
});
// Link to Register Screen
btnLinkToRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(i);
finish();
}
});
}
/**
* function to verify login details in mysql db
* */
private void checkLogin(final String email, final String password) {
// Tag used to cancel the request
String tag_string_req = "req_login";
pDialog.setMessage("Logging in ...");
showDialog();
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_LOGIN, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
// user successfully logged in
// Create login session
session.setLogin(true);
My problem is here, i'm using if(!(CK==uid)) it works but when CK==uid it doesn't work , String CK= admin and when i login with admin not a simple user the uid=admin too . i used Log.e to verify you can see my capture image
you can see that CK and uid are the same but when i use (if CK==uid) it doesn't work
// Now store the user in SQLite
String uid = jObj.getString("uid");
JSONObject user = jObj.getJSONObject("user");
String name = user.getString("name");
String email = user.getString("email");
String created_at = user
.getString("created_at");
// Inserting row in users table
db.addUser(name, email, uid, created_at);
Log.e(TAG,"CK: " + CK + " user uid: " + uid);
// Launch main activity
if(!(CK==uid)){
Intent intent = new Intent(LoginActivity.this,
MainActivity.class);
startActivity(intent);
finish();
} else{
Intent i = new Intent(getApplicationContext(), AllReclamationsActivity.class);
startActivity(i);
finish();
}
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("email", email);
params.put("password", password);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
my problem is in this part :
// Now store the user in SQLite
String uid = jObj.getString("uid");
JSONObject user = jObj.getJSONObject("user");
String name = user.getString("name");
String email = user.getString("email");
String created_at = user
.getString("created_at");
// Inserting row in users table
db.addUser(name, email, uid, created_at);
Log.e(TAG,"CK: " + CK + " user uid: " + uid);
// Launch main activity
if(!(CK==uid)){
Intent intent = new Intent(LoginActivity.this,
MainActivity.class);
startActivity(intent);
finish();
} else{
Intent i = new Intent(getApplicationContext(), AllReclamationsActivity.class);
startActivity(i);
finish();
}
This not a integer value its a string so compare it like as
Use the below function in your condition:
if(!(CK.equals(uid))){
Intent intent = new Intent(LoginActivity.this,
MainActivity.class);
startActivity(intent);
finish();
}

User Login credential doesn't show up in the landing page(Homepage) after logging in

I got user-login template from github. I modified it a bit to suit my need but didn't altered any important code.
Problem 1: If I register and login, the page goes to activity_main class(landing page) and my login credentials(name & email) are shown. But if I log out and logging again the credentials are not shown on the landing page. First time it shows next time never.
Problem 2: If I register a new ID but login with any old already registered ID (immediately after registering new), landing page shows the credential of newly register ID. After that again it won't show up if I log in with any ID.
What I want to Happen: User credential to be shown on landing page whenever he logs in.Also prob 2nd to be fixed.
Any help would be appreciated guys.
login page code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
// Session manager
session = new SessionManager(getApplicationContext());
// Check if user is already logged in or not
if (session.isLoggedIn()) {
// User is already logged in. Take him to main activity
Intent intent = new Intent(Activity_Login.this, Activity_Main.class);
startActivity(intent);
finish();
}
// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
// Check for empty data in the form
if (email.trim().length() > 0 && password.trim().length() > 0) {
// login user
checkLogin(email, password);
} else {
// Prompt user to enter credentials
Toast.makeText(getApplicationContext(),
"Please enter the credentials!", Toast.LENGTH_LONG)
.show();
}
}
});
// Link to Register Screen
btnLinkToRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
Activity_Register.class);
startActivity(i);
finish();
}
});
}
/**
* function to verify login details in mysql db
* */
private void checkLogin(final String email, final String password) {
// Tag used to cancel the request
String tag_string_req = "req_login";
pDialog.setMessage("Logging in ...");
showDialog();
StringRequest strReq = new StringRequest(Method.POST,
Config_URL.URL_REGISTER, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
// user successfully logged in
// Create login session
session.setLogin(true);
// Launch main activity
Intent intent = new Intent(Activity_Login.this,
Activity_Main.class);
startActivity(intent);
finish();
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "login");
params.put("email", email);
params.put("password", password);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
Register page code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
inputFullName = (EditText) findViewById(R.id.name);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
inputNumber = (EditText) findViewById(R.id.number);
btnRegister = (Button) findViewById(R.id.btnRegister);
btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
// Session manager
session = new SessionManager(getApplicationContext());
// SQLite database handler
db = new SQLiteHandler(getApplicationContext());
// Check if user is already logged in or not
if (session.isLoggedIn()) {
// User is already logged in. Take him to main activity
Intent intent = new Intent(Activity_Register.this,
Activity_Main.class);
startActivity(intent);
finish();
}
// Register Button Click event
btnRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String name = inputFullName.getText().toString();
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
String number = inputNumber.getText().toString();
if (!name.isEmpty() && !email.isEmpty() && !password.isEmpty() && !number.isEmpty()) {
registerUser(name, email, password, number);
} else {
Toast.makeText(getApplicationContext(),
"Please enter your details!", Toast.LENGTH_LONG)
.show();
}
}
});
// Link to Login Screen
btnLinkToLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
Activity_Login.class);
startActivity(i);
finish();
}
});
}
/**
* Function to store user in MySQL database will post params(tag, name,
* email, password) to register url
* */
private void registerUser(final String name, final String email,
final String password, final String number) {
// Tag used to cancel the request
String tag_string_req = "req_register";
pDialog.setMessage("Registering ...");
showDialog();
StringRequest strReq = new StringRequest(Method.POST,
Config_URL.URL_REGISTER, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
// User successfully stored in MySQL
// Now store the user in sqlite
String uid = jObj.getString("uid");
JSONObject user = jObj.getJSONObject("user");
String name = user.getString("name");
String email = user.getString("email");
String created_at = user
.getString("created_at");
// Inserting row in users table
db.addUser(name, email, uid, created_at);
// Launch login activity
Intent intent = new Intent(
Activity_Register.this,
Activity_Login.class);
startActivity(intent);
finish();
} else {
// Error occurred in registration. Get the error
// message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Registration Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "register");
params.put("name", name);
params.put("email", email);
params.put("password", password);
params.put("number", number);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
Main activity page code:
public class Activity_Main extends Activity {
private TextView txtName;
private TextView txtEmail;
private Button btnLogout;
private SQLiteHandler db;
private SessionManager session;
public Button booknow;
public void init(){
booknow= (Button) findViewById(R.id.booknow);
booknow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent toy = new Intent(Activity_Main.this,BikeEntryActivity.class);
startActivity(toy);
}
});
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
txtName = (TextView) findViewById(R.id.name);
txtEmail = (TextView) findViewById(R.id.email);
btnLogout = (Button) findViewById(R.id.btnLogout);
// SqLite database handler
db = new SQLiteHandler(getApplicationContext());
// session manager
session = new SessionManager(getApplicationContext());
if (!session.isLoggedIn()) {
logoutUser();
}
// Fetching user details from sqlite
HashMap<String, String> user = db.getUserDetails();
String name = user.get("name");
String email = user.get("email");
// Displaying the user details on the screen
txtName.setText(name);
txtEmail.setText(email);
// Logout button click event
btnLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
logoutUser();
}
});
}
/**
* Logging out the user. Will set isLoggedIn flag to false in shared
* preferences Clears the user data from sqlite users table
* */
private void logoutUser() {
session.setLogin(false);
db.deleteUsers();
// Launching the login activity
Intent intent = new Intent(Activity_Main.this, Activity_Login.class);
startActivity(intent);
finish();
}
}
For problem 1, when you logout, you are deleting users by calling db.deleteUsers();
When you login again, you need to call db.addUser(name, email, uid, created_at); as you did for registration.
The same applies for problem 2.
UPDATE:
....
if (!error) {
// user successfully logged in
// Create login session
session.setLogin(true);
//You need to save the user here before launching main activity.
db.addUser(name,email);//or whatever method you use to save user.
// Launch main activity
Intent intent = new Intent(Activity_Login.this,
Activity_Main.class);
startActivity(intent);
finish();
}

android shared preference getting error

i need to store user login and password details in shared preference but i am getting error. I need to maintain user login details in session. When user login user mail and password should be get stored in edit text. From next time user can click on login button to enter directly. What i need to do now. Here is my code. When i try below code i am getting unfortunately closed error. Where i need to modify the code. What is the problem in this code.
public class MainActivity extends Activity {
Button b;
EditText email,password;
HttpPost httppost;
StringBuffer buffer;
SharedPreferences sharedpreferences;
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String Name = "nameKey";
public static final String Phone = "phoneKey";
String email1,passw;
SharedPreferences sh_Pref;
Editor toEdit;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;
DBHelper db = new DBHelper(this);
private boolean isValidEmaillId(String email){
return Pattern.compile("^(([\\w-]+\\.)+[\\w-]+|([a-zA-Z]{1}|[\\w-]{2,}))#"
+ "((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
+ "[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\."
+ "([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
+ "[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
+ "([a-zA-Z]+[\\w-]+\\.)+[a-zA-Z]{2,4})$").matcher(email).matches();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button)findViewById(R.id.Button01);
email = (EditText)findViewById(R.id.username);
password= (EditText)findViewById(R.id.password);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(!isValidEmaillId(email.getText().toString().trim())){
Toast.makeText(getApplicationContext(), "Invalid Email Address", Toast.LENGTH_SHORT).show();
}
else if(password.getText().toString().equals(""))
{
Toast.makeText(getApplicationContext(), "Please enter password", Toast.LENGTH_SHORT).show();
}
else
{
email1 = email.getText().toString().trim();
passw = password.getText().toString().trim();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, email1);
editor.putString(Phone, passw);
editor.commit();
System.out.println("sharde :" +Name+Phone);
dialog = ProgressDialog.show(MainActivity.this, "",
"Validating user...", true);
new Thread(new Runnable() {
public void run() {
login();
}
}).start();
}
}
});
}
void login(){
try{
final User user = new User();
httpclient=new DefaultHttpClient();
httppost= new HttpPost("http://ip:8080/ActCFWeb/login"); // make sure the url is correct.
//add your data
nameValuePairs = new ArrayList<NameValuePair>(2);
// Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar,
nameValuePairs.add(new BasicNameValuePair("email",email1)); // $Edittext_value = $_POST['Edittext_value'];
nameValuePairs.add(new BasicNameValuePair("pass",passw));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Execute HTTP Post Request
System.out.println(response);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost, responseHandler);
System.out.println("Response : " + response);
runOnUiThread(new Runnable() {
public void run() {
dialog.dismiss();
}
});
if(response.contains("success")){
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(MainActivity.this,"Login Success", Toast.LENGTH_SHORT).show();
}
});
Intent nextScreen = new Intent(getApplicationContext(), FeedBack.class);
//Sending data to another Activity
nextScreen.putExtra("email", email.getText().toString());
Log.e("n", email.getText()+"."+ email.getText());
startActivity(nextScreen);
}else{
showAlert();
}
}catch(Exception e){
dialog.dismiss();
System.out.println("Exception : " + e.getMessage());
}
}
public void showAlert(){
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Login Error.");
builder.setMessage("User not Found.")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
public boolean isOnline() {
ConnectivityManager conMgr = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = conMgr.getActiveNetworkInfo();
if(netInfo == null || !netInfo.isConnected() || !netInfo.isAvailable()){
Toast.makeText(getApplicationContext(), "No Internet connection!", Toast.LENGTH_LONG).show();
return false;
}
return true;
}
}
I suppose that You call views methods from thread. You have login method in witch you probably call to dialog or other views .You cannot access from not main thread to ui elements. You have to use handler or asynck task.
May be you are talking about this
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, email1);
editor.putString(Phone, passw);
editor.commit();
System.out.println("sharde :" +sharedpreferences.getString(Name, "def").toString()+ ", "sharedpreferences.getString(Phone, "def");
Getting values from SharedPreferences storage.
SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
String emailString = sharedPreferences.getString("email", null);
String passwordString = sharedPreferences.getString("password", null);
In the onCreate method, first check whether the preferences has values for email and password.
if((emailString != null) && (passwordString != null)) {
//Populate the email and password edit texts using stored email and password values.
etEmail.setText(emailString);
etPassword.setText(passwordString);
}
Starting an activity should be performed in main(UI) thread. You can use Handler or runOnUiThread.
if(response.contains("success")){
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(MainActivity.this,"Login Success", Toast.LENGTH_SHORT).show();
Intent nextScreen = new Intent(getApplicationContext(), FeedBack.class);
//Sending data to another Activity
nextScreen.putExtra("email", email.getText().toString());
Log.e("n", email.getText()+"."+ email.getText());
startActivity(nextScreen);
}
});
}else{
showAlert();
}

Categories

Resources