how to save JSONObject reponse using Shared Preferences in App - android

public class MainActivity extends Activity implements OnPreparedListener,
OnClickListener {
Button login;
Button register;
EditText pass_word;
EditText mail;
TextView loginErrormsg;
private static final String TAG = null;
private static String KEY_SUCCESS = "success";
private static String KEY_UID = "uid";
private static String KEY_EMAIL = "email";
private static String KEY_PASSWORD = "password";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
setContentView(R.layout.activity_main);
mail = (EditText) findViewById(R.id.email);
pass_word = (EditText) findViewById(R.id.password);
loginErrormsg = (TextView) findViewById(R.id.login_error);
login = (Button) findViewById(R.id.btnlogin);
register = (Button) findViewById(R.id.btnregister);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String email = mail.getText().toString();
String password = pass_word.getText().toString();
UserFunctions userFunctions = new UserFunctions();
JSONObject json = userFunctions.loginUser(email, password);
// JSONObject userinfo = json.getJSONObject("user");
// check for login response
try {
if (json.getString(KEY_SUCCESS) != null) {
loginErrormsg.setText("");
String res = json.getString(KEY_SUCCESS);
if (Integer.parseInt(res) == 1) {
Log.d("Login Successful!", json.toString());
// user successfully logged in
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(
getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
// Clear all previous data in database
userFunctions.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_EMAIL),
json_user.getString(KEY_PASSWORD));
Intent dashboard = new Intent(
getApplicationContext(),
LoginActivity.class);
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
// Close Login Screen
finish();
} else {
// Error in login
loginErrormsg
.setText("Incorrect username/password");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(i);
}
});
}
public static void setUserObject(Context c, String userObject, String key) {
SharedPreferences pref = PreferenceManager
.getDefaultSharedPreferences(c);
SharedPreferences.Editor editor = pref.edit();
editor.putString(key, userObject);
editor.commit();
}
public static String getUserObject(Context ctx, String key) {
SharedPreferences pref = PreferenceManager
.getDefaultSharedPreferences(ctx);
String userObject = pref.getString(key, null);
return userObject;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
This is my Server response:
{
"tag":"login",
"success":1,
"error":0,
"user":{
"email":"sridhar#gmail.com",
"password":"7a4fb4770d2c404b0c48abd49f4c5f6a",
"id":"118"
}
}

If you want to store only id in shared preference from you server responce, you can do it like,
JSONObject jsonObject = new JSONObject("Your response from server");
JSONObject jsonObject1 = jsonObject.getJSONObject("user");
String id = jsonObject1.getString("id");
SharedPreference sp = getApplicationContext().getSharedPreferences(
"sharedPrefName", 0); // 0 for private mode
Editor editor = sp.edit();
editor.putString("key_name",id); // key_name is the name through which you can retrieve it later.
editor.commit();
// To retrieve value from shared preference in another activity
SharedPreference sp = getApplicationContext().getSharedPreferences(
"sharedPrefName", 0); // 0 for private mode
String id = sp.getString("key_name","defaultvalue"); // key_name is the key you have used for store "id" in shared preference. and deafult value can be anything.
Default value will be returns if your shared preference dose not have any value for given key, else value stored for key is returns

Well, since you already have the id in the json_user object, just do this:
String userId = json_user.optString("id");
if(!userId.isEmpty()) {
getSharedPreferences(YOUR_PREFERENCE_NAME, MODE_PRIVATE).edit().putString(YOUR_USER_ID_KEY_NAME, userId).commit();
}
Then later to retrieve it, use:
String userId = getSharedPreferences(YOUR_PREFERENCE_NAME, MODE_PRIVATE).getString(YOUR_USER_ID_KEY_NAME, null);
if(userId != null) {
//Successfully retrieved user id
}
else {
//Id not found in preferences
}

Related

How to create multiple users registration and login activity in an android?

I've made registration and login activity in an android using shared preferences. User is able to registered and logged in successfully. But my problem is when new user is registered, it delete the previous user's registration details.
Here is my registration page:
public class Registration extends Activity implements
View.OnClickListener
{
SharedPreferences pref;
Editor editor;
TextView btn_registration , btn_formlogin;
EditText et_name, et_pass, et_email , et_phone ;
ImageView btn_upload ;
private static final int PICK_IMAGE_REQUEST = 0;
private Uri mImageUri;
SessionManager session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
et_name = (EditText) findViewById(R.id.edt_Name);
et_pass = (EditText) findViewById(R.id.edt_userPassword);
et_email = (EditText) findViewById(R.id.edt_userEmail);
et_phone = (EditText) findViewById(R.id.edt_Phone);
btn_registration = (TextView) findViewById(R.id.btn_registration);
btn_formlogin = (TextView) findViewById(R.id.btn_formlogin);
btn_upload = (ImageView)findViewById(R.id.img_upload);
Map<String,String> values = new HashMap<String,String>();
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
btn_upload.setOnClickListener(this);
SharedPreferences preference =
PreferenceManager.getDefaultSharedPreferences(this);
final String mImageUri = preference.getString("image", null);
btn_upload.setImageResource(R.drawable.adduser);
// creating an shared Preference file for the information to be stored
// first argument is the name of file and second is the mode, 0 is
private mode
pref = getSharedPreferences("USER_CREDENTIALS", 0);
// get editor to edit in file
editor = pref.edit();
// the tap of button we will fetch the information from four edittext
btn_registration.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View v) {
boolean validName = true;
boolean validPass = true;
boolean validPhone = true;
boolean validEmail = true;
String name = et_name.getText().toString();
String email = et_email.getText().toString();
String pass = et_pass.getText().toString();
String phone = et_phone.getText().toString();
if (isEmpty(et_name)) {
et_name.setError("Enter the Name");
validName = false;
}
if (isEmpty(et_pass)) {
et_pass.setError("Password can't be null");
validPass = false;
}
if (isEmail(et_email) == false) {
et_email.setError("Enter valid email");
validEmail = false;
}
if (isValidMobile(et_phone) == false) {
validPhone = false;
}
final String required_email= pref.getString("Email",null);
final String required_phone=pref.getString("Phone",null);
if(et_email.equals(required_email)){
validEmail = true;
}
else if(et_phone.equals(required_phone)){
validPhone = true;
}
if (validName && validPass && validPhone && validEmail){
// as now we have information in string. Lets stored them
with the help of editor
editor.putString("Name" , name );
editor.putString("Email", email);
editor.putString("Password", pass);
editor.putString("Phone", phone);
editor.putString("image", String.valueOf(mImageUri));
editor.commit(); // commit the values
Toast.makeText(Registration.this, "Registration
Successful", Toast.LENGTH_LONG).show();
session = new SessionManager(getApplicationContext());
session.createLoginSession(name, email, mImageUri);
// after saving the value open next activity
Intent ob = new Intent(Registration.this,
DashBoard.class);
startActivity(ob);
}
else{
Toast.makeText(Registration.this, "Registration
unsuccessful! Please retry.", Toast.LENGTH_LONG).show();
}
}
});
I just want to know how to register multiple user using shared preferences file ?
If you will have multiple users, it is better to use a database(sqlite) than a shared preferences.
in shared preference you can save only single value in a object if you want to save multiple users in your device then you can use room database to store multiple user details in your device. Shared Preference can be used only for single information or if you want to store multiple values in shared preference then you can store arrayList in shared prefefrence.
save array list in shared preference:-
private static SharedPreferences mPrefs;
private static SharedPreferences.Editor mPrefsEditor;
public static Set<String> getCamEval(Context ctx) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
return mPrefs.getStringSet("sdk_camEval", null);
}
public static void setCamEval(Context ctx, ArrayList<String> value) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
mPrefsEditor = mPrefs.edit();
Set<String> set = new HashSet<>();
set.addAll(value);
mPrefsEditor.putStringSet("sdk_camEval", set);
mPrefsEditor.commit();
}

unable to set a session

I am very new in android.In my app I make a login page.I use Shared Preferences for session.it works fine but a problem when i close my app and again open then login page comes.I want when user press logout button only that time login page will come.
this is my SharedPreferences class
public class SharedPrefManager {
//the constants
private static final String SHARED_PREF_NAME = "dreamzsharedpref";
private static final String KEY_USERNAME = "keyusername";
private static final String KEY_PHONE = "keyphone";
private static final String KEY_ID = "keyid";
private static SharedPrefManager mInstance;
private static Context mCtx;
private SharedPrefManager(Context context) {
mCtx = context;
}
public static synchronized SharedPrefManager getInstance(Context context) {
if (mInstance == null) {
mInstance = new SharedPrefManager(context);
}
return mInstance;
}
//method to let the user login
//this method will store the user data in shared preferences
public void userLogin(User user) {
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(KEY_ID, user.getUserid());
editor.putString(KEY_PHONE, user.getUserphno());
editor.putString(KEY_USERNAME, user.getUsername());
editor.apply();
}
//this method will checker whether user is already logged in or not
public boolean isLoggedIn() {
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getString(KEY_PHONE, null) != null;
}
//this method will give the logged in user
public User getUser() {
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
return new User(
sharedPreferences.getString(KEY_USERNAME, null),
sharedPreferences.getString(KEY_PHONE, null),
sharedPreferences.getInt(KEY_ID, -1)
);
}
//this method will logout the user
public void logout() {
SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.apply();
mCtx.startActivity(new Intent(mCtx, LoginActivity.class));
}
}
this is my login method in login class
private void userLogin() {
//first getting the values
final String username = UsernameEt.getText().toString();
final String password = PasswordEt.getText().toString();
//validating inputs
if (TextUtils.isEmpty(username)) {
UsernameEt.setError("Please enter your username");
UsernameEt.requestFocus();
return;
}
if (TextUtils.isEmpty(password)) {
PasswordEt.setError("Please enter your password");
PasswordEt.requestFocus();
return;
}
//if everything is fine
class UserLogin extends AsyncTask<Void, Void, String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.setVisibility(View.VISIBLE);
}
#Override
protected String doInBackground(Void... voids) {
//creating request handler object
RequestHandler requestHandler = new RequestHandler();
//creating request parameters
HashMap<String, String> params = new HashMap<>();
params.put("vuserphno", username);
params.put("votp", password);
//returing the response
return requestHandler.sendPostRequest(URLs.URL_LOGIN, params);//this URLs is a class where URL_LOGIN is login url
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
progressBar.setVisibility(View.GONE);
try {
JSONObject obj = new JSONObject(s);
JSONArray array = obj.getJSONArray("user");
for (int i = 0; i < array.length(); i++) {
//getting the user from the response
JSONObject userJson = array.getJSONObject(i);
//creating a new user object
User user = new User(
userJson.getString("username"),
userJson.getString("userphno"),
userJson.getInt("userid")
);
//storing the user in shared preferences
SharedPrefManager.getInstance(getApplicationContext()).userLogin(user);
}
//starting the profile activity
finish();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
UserLogin ul = new UserLogin();
ul.execute();
}
please tell me where is the problem and how I can solve this problem.
Thanks.
In your LoginActivity, check for login state and change activity, finish itself so it's clear from the back stack.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
if (SharedPrefManager.getInstance().isLoggedIn(this)) {
startActivity(this, MainActivity.class);
finish();
return;
}
// ...
}

I want to store Register and Login information in shared preferences in android

I know there are n number of examples in android for shared preferences but I want to Register and store the info in shared preferences and in database using JSON. And then fetch data from JSON and Login with those credentials. If user is already logged in open Main Activity,else go to Splash screen and then open Login Activity. Please go through my detailed code :
RegisterActivity :
public class RegisterActivity extends AppCompatActivity implements ServerRequests.Registereponse {
private EditText password, phone, email;
public static EditText name;
ServerRequests serverRequests;
JSONParser jsonParser;
private Button registerButton;
TextView alreadyMember;
Editor editor;
UserSession session;
SharedPreferences sharedPreferences;
public static final String MyPREFERENCES = "MyPrefs";
public static final String Name1 = "nameKey";
public static final String Phone1 = "phoneKey";
public static final String Email1 = "emailKey";
public static final String Password1 = "passwordKey";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
jsonParser = new JSONParser();
serverRequests = new ServerRequests(getApplicationContext());
serverRequests.setRegistereponse(this);
alreadyMember = (TextView) findViewById(R.id.alreadyMember);
name = (EditText) findViewById(R.id.FName);
phone = (EditText) findViewById(R.id.PhoneNum);
email = (EditText) findViewById(R.id.mail);
password = (EditText) findViewById(R.id.password);
registerButton = (Button) findViewById(R.id.email_sign_in_button);
sharedPreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
registerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CharSequence temp_emailID = email.getText().toString();
if (name.getText().toString().length() == 0) {
name.setError("Please enter your name");
name.requestFocus();
} else if (phone.getText().toString().length() == 0) {
phone.setError("Please enter your phone number");
phone.requestFocus();
} else if (!isValidEmail(temp_emailID)) {
email.setError("Please enter valid email");
email.requestFocus();
} else if (password.getText().toString().length() == 0) {
password.setError("Please enter password");
password.requestFocus();
} else {
try {
String Name = name.getText().toString();
String Email = email.getText().toString();
String Password = password.getText().toString();
String Phone = phone.getText().toString();
JSONObject obj = jsonParser.makeRegisterJson(Name, Email, Password, Long.parseLong(Phone));
Log.e("final Json", obj.toString());
serverRequests.register(obj);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(Name1, Name);
editor.putString(Email1, Email);
editor.putString(Password1, Password);
editor.putString(Phone1, Phone);
editor.commit();
// Toast.makeText(RegisterActivity.this, "Registered Successfully!", Toast.LENGTH_LONG).show();
} catch (Exception e) {
}
}
// startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
}
});
alreadyMember.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
finish();
}
});
}
#Override
public void onRegsiterReposne(JSONObject object) {
Toast.makeText(RegisterActivity.this, "hiii" + object.toString(), Toast.LENGTH_SHORT).show();
}
public final static boolean isValidEmail(CharSequence target) {
if (TextUtils.isEmpty(target)) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
}
}
LoginActivity :
public class LoginActivity extends AppCompatActivity implements ServerRequests.Loginreponse {
private static final String PREFER_NAME = "Reg";
private Button email_sign_in_button;
private EditText email, password;
private TextView notMember, forgotPass;
UserSession session;
private SharedPreferences sharedPreferences;
ServerRequests serverRequests;
JSONParser jsonParser;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
jsonParser = new JSONParser();
serverRequests = new ServerRequests(getApplicationContext());
serverRequests.setLoginreponse(this);
notMember = (TextView) findViewById(R.id.notMember);
forgotPass = (TextView) findViewById(R.id.forgotPass);
notMember.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
finish();
}
});
forgotPass.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, ForgotPassword.class));
}
});
// get Email, Password input text
email = (EditText) findViewById(R.id.email);
password = (EditText) findViewById(R.id.pass);
// User Login button
email_sign_in_button = (Button) findViewById(R.id.login);
sharedPreferences = getSharedPreferences(PREFER_NAME, MODE_PRIVATE);
// Login button click event
email_sign_in_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
String Email = email.getText().toString();
String Password = password.getText().toString();
JSONObject obj = jsonParser.makeLoginJson(Email, Password);
Log.e("final Json", obj.toString());
serverRequests.login(obj);
} catch (Exception e) {
}
// startActivity(new Intent(LoginActivity.this, MainActivity.class));
// finish();
}
});
}
#Override
public void onLoginReposne(JSONObject object) {
Toast.makeText(LoginActivity.this, "helloo" + object.toString(), Toast.LENGTH_SHORT).show();
if (object.toString().contains("true")) {
Toast.makeText(LoginActivity.this, "Logged in..", Toast.LENGTH_SHORT).show();
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
}
}
}
SplashScreen :
public class SplashScreen extends Activity {
Thread splashTread;
SharedPreferences preferences;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
StartAnimations();
}
public void onAttachedToWindow() {
super.onAttachedToWindow();
Window window = getWindow();
window.setFormat(PixelFormat.RGBA_8888);
}
private void StartAnimations() {
Animation anim = AnimationUtils.loadAnimation(this, R.anim.alpha);
anim.reset();
LinearLayout l = (LinearLayout) findViewById(R.id.lin_lay);
l.clearAnimation();
l.startAnimation(anim);
anim = AnimationUtils.loadAnimation(this, R.anim.translate);
anim.reset();
ImageView iv = (ImageView) findViewById(R.id.splashImage);
iv.clearAnimation();
iv.startAnimation(anim);
/* TextView tv = (TextView) findViewById(R.id.splashText);
tv.clearAnimation();
tv.startAnimation(anim);*/
splashTread = new Thread() {
#Override
public void run() {
try {
int waited = 0;
// Splash screen pause time
while (waited < 3500) {
sleep(100);
waited += 100;
}
startNextScreen();
} catch (InterruptedException e) {
// do nothing
} finally {
SplashScreen.this.finish();
}
}
};
splashTread.start();
}
private void startNextScreen() {
preferences = getSharedPreferences("TrainingApp", MODE_PRIVATE);
String userLoginStatus = preferences.getString("userLoginStatus", "no");
if (userLoginStatus.equals("no")) {
Intent intent = new Intent(SplashScreen.this,
LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
SplashScreen.this.finish();
} else {
Intent intent = new Intent(SplashScreen.this,
MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
SplashScreen.this.finish();
}
}
}
JSONParser class :
public class JSONParser {
//----------For Register
public JSONObject makeRegisterJson(String name, String email, String password, long phone) throws JSONException {
JSONObject object = new JSONObject();
object.put("name", name);
object.put("email", email);
object.put("password", password);
object.put("phone", phone);
// if its in array------
/*JSONObject finalObject=new JSONObject();
finalObject.put("request",object);
return finalObject;*/
return object;
}
//--------For Login--------------------------------------------------------
public JSONObject makeLoginJson(String Name, String password) throws JSONException {
JSONObject object = new JSONObject();
object.put("userName", Name);
object.put("password", password);
/*JSONObject finalObject=new JSONObject();
finalObject.put("request",object);
return finalObject;*/
return object;
}
}
ServerRequests class :
// ---------------- for register------------------------------------------------------------------------------
public void setRegistereponse(Registereponse registereponse) {
this.registereponse = registereponse;
}
private Registereponse registereponse;
public interface Registereponse {
void onRegsiterReposne(JSONObject object);
}
public void register(JSONObject jsonObject) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, Services.REGISTER_URL, jsonObject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Log.e("Json response", "" + response);
boolean b = response.getBoolean("success");
if (registereponse != null) {
registereponse.onRegsiterReposne(response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Error ", "" + error);
}
}
);
queue.add(jsonObjectRequest);
}
// --------------For Login ---------------------------------------------------------------------------
public void setLoginreponse(Loginreponse loginreponse) {
this.loginreponse = loginreponse;
}
private Loginreponse loginreponse;
public interface Loginreponse {
void onLoginReposne(JSONObject object);
}
public void login(JSONObject jsonObject) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, Services.LOGIN_URL, jsonObject,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Log.e("Json response", "" + response);
boolean b = response.getBoolean("success");
if (loginreponse != null) {
loginreponse.onLoginReposne(response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Error ", "" + error);
}
}
);
queue.add(jsonObjectRequest);
}
UserSession class :
public class UserSession {
// Shared Preferences reference
SharedPreferences pref;
// Editor reference for Shared preferences
Editor editor;
// Context
Context _context;
// Shared preferences mode
int PRIVATE_MODE = 0;
// Shared preferences file name
public static final String PREFER_NAME = "Reg";
// All Shared Preferences Keys
public static final String IS_USER_LOGIN = "IsUserLoggedIn";
// User name (make variable public to access from outside)
public static final String KEY_NAME = "Name";
// Email address (make variable public to access from outside)
public static final String KEY_EMAIL = "Email";
// password
public static final String KEY_PASSWORD = "Password";
public static final String KEY_PHONE = "PhoneNumber";
public static final String KEY_QUALIFICATION = "Qualification";
// Constructor
public UserSession(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREFER_NAME, PRIVATE_MODE);
editor = pref.edit();
}
//Create login session
public void createUserLoginSession(String uEmail, String uPassword) {
// Storing login value as TRUE
editor.putBoolean(IS_USER_LOGIN, true);
// Storing name in preferences
editor.putString(KEY_EMAIL, uEmail);
// Storing email in preferences
editor.putString(KEY_PASSWORD, uPassword);
// commit changes
editor.commit();
}
/**
* Check login method will check user login status
* If false it will redirect user to login page
* Else do anything
*/
public boolean checkLogin() {
// Check login status
if (!this.isUserLoggedIn()) {
// user is not logged in redirect him to Login Activity
Intent i = new Intent(_context, LoginActivity.class);
// Closing all the Activities from stack
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
return true;
}
return false;
}
/**
* Get stored session data
*/
public HashMap<String, String> getUserDetails() {
//Use hashmap to store user credentials
HashMap<String, String> user = new HashMap<String, String>();
// user name
user.put(KEY_NAME, pref.getString(KEY_NAME, null));
// user email id
user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null));
user.put(KEY_PASSWORD, pref.getString(KEY_PASSWORD, null));
user.put(KEY_PHONE, pref.getString(KEY_PHONE, null));
user.put(KEY_QUALIFICATION, pref.getString(KEY_QUALIFICATION, null));
// return user
return user;
}
/**
* Clear session details
*/
public void logoutUser() {
// Clearing all user data from Shared Preferences
editor.clear();
editor.commit();
// After logout redirect user to MainActivity
Intent i = new Intent(_context, LoginActivity.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
}
// Check for login
public boolean isUserLoggedIn() {
return pref.getBoolean(IS_USER_LOGIN, false);
}
}
At the time of login successfull put this code:
prefs = getSharedPreferences("logindetail", 0);
SharedPreferences.Editor edit = prefs.edit();
edit.putString("userLoginStatus", "yes");
edit.commit();
At the time of logout use this:
prefs = getSharedPreferences("logindetail", 0);
SharedPreferences.Editor edit = prefs.edit();
edit.clear();
edit.commit();
And at the time of checking if user is login or not use below code:
Loginprefs = getApplicationContext().getSharedPreferences("logindetail", 0);
userLoginStatus = Loginprefs.getString("userLoginStatus", null);
if(userLoginStatus.tostring().equals("yes")){
//the user is login
}else{
//user is logout
}
Hope this helps you

SharedPreferences to save login data

In my application a user starts the application and try to logs in , the application checks whether there is in the Shared Set < User> with the list of credentials for all users , if it does not exist create it from scratch .... Here's my question is how do I check in the shared existence of this Set < User>?
Here, have a look at my code for shared preferences. This code will save your login data.
public class MainActivity extends Activity {
SharedPreferences sharedpreferences;
TextView name;
TextView email;
public static final String mypreference = "mypref";
public static final String Name = "nameKey";
public static final String Email = "emailKey";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (TextView) findViewById(R.id.etName);
email = (TextView) findViewById(R.id.etEmail);
sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
if (sharedpreferences.contains(Name)) {
name.setText(sharedpreferences.getString(Name, ""));
}
if (sharedpreferences.contains(Email)) {
email.setText(sharedpreferences.getString(Email, ""));
}
}
public void Save(View view) {
String n = name.getText().toString();
String e = email.getText().toString();
Editor editor = sharedpreferences.edit();
editor.putString(Name, n);
editor.putString(Email, e);
editor.commit();
}
public void clear(View view) {
name = (TextView) findViewById(R.id.etName);
email = (TextView) findViewById(R.id.etEmail);
name.setText("");
email.setText("");
}
public void Get(View view) {
name = (TextView) findViewById(R.id.etName);
email = (TextView) findViewById(R.id.etEmail);
sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
if (sharedpreferences.contains(Name)) {
name.setText(sharedpreferences.getString(Name, ""));
}
if (sharedpreferences.contains(Email)) {
email.setText(sharedpreferences.getString(Email, ""));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Here is simple login code we can store data by putString method of Editor class
SharedPreferences.Editor editor = sp.edit();
editor.putString("User", c.getString(c.getColumnIndex("Name")).toString());
editor.commit();
full code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et1 = (EditText) findViewById(R.id.editText);
et2 = (EditText) findViewById(R.id.editText2);
btn = (Button) findViewById(R.id.button);
btn3 = (Button) findViewById(R.id.button3);
btn3 = (Button) findViewById(R.id.button3);
ct = (Button) findViewById(R.id.ct);
final SQLiteDatabase db = openOrCreateDatabase("DemoDb",MODE_ENABLE_WRITE_AHEAD_LOGGING,null);
ct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
db.execSQL("create table login(LoginId varchar(10) primary key,Password varchar(10),Name varchar(10));");
}
});
sp = getSharedPreferences("myLogin", MODE_PRIVATE);
if(!sp.getBoolean("LogInMode",false)) {
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if( et1.getText().toString().length()==0 || et2.getText().toString().length()==0){
Toast.makeText(getBaseContext(), "User Not Found", Toast.LENGTH_SHORT).show();
}else {
String data = "content://com.example.maity.dbdemo.123/DemoDb";
Uri uri = Uri.parse(data);
ContentResolver resolver = getContentResolver();
String[] ar = {"", ""};
ar[0] = et1.getText().toString().trim();
ar[1] = et2.getText().toString().trim();
final Cursor c = resolver.query(uri, null, null, ar, null);
if (c.moveToNext()) {
if ((et1.getText().toString().trim().equals(c.getString(c.getColumnIndex("LoginId")).toString())) &&
(et2.getText().toString().trim().equals(c.getString(c.getColumnIndex("Password")).toString()))) {
SharedPreferences.Editor editor = sp.edit();
editor.putBoolean("LogInMode", true);
editor.putString("User", c.getString(c.getColumnIndex("Name")).toString());
editor.commit();
Intent intent = new Intent(MainActivity.this, WelcomePage.class);
startActivity(intent);
finish();
}
}else {
Toast.makeText(getBaseContext(), "User Not Found", Toast.LENGTH_SHORT).show();
}
}
}
});
}
else{
Intent intent = new Intent(MainActivity.this, WelcomePage.class);
startActivity(intent);
finish();
}
}
If your login api response is like below
{
"status": true,
"message": "Login Success",
"data": {
"user_id": "1",
"first_name": "Ketan",
"last_name": "Ramani",
"username": "ketanramani"
}
}
Then you can save all login response by dynamically using below code
SharedPreferences preferences = getApplicationContext().getSharedPreferences("LoginPref", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(dataObject.toString());
Iterator<String> iterator = jsonObject.keys();
while (iterator.hasNext()) {
String key = iterator.next();
editor.putString(key, jsonObject.optString(key)).apply();
}
} catch (JSONException e) {
e.printStackTrace();
}
Your data will save in sharedpreferences like below
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<string name="user_id">1</string>
<string name="first_name">Ketan</string>
<string name="last_name">Ramani</string>
<string name="username">ketanramani</string>
</map>

Getting cannot convert jsonarray to json object

Hi i am developing an app which uses mysql db but when i try to get the values and display it i get the following error.
02-20 05:48:33.021: W/System.err(1723): org.json.JSONException: Value [{"3":"images\/BigBazaar.png","2":"Jayanagar 4th Block","outlet_name":"Big Bazaar","1":"Big Bazaar","0":"1","outlet_image":"images\/BigBazaar.png","outlet_location":"Jayanagar 4th Block","outlet_id":"1"}] of type org.json.JSONArray cannot be converted to JSONObject
I am also able to see the output in log ie;
02-20 05:48:33.380: I/TAG(1723): [{"0":"1","outlet_id":"1","1":"Big Bazaar","outlet_name":"Big Bazaar","2":"Jayanagar 4th Block","outlet_location":"Jayanagar 4th Block","3":"images\/BigBazaar.png","outlet_image":"images\/BigBazaar.png"}]
This is my code.
public class StoreActivity extends Activity {
private String mBaseUrl="http://192.168.1.5/Flutura/PHP/";
private String mDataUrl=mBaseUrl+"Core/Data/android.data3.php";
private String mAssetsUrl=mBaseUrl+"Assets/";
private String mRequest="outlet";
private String mOutletID="0";
private String mRecommendedProducts="";
private String mOutletDetails="";
private SharedPreferences myPrefs ;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.store);
myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
mOutletID = myPrefs.getString("outlet_id", "0");
mOutletDetails = myPrefs.getString("outlet_details","{}");
Log.v("outlet_details",myPrefs.getString("outlet_details","{}"));
if(mOutletDetails != "{}"){
setOutletData(mOutletDetails);
}
else{
executeAjaxRequest();
}
}
private void executeAjaxRequest(){
String url = mDataUrl+"?request="+mRequest+"&outlet_id="+mOutletID;
Log.v("url",url);
AsyncHttpClient httpclient = new AsyncHttpClient();
httpclient.get(url, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
setOutletData(response);
Log.i("TAG",response);
}
});
}
private void setOutletData(String response){
try{
JSONObject store = new JSONObject(response);
ImageView store_avatar = (ImageView) findViewById(R.id.store_avatar);
TextView store_id = (TextView) findViewById(R.id.store_id);
TextView store_name = (TextView) findViewById(R.id.store_name);
TextView store_loc = (TextView) findViewById(R.id.store_location);
if(store_avatar != null){
/*
int resid;
resid = getApplicationContext().getResources().getIdentifier(store.getString("outlet_image").replaceAll(".png",""), "drawable", "org.flutura.recommendation");
store_avatar.setImageResource(resid);*/
ImageDownloader imdload = new ImageDownloader();
imdload.setMode(ImageDownloader.Mode.CORRECT);
imdload.download(mAssetsUrl+store.getString("outlet_image"),store_avatar );
mOutletDetails = store.toString();
mRecommendedProducts = store.getString("recommended_products");
store_avatar.setClickable(true);
store_avatar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(StoreActivity.this,StoreMapActivity.class);
SharedPreferences myPrefs = getApplicationContext().getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putString("outlet_details", mOutletDetails);
prefsEditor.commit();
startActivity(myIntent);
}
});
}
mOutletID = store.getString("outlet_id");
if(store_id != null){
store_id.setText(mOutletID);
}
if(store_name != null){
store_name.setText(store.getString("outlet_desc"));
}
if(store_loc != null){
store_loc.setText(store.getString("outlet_loc"));
}
Button recommended_products_button = (Button) findViewById(R.id.recommended_products_button);
recommended_products_button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
// Load the recommended products screen
Intent myIntent = new Intent(StoreActivity.this,RecommendedProductsListActivity.class);
SharedPreferences myPrefs = getApplicationContext().getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putString("outlet_id",mOutletID);
prefsEditor.putString("recommended_products", mRecommendedProducts);
prefsEditor.commit();
startActivity(myIntent);
}
});
Button category_wise_sales_button = (Button) findViewById(R.id.category_wise_sales_button);
category_wise_sales_button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
// Load the recommended products screen
Intent myIntent = new Intent(StoreActivity.this,CategoryWiseSalesActivity.class);
SharedPreferences myPrefs = getApplicationContext().getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putString("outlet_id",mOutletID);
prefsEditor.commit();
startActivity(myIntent);
}
});
}
catch(JSONException e){
e.printStackTrace();
}
catch(NullPointerException e){
e.printStackTrace();
}
}
}
This is my php code.
<?php
error_reporting(0);
//$url = $_GET['url'];
//$mR = $_GET['mRequest'];
$mOid = $_GET['mOutletId'];
//$mloc = $_GET['mLocation'];
//connect to the db
$user = "root";
$pswd = "";
$db = "recommendations_db";
$host = "localhost";
$conn = mysql_connect($host, $user, $pswd);
mysql_select_db($db);
//if($mR == 'outlets' && $mloc = 'all'){
$query = "SELECT outlet_id,outlet_name,outlet_location,outlet_image FROM outlets WHERE outlet_id = '$mOid'";
$result = mysql_query($query) or die("Unable to verify user because : " . mysql_error());
//while($row = mysql_fetch_array($result))
//{
$output[] = mysql_fetch_array($result);
//}
print( json_encode($output));
?>
Can anyone tell me what is wrong as i am on a tight schedule and need to finish this today.
Code for search button.
search_button.setClickable(true);
search_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String outlet_no = outlet_id.getText().toString();
if(!outlet_no.isEmpty()){
#SuppressWarnings("deprecation")
SharedPreferences myPrefs = getApplicationContext().getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putString("outlet_id", outlet_no);
prefsEditor.commit();
Intent myIntent = new Intent(HomeActivity.this, StoreActivity.class);
startActivity(myIntent);
HomeActivity.this.startActivity(myIntent);
}
else{
Toast.makeText(getApplicationContext(), "Please enter an outlet id", Toast.LENGTH_SHORT);
}
}
});
Getting cannot convert jsonarray to json object
because your are getting JSONArray instead of JSONObject from server so just change your code by converting String to jsonArray as :
JSONArray jsonArr = new JSONArray(response); //<<< convert to jsonarray
// extract jsonObejct from JsonArray
JSONObject store = jsonArr.getJSONObject(0);
instead of
JSONObject store = new JSONObject(response);

Categories

Resources