I been trying to create a small login app that stores the logged in information to shared preferences.
i created a class called Mysession to store,get and clear shared preferences data,
the class takes a context and when i pass the context from my login activity to login class and then store the data to shared preferences i get an error.
the error indicates that i passed an empty context.
these are my classes and activities.
Login Activity
public class LoginActivity extends AppCompatActivity {
EditText lemailtxt,lpasstxt;
Button loginbttn;
String lurl;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
lurl = "http://192.168.1.6/test/test.php";
lemailtxt = (EditText) findViewById(R.id.emailtxt);
lpasstxt = (EditText) findViewById(R.id.passtxt);
loginbttn = (Button) findViewById(R.id.loginbttn);
loginbttn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MLoginOnline login = new MLoginOnline(getApplicationContext()
,lurl,lemailtxt.getText().toString(),lpasstxt.getText().toString());
login.execute();
}
});
}
Login Class
public class MLoginOnline extends AsyncTask<Void,Void,String>{
Context mContext;
String Purl;
String Pemail,Ppass;
ProgressDialog progressDialog;
public MLoginOnline(Context mContext, String purl, String pemail, String ppass) {
this.mContext = mContext;
Purl = purl;
Pemail = pemail;
Ppass = ppass;
}
MySession session = new MySession(mContext);
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(mContext);
progressDialog.setTitle("Login");
progressDialog.setMessage("Loging in please wait......");
progressDialog.show();
}
#Override
protected String doInBackground(Void... params) {
String data = Loginto();
return data;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
String id,name,sem;
if (s ==null){
Toast.makeText(mContext,"Error Login in",Toast.LENGTH_SHORT).show();
progressDialog.hide();
}else {
progressDialog.hide();
try {
JSONObject object = new JSONObject(s);
id = object.getString("id");
name = object.getString("name");
sem = object.getString("sem");
session.InPutUser(id,name,Pemail,sem);
Intent intent = new Intent(mContext, HomeActivity.class);
mContext.startActivity(intent);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private String Loginto(){
InputStream inputStream=null;
String line = null;
try {
URL url = new URL(Purl+"?Email="+Pemail+"&Password="+Ppass);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
inputStream = new BufferedInputStream(con.getInputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuffer stringBuffer = new StringBuffer();
if(bufferedReader != null){
while ((line=bufferedReader.readLine()) != null){
stringBuffer.append(line+"\n");
}
}else {
return null;
}
return stringBuffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
**Shared preferences class **
public class MySession {
Context mcontext;
SharedPreferences preferences;
SharedPreferences.Editor editor;
int PRIVATE_MODE = 0;
private static final String PREFER_NAME = "session";
private final String IS_USER_LOGED_IN = "IsUserLogedIn";
public final String KEY_ID = "id";
public final String KEY_EMAIL = "email";
public static final String KEY_NAME = "name";
public static final String KEY_SEM = "sem";
public MySession(Context mcontext) {
this.mcontext = mcontext;
this.preferences = mcontext.getSharedPreferences(PREFER_NAME,PRIVATE_MODE);
editor = preferences.edit();
}
public void InPutUser(String id,String name,String email,String sem){
editor.putBoolean(IS_USER_LOGED_IN,true);
editor.putString(KEY_ID,id);
editor.putString(KEY_NAME,name);
editor.putString(KEY_SEM,sem);
editor.putString(KEY_EMAIL,email);
editor.commit();
}
public void logoutUser(Context context,Class intent){
// Clearing all user data from Shared Preferences
editor.clear();
editor.commit();
// After logout redirect user to Login Activity
Intent i = new Intent(context, intent);
// 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);
}
public HashMap<String, String> getNameAndSem(){
HashMap<String, String> user = new HashMap<String, String>();
// user name
user.put(KEY_NAME, preferences.getString(KEY_NAME, null));
// user email id
user.put(KEY_EMAIL, preferences.getString(KEY_SEM, null));
// return user
return user;
}
public HashMap<String, String> getIDandEMail() {
HashMap<String, String> user = new HashMap<String, String>();
// user name
user.put(KEY_NAME, preferences.getString(KEY_ID, null));
// user email id
user.put(KEY_EMAIL, preferences.getString(KEY_EMAIL, null));
// return user
return user;
}
public boolean IsUserLoggedIn(){
return preferences.getBoolean(IS_USER_LOGED_IN, false);
}
}
Cat log
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.zer0ll.demo.studentapp, PID: 20793
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference
at com.zer0ll.demo.studentapp.MySession.<init>(MySession.java:36)
at com.zer0ll.demo.studentapp.MLoginOnline.<init>(MLoginOnline.java:43)
at com.zer0ll.demo.studentapp.MainView.LoginActivity$1.onClick(LoginActivity.java:32)
at android.view.View.performClick(View.java:5156)
at android.view.View$PerformClick.run(View.java:20755)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5835)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
Application terminated.
In your MLoginOnline class
Here MySession session = new MySession(mContext); needs to be defined under a method cause mContext is not initialized yet.
MySession session; //declare globally
public MLoginOnline(Context mContext, String purl, String pemail, String ppass) {
this.mContext = mContext;
Purl = purl;
Pemail = pemail;
Ppass = ppass;
session = new MySession(mContext); //initialize here
}
Your session field is being initialized with null Context.
Instead of:
MySession session = new MySession(mContext);
Do:
MySession session;
public MLoginOnline(Context mContext, String purl, String pemail, String ppass) {
this.mContext = mContext;
Purl = purl;
Pemail = pemail;
Ppass = ppass;
session = new MySession(mContext);
}
public MLoginOnline(Context mContext, String purl, String pemail, String ppass) {
this.mContext = mContext;
Purl = purl;
Pemail = pemail;
Ppass = ppass;
}
MySession session = new MySession(mContext);
put MySession session = new MySession(mContext); into MLoginOnline
final code will be like this
MySession session;
public MLoginOnline(Context mContext, String purl, String pemail, String ppass) {
this.mContext = mContext;
Purl = purl;
Pemail = pemail;
Ppass = ppass;
session = new MySession(mContext);
}
You are using getApplicationContext() while creating MLoginOnline object.
I would say better use 'this' here.
here you could see the differences between context type
Difference between getContext() , getApplicationContext() , getBaseContext() and “this”
Related
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 am able to login to the System, and Logout from the System.When i presses back from the Dashboard without making Logout from the System.I have login to the System eachtime.How can i restrict to loginPage without making the Logout from the System.I need to open the Dashbord page,if the user havenot logout from the System and direct to the Login if the accesstoken time expires
Login
public class Login extends AppCompatActivity implements View.OnClickListener {
EditText userName, Password;
Button login;
public static final String LOGIN_URL = "http://192.168.100.5:84/Token";
public static final String KEY_USERNAME = "UserName";
public static final String KEY_PASSWORD = "Password";
String username, password;
String accesstoken, tokentype, expiresin, masterid, name, access, issue, expires, masterid1;
SessionManagement sessionManagement;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
userName = (EditText) findViewById(R.id.login_name);
Password = (EditText) findViewById(R.id.login_password);
userName.setHint(Html.fromHtml("<font color='#008b8b' style='italic'>Username</font>"));
Password.setHint(Html.fromHtml("<font color='#008b8b'>Password</font>"));
login = (Button) findViewById(R.id.login);
login.setOnClickListener(this);
/* sessionManagement = (SessionManagement) getSharedPreferences("mySharedPref", 0);
if (sessionManagement.isLoggedIn()) {
startActivity(new Intent(getApplicationContext(), Home.class));
} */
}
private void UserLogin() {
username = userName.getText().toString().trim();
password = Password.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, LOGIN_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
accesstoken = jsonObject.getString("access_token");
tokentype = jsonObject.getString("token_type");
expiresin = jsonObject.getString("expires_in");
username = jsonObject.getString("userName");
masterid = jsonObject.getString("MasterID");
masterid = masterid.replaceAll("[^\\.0123456789]", "");
masterid1 = jsonObject.getString("MasterID");
name = jsonObject.getString("Name");
access = jsonObject.getString("Access");
issue = jsonObject.getString(".issued");
expires = jsonObject.getString(".expires");
SessionManagement session = new SessionManagement(Login.this);
session.createLoginSession(accesstoken, tokentype, expiresin, username, masterid, name, access, issue, expires);
// session.createLoginSession(masterid1);
openProfile();
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Fetch failed!", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Toast.makeText(Login.this, error.toString(), Toast.LENGTH_LONG).show();
Toast.makeText(Login.this, "Please enter valid username and Password", Toast.LENGTH_SHORT).show();
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
//params.put("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
return params;
}
#Override
protected Map<String, String> getParams() {
Map<String, String> map = new HashMap<String, String>();
map.put(KEY_USERNAME, username);
map.put(KEY_PASSWORD, password);
//map.put("access_token", accesstoken);
map.put("grant_type", "password");
return map;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
60000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void openProfile() {
Intent intent = new Intent(this, Home.class);
intent.putExtra(KEY_USERNAME, username);
startActivity(intent);
startActivity(intent);
}
#Override
public void onClick(View v) {
UserLogin();
}
}
SessionManagementis used for storing access token and other required information
public class SessionManagement {
SharedPreferences pref;
SharedPreferences.Editor editor;
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Sharedpref file name
private static final String PREF_NAME = "AndroidHivePref";
private static final String IS_LOGIN = "IsLoggedIn";
public static final String KEY_access_token = "access_token";
public static final String KEY_token_type = "token_type";
public static final String Key_EXPIRES_IN = "expires_in";
public static final String KEY_USERNAME = "userName";
public static final String KEY_MASTER_ID = "MasterID";
public static final String KEY_MASTER_ID1 = "MasterID";
public static final String KEY_Name = "Name";
public static final String KEY_Access = "Access";
public static final String KEY_Issued = ".issued";
public static final String KEY_expires = ".expires";
// Constructor
public SessionManagement(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
SettingFragment context;
public void createLoginSession(String accesstoken, String tokentype, String expiresin, String username, String masterId, String name, String access, String issued, String expires) {
editor.putBoolean(IS_LOGIN, true);
editor.putString(KEY_access_token, accesstoken);
editor.putString(KEY_token_type, tokentype);
editor.putString(Key_EXPIRES_IN, expiresin);
editor.putString(KEY_USERNAME, username);
editor.putString(KEY_MASTER_ID, masterId);
editor.putString(KEY_MASTER_ID1, masterId);
editor.putString(KEY_Name, name);
editor.putString(KEY_Access, access);
editor.putString(KEY_Issued, issued);
editor.putString(KEY_expires, expires);
editor.apply();
String user_new_access_token = pref.getString(KEY_access_token, null);
String user_new_access_tokentype = pref.getString(KEY_token_type, null);
String user_name_expiresin = pref.getString(Key_EXPIRES_IN, null);
String user_name_Username = pref.getString(KEY_USERNAME, null);
String user_name_masterID = pref.getString(KEY_MASTER_ID, null);
String user_name_name = pref.getString(KEY_Name, null);
String user_name_access = pref.getString(KEY_Access, null);
String user_name_issued = pref.getString(KEY_Issued, null);
String user_name_expires = pref.getString(KEY_expires, null);
String user_name_masterID1 = pref.getString(KEY_MASTER_ID1, null);
Log.d("TAG", "Access Token :" + accesstoken + user_new_access_token);
Log.d("TAG", "TokenType:" + user_new_access_tokentype);
Log.d("TAG", "Expires in:" + user_name_expiresin);
Log.d("TAG", "UserName:" + user_name_Username);
Log.d("TAG", "MasterID:" + user_name_masterID);
Log.d("TAG", "Name:" + user_name_name);
Log.d("TAG", "Access:" + user_name_access);
Log.d("TAG", "Issued:" + user_name_issued);
Log.d("TAG", "Expires:" + user_name_expires);
Log.d("TAG", "user_name_masterID1:" + user_name_masterID1);
// String user_name_new = pref.getString(KEY_access_token, null);
// Log.d("TAG", " :" + accesstoken + " user_name_new:" + user_name_new);
// Log.d(tokentype, "admin");
//ad Log.d(expiresin, "expiresin");
editor.commit();
}
/**
* Check login method wil check user login status
* If false it will redirect user to login page
* Else won't do anything
*/
public void checkLogin() {
// Check login status
if (!this.isLoggedIn()) {
// user is not logged in redirect him to Login Activity
Intent i = new Intent(_context, Login.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);
}
}
/**
* Get stored session data
*/
public HashMap<String, String> getUserDetails() {
HashMap<String, String> user = new HashMap<String, String>();
// user name
// user.put(KEY_USERNAME, pref.getString(KEY_USERNAME, null));
user.put(KEY_access_token, pref.getString(KEY_access_token, null));
user.put(KEY_token_type, pref.getString(KEY_token_type, null));
// user.put(KEY_TOKEN_TYPE, pref.getString(KEY_TOKEN_TYPE, null));
// user.put(KEY_MASTER_ID, pref.getString(KEY_MASTER_ID, null));
// user.put(KEY_access_token, pref.getString(KEY_access_token, null));
// user.put(KEY_NAME, pref.getString(KEY_NAME, null));
//user.put(KEY_Access, pref.getString(KEY_Access, null));
// return user
return user;
}
/**
* Clear session details
*/
public void logoutUser() {
editor.clear();
editor.commit();
// After logout redirect user to Loing Activity
Intent i = new Intent(_context, Login.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);
}
public String getMasterId() {
String masterID = pref.getString(KEY_MASTER_ID, null);
return masterID;
}
public String getMasterId1() {
String masterID = pref.getString(KEY_MASTER_ID1, null);
return masterID;
}
public String getAccess() {
String accessID = pref.getString(KEY_Access, null);
return accessID;
}
public String getKeyName() {
String KeyName = pref.getString(KEY_Name, null);
return KeyName;
}
public String getAccesstToken() {
String user_new_access_token = pref.getString(KEY_access_token, null);
return user_new_access_token;
}
public void clear() {
Log.d("TAg", "Full Cleared");
editor.clear();
// editor.remove(KEY_MASTER_ID);
// editor.remove(KEY_USERNAME);
editor.commit();
}
/**
* Quick check for login
**/
// Get Login State
public boolean isLoggedIn() {
return pref.getBoolean(IS_LOGIN, false);
}
}
How can i direct to dashboard page if the user has not logout to the
system?
I have checked the session on the Login page .If isLoggedIn() == true then i have switched to the Dashboard page.
sessionmanagement
public boolean isLoggedIn() {
System.out.println("Pref" + pref.getBoolean(IS_LOGIN, false));
return pref.getBoolean(IS_LOGIN, false);
}
public boolean checkLogin() {
// Check login status
if (!this.isLoggedIn()) {
// user is not logged in redirect him to Login Activity
Intent i = new Intent(_context, Login.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);
}
// return false;
return false;
}
Login
if (session.isLoggedIn() == true) {
Intent intent = new Intent(this, Home.class);
startActivity(intent);
}
one can do with checking the session expiry time also
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
Help me on android SharedPreferences, I have login activity when after login will set the SharedPreferences, but when set SharedPreferences always error null pointer. I try to show the value with toast and all variable have value. this my activity
public class LoginNewActivity extends Activity {
public SessionManager session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView toRegister = (TextView) findViewById(R.id.link_to_register);
toRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), RegisterActivity.class);
startActivity(i);
}
});
final EditText etUsnm = (EditText) findViewById(R.id.tuserid);
final EditText etPswd = (EditText) findViewById(R.id.tpasswd);
Button bLogin = (Button) findViewById(R.id.btnLogin);
bLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String username = etUsnm.getText().toString();
String password = etPswd.getText().toString();
new UserLoginTask().execute(username, password);
}
});
}
public class UserLoginTask extends AsyncTask<String, String, JSONObject> {
ProgressDialog pdLoading = new ProgressDialog(LoginNewActivity.this);
HttpURLConnection conn;
URL url = null;
JSONParser jsonParser = new JSONParser();
private static final String TAG_MESSAGE = "message";
private static final String TAG_NAMA = "nama_user";
private static final String TAG_USERNAME = "username";
private static final String TAG_HAKAKSES = "role";
private static final String TAG_ERROR = "error";
private static final String LOGIN_URL = "http://192.168.1.101/mlls/getLoginNew.php";
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected JSONObject doInBackground(String... args) {
try {
HashMap<String, String> params = new HashMap<>();
params.put("username", args[0]);
params.put("password", args[1]);
Log.d("request", "starting");
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
if (json != null) {
Log.d("JSON result", json.toString());
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(JSONObject json) {
String nama = "";
int iduser = 0;
String email = "";
String hakakses = "";
int error_message = 0;
if (json != null) {
//Toast.makeText(LoginActivity.this, json.toString(),
//Toast.LENGTH_LONG).show();
try {
nama = json.getString(TAG_NAMA);
email = json.getString(TAG_USERNAME);
hakakses = json.getString(TAG_HAKAKSES);
error_message = json.getInt(TAG_ERROR);
} catch (JSONException e) {
e.printStackTrace();
}
}
if(error_message == 1) {
pdLoading.dismiss();
session.setLogin(true);
session.setStatus(hakakses);
session.setNama(nama);
session.setUsername(email);
session.setId(iduser);
Toast.makeText(LoginNewActivity.this, hakakses,
Toast.LENGTH_LONG).show();
//Intent intent = new Intent(LoginNewActivity.this, LessonListActivity.class);
//intent.putExtra("nama", nama);
//intent.putExtra("email", email);
//intent.putExtra("hakakses", hakakses);
//startActivity(intent);
//LoginNewActivity.this.finish();
}else{
Toast.makeText(getApplicationContext(), "User ID atau Password anda salah.", Toast.LENGTH_LONG).show();
}
}
}}
and this is my sharedPreferences
public class SessionManager {
private static String TAG = SessionManager.class.getSimpleName();
SharedPreferences pref;
Editor editor;
Context _context;
int PRIVATE_MODE = 0;
private static final String PREF_NAME = "Hlls";
private static final String KEY_IS_LOGGEDIN = "isLoggenIn";
private static final String KEY_IS_USER = "isStatus";
private static final String KEY_IS_NAMA = "isNama";
private static final String KEY_IS_USERNAME = "isUsername";
private static final String KEY_IS_IDUSER = "isIdUser";
public SessionManager(Context context){
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public void setLogin(boolean isLoggedIn){
editor.putBoolean(KEY_IS_LOGGEDIN, isLoggedIn);
editor.commit();
Log.d(TAG, "User login session modified");
}
public void setId(int isIdUser){
editor.putInt(KEY_IS_IDUSER, isIdUser);
editor.commit();
Log.d(TAG, "ID User akses session modified");
}
public void setStatus(String isStatus){
editor.putString(KEY_IS_USER, isStatus);
editor.commit();
Log.d(TAG, "User akses session modified");
}
public void setNama(String isNama){
editor.putString(KEY_IS_NAMA, isNama);
editor.commit();
Log.d(TAG, "Username session modified");
}
public void setUsername(String isUsername){
editor.putString(KEY_IS_USERNAME, isUsername);
editor.commit();
Log.d(TAG, "Username session modified");
}
public String isNama(){
return pref.getString(KEY_IS_NAMA, "");
}
public int isId(){
return pref.getInt(KEY_IS_IDUSER, 0);
}
public String isUsername(){
return pref.getString(KEY_IS_USERNAME, "");
}
public boolean isLoggedIn(){
return pref.getBoolean(KEY_IS_LOGGEDIN, false);
}
public String isStatus(){
return pref.getString(KEY_IS_USER, "");
}
}
help me for this error, sorry for bad english
NullPointerException is thrown when an application attempts to use an
object reference that has the null value .
You should call this in your ONCREATE section .
session=new SessionManager(LoginNewActivity.this);
Finally
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
session=new SessionManager(LoginNewActivity.this);
Use mode private instead of private mode
pref = _context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
It is flag provided by android itself you need not assign any other flag to it.
and you have not initialized session manager context is null.
I guess you are not initializing your Shared Preference class.
SessionManager session = new SessionManager(this);
In case its true
Please try and make it a singleton class as a general practise
Something like this
public final class PreferenceManager {
private static SharedPreferences preferences;
/**
* Private constructor to restrict the instantiation of class.
*/
private PreferenceManager() {
throw new AssertionError();
}
public static SharedPreferences getInstance(Context context) {
if (preferences == null && context != null) {
preferences = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
}
return preferences;
}
}
You need to do the following in your Activity:
session = new SessionManager(LoginNewActivity.this);
You have not created the object of your SessionManager class, so its constructor never gets called and you get NPE.
JSON DATA
{
VerifiedMember: [{ user_id: "23", first_name: "karan", phone: "" }],
success: 1,
message: "success"
}
Login Activity Class
public class NewLogin extends AppCompatActivity {
private static final String PREFER_NAME = "Reg";
Button btnLogin;
private EditText editTextUserName;
private EditText editTextPassword;
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
SharedPreferences sharedPreferences;
// User Session Manager Class
UserSessionManager session;
String username;
String password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_login);
// User Session Manager
session = new UserSessionManager(getApplicationContext());
sharedPreferences = getApplication().getSharedPreferences("KEY", Context.MODE_PRIVATE);
sharedPreferences = getSharedPreferences(PREFER_NAME, Context.MODE_PRIVATE);
editTextUserName = (EditText) findViewById(R.id.et_email);
editTextPassword = (EditText) findViewById(R.id.et_password);
Toast.makeText(getApplicationContext(),
"User Login Status: " + session.isUserLoggedIn(),
Toast.LENGTH_LONG).show();
}
public void invokeLogin(View view) {
new loginAccess().execute();
}
private class loginAccess extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewLogin.this);
pDialog.setMessage("Login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
username = editTextUserName.getText().toString();
password = editTextPassword.getText().toString();
}
#Override
protected String doInBackground(String... arg0) {
List<NameValuePair> params = new ArrayList<>();
// Get username, password from EditText
String username = editTextUserName.getText().toString();
String password = editTextPassword.getText().toString();
String url = "xxxx.xxx";
JSONObject json;
int successValue = 0;
try {
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
json = jsonParser.makeHttpRequest(url, "POST", params);
// Validate if username, password is filled
if(username.trim().length() > 0 && password.trim().length() > 0){
String uName = null;
String uPassword =null;
if (sharedPreferences.contains("username")) {
uName = sharedPreferences.getString("username", "");
}
if (sharedPreferences.contains("password")) {
uPassword = sharedPreferences.getString("password", "");
}
if (username.equals(uName) && password.equals(uPassword)) {
session.createUserLoginSession("username", "password");
} else {
}
}else{
}
Log.d("TESS :: ", json.toString());
successValue = json.getInt("success");
Log.d("Success Response :: ", String.valueOf(successValue));
} catch (Exception e1) {
// TODO Auto-generated catch block flag=1;
e1.printStackTrace();
}
return String.valueOf(successValue);
}
protected void onPostExecute(String jsonstring) {
pDialog.dismiss();
if (jsonstring.equals("1")) {
Intent i = new Intent(NewLogin.this, Sample.class);
startActivity(i);
finish();
} else {
Toast.makeText(NewLogin.this, "Please enter the correct details!!", Toast.LENGTH_LONG).show();
}
}
}
}
Sample activity:
public class Sample extends AppCompatActivity {
private static final String URL_DATA = "xxx.xxx";
// User Session Manager Class
UserSessionManager session;
LinearLayout linearLayout;
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private SwipeRefreshLayout swipeRefreshLayout;
private List<Data_SAerver> data_sAervers;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recyclerview);
// Session class instance
session = new UserSessionManager(getApplicationContext());
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
loadRecyclerViewData();
swipeRefreshLayout.setRefreshing(false);
}
});
swipeRefreshLayout.setColorScheme(
android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
linearLayout = (LinearLayout) findViewById(R.id.linaralayout1);
linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Sample.this, Post_data_Activity.class);
startActivity(i);
}
});
recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
data_sAervers = new ArrayList<>();
loadRecyclerViewData();
}
private void loadRecyclerViewData() {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_DATA, new Response.Listener<String>() {
#Override
public void onResponse(String s) {
progressDialog.dismiss();
String filename = "";
String filetype = "";
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray posts = jsonObject.getJSONArray("posts");
if (posts != null && posts.length() > 0) {
for (int i = 0; i < posts.length(); i++) {
JSONObject fileObj = posts.getJSONObject(i);
String fName = fileObj.getString("firstname");
String created_at = fileObj.getString("created_at");
String post_desc = fileObj.getString("post_desc");
Log.e("Details", fName + "" + created_at + "" + post_desc);
JSONArray files = fileObj.getJSONArray("files");
if (files != null && files.length() > 0) {
for (int j = 0; j < files.length(); j++) {
JSONObject Jsonfilename = files.getJSONObject(j);
filename = Jsonfilename.getString("file_name");
filetype = Jsonfilename.getString("file_type");
if (filetype.equalsIgnoreCase("2")) {
filename = "xxx.xxx" + filename;
} else if(filetype.equalsIgnoreCase("1")) {
filename = "xxx.xxx" + filename;
}
Log.e("Files", "" + filename);
}
} else {
filename = "";
filetype = "";
}
Data_SAerver item = new Data_SAerver(fName, created_at, post_desc, filename, filetype);
data_sAervers.add(item);
}
}
adapter = new MyAdapter(data_sAervers, getApplicationContext());
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
swipeRefreshLayout.setRefreshing(false);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.menuLogout:
session.logoutUser();
/*startActivity(new Intent(this, NewLogin.class));
break;*/
}
return true;
}
}
MyAdapter class:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<Data_SAerver> data_sAervers;
private Context context;
public MyAdapter(List<Data_SAerver> data_sAervers, Context context) {
this.data_sAervers = data_sAervers;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.sample, parent, false);
return new ViewHolder(v, context);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
final Data_SAerver data_sAerver = data_sAervers.get(position);
holder.firstname.setText(data_sAerver.getFirstname());
holder.created_at.setText(data_sAerver.getCreated_at());
holder.post_desc.setText(data_sAerver.getPost_desc());
holder.filepathurl.setText(data_sAerver.getfilepath());
if (data_sAerver.getFiletype().equals("1")) {
holder.files.setVisibility(View.VISIBLE);
Picasso.with(context).load(data_sAerver.getfilepath()).resize(736, 1128).onlyScaleDown().into(holder.files);
holder.playvideo.setVisibility(View.GONE);
} else {
if (data_sAerver.getFiletype().equals("2")) {
holder.playvideo.setVisibility(View.VISIBLE);
holder.files.setVisibility(View.GONE);
holder.playvideo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent play = new Intent(context, PlayVideo.class);
play.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
play.putExtra("url", data_sAerver.getfilepath());
context.startActivity(play);
}
});
}
}
}
#Override
public int getItemCount() {
return data_sAervers.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
// User Session Manager Class
UserSessionManager session;
public TextView firstname, commenttext;
public TextView created_at;
public TextView post_desc;
public ImageView files;
public LinearLayout comment_linear_layout;
public TextView comment_btn;
public TextView filepathurl;
public TextView playvideo;
// private TextView editTextUserName;
public TextView onlinefirstname;
Context con;
public ViewHolder(View itemView, Context context) {
super(itemView);
filepathurl = (TextView) itemView.findViewById(R.id.filepathurl);
filepathurl.setVisibility(View.GONE);
// editTextUserName = (TextView) itemView.findViewById(R.id.editTextUserrName);
playvideo = (TextView) itemView.findViewById(R.id.playvideo);
firstname = (TextView) itemView.findViewById(R.id.firstname);
created_at = (TextView) itemView.findViewById(R.id.created_at);
post_desc = (TextView) itemView.findViewById(R.id.post_desc);
files = (ImageView) itemView.findViewById(R.id.image_files);
con = context;
// onlinefirstname = (TextView)itemView.findViewById(R.id.online_user_firstname);
SparkButton sparkButton = (SparkButton) itemView.findViewById(R.id.star_button1);
sparkButton.setChecked(false);
comment_btn = (TextView) itemView.findViewById(R.id.comment_btn);
comment_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(con, Popup_layout.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
con.startActivity(i);
}
});
}
}
}
UserSessionManager:
public class UserSessionManager {
// 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 = "username";
// Email address (make variable public to access from outside)
public static final String KEY_EMAIL = "firstname";
// password
public static final String KEY_PASSWORD = "password";
// Constructor
public UserSessionManager(Context context){
this._context = context;
pref = _context.getSharedPreferences(PREFER_NAME, PRIVATE_MODE);
editor = pref.edit();
}
//Create login session
public void createUserLoginSession(String uName, String uPassord){
// Storing login value as TRUE
editor.putBoolean(IS_USER_LOGIN, true);
// Storing name in pref
editor.putString(KEY_NAME, uName);
// Storing email in pref
editor.putString(KEY_PASSWORD, uPassord);
// 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, Sample.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));
// 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 Login Activity
Intent i = new Intent(_context, NewLogin.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);
}
}
Here I am not able to get user_id using shared preference. Please help me how to get it.
In onPostExecute try this you will get User ID
try {
String userid;
JSONObject ob = new JSONObject(jsonstring);
JSONArray arr = ob.getJSONArray("VerifiedMember");
for (int i = 0; i < arr.length(); i++) {
JSONObject obj = arr.getJSONObject(i);
userid=obj.getString("user_id");
}
} catch (Exception e) {
}
You can use this pojo generator
http://www.jsonschema2pojo.org/
For parsing you can use google's gson library or jackson parser is also good.
http://www.vogella.com/tutorials/JavaLibrary-Gson/article.html
I have a project and i want to save every variables that are available to the user online to the shared preference. It is their string values user_id, Fname, Lname, and their int values "lexile", "user_id".I have been following a tutorial online so far so good but it only provides saving two variables so I improvise. I didnt get any error when running but when actually using the application I cant seem to login and open the second activity maybe because of my hashmaping.
Here is the code below
this is the part of the login that is related
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//SUBUKAN NA ISINGIT DINE ANG PAGCHECK SA INTERNET SERCVICE
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
//OPENS THE NEW ACTIVITY
if (success) {
String Fname = jsonResponse.getString("Fname");
String Lname = jsonResponse.getString("Lname");
int lexile = jsonResponse.getInt("lexile");
int user_id = jsonResponse.getInt("user_id");
// String username = jsonResponse.getString("username");
// int user_id = jsonResponse.getInt("user_id");
Intent intent = new Intent(Login.this, User_nav.class);
intent.putExtra("Lname", Lname);
intent.putExtra("Fname", Fname);
intent.putExtra("lexile", lexile);
intent.putExtra("user_id", user_id);
// intent.putExtra("username",username);
//intent.putExtra("user_id", user_id);
//THIS IS THE PART OF THE SESSION MANAGER
session.createLoginSession(Lname, Fname, lexile, user_id);
Login.this.startActivity(intent);
progress.dismiss();
}
This is the second activity, the codes that are related
SessionManager session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user);
session = new SessionManager(getApplicationContext());
Toast.makeText(getApplicationContext(), "User Login Status: " + session.isLoggedIn(),Toast.LENGTH_LONG).show();
session.checkLogin();
HashMap<String, String> user = session.getUserDetails();
String Lname = user.get(SessionManager.KEY_FNAME);
String Fname = user.get(SessionManager.KEY_LNAME);
HashMap<String, Integer> user_int = session.getUserLexileNID();
Integer lexile = user_int.get(SessionManager.KEY_LEXILE);
Integer user_id = user_int.get(SessionManager.KEY_USER_ID);
TextView Name = (TextView) header.findViewById(R.id.Name);
TextView displayLexile = (TextView) header.findViewById(R.id.lexile);
Name.setText(Html.fromHtml(Lname+", " +Fname));
displayLexile.setText("Lexile Level: "+lexile + "" +user_id);
This is the SessionManager that holds all of those codes for session making.
package com.capstone.jmilibraryapp;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v4.content.SharedPreferencesCompat;
import java.util.HashMap;
public class SessionManager {
SharedPreferences pref;
SharedPreferences.Editor editor;
Context _context;
int PRIVATE_MODE = 0;
private static final String PREF_NAME = "JMIPref";
private static final String IS_LOGIN = "IsLoggedIn";
public static final String KEY_FNAME = "Fname";
public static final String KEY_LNAME = "Lname";
public static final String KEY_USER_ID = "user_id";//PART OF THE PROBLEM
public static final String KEY_LEXILE = "lexile";///PART OF THE PROBLEM
//constructor
public SessionManager(Context context){
this._context = context;
pref =_context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
//create login session
public void createLoginSession(String Fname, String Lname, Integer user_id, Integer lexile){
editor.putBoolean(IS_LOGIN, true);
editor.putString(KEY_FNAME, Fname);
editor.putString(KEY_LNAME, Lname);
editor.putInt(KEY_USER_ID, user_id);
editor.putInt(KEY_LEXILE, lexile);
editor.commit();
}
//Part of the tutorial dont seem to have any problem
public HashMap<String, String> getUserDetails(){
HashMap<String, String> user = new HashMap<String, String>();
user.put(KEY_FNAME, pref.getString(KEY_FNAME, null));
user.put(KEY_LNAME, pref.getString(KEY_LNAME, null));
return user;
}
//THIS MAYBE THE SOURCE OF THE PROBLEM
public HashMap<String, Integer> getUserLexileNID(){
HashMap<String, Integer> user_int = new HashMap<>();
user_int.put(KEY_LEXILE, pref.getInt(KEY_LEXILE,-1 ));
user_int.put(KEY_USER_ID, pref.getInt(KEY_USER_ID,-1 ));
return user_int;
}
public void checkLogin(){
if (!this.isLoggedIn()) {
Intent i = new Intent(_context, Login.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
_context.startActivity(i);
}}
public void logoutUser(){
editor.clear();
editor.commit();
Intent i = new Intent(_context, Login.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
_context.startActivity(i);
}
public boolean isLoggedIn(){
return pref.getBoolean(IS_LOGIN, false);
}
}