Hello everyone I am working on a CRM project which uses Sugarcrm 6.5 version. I wanted to know what kind of changes I have to do in my LoginActivity to get Token So that I can call it in other Activity.
public class LoginActivity extends AppCompatActivity {
private static final String TAG = LoginActivity.class.getSimpleName();
private Button button;
private EditText editText;
private EditText editText2;
private ProgressDialog pDialog;
private SessionManager session;
private SQLiteHandler db;
CheckBox show_password;
String user_fullname, email, user_id,user_mobile, session_id, module;
public LoginActivity(){
}
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
editText = (EditText) findViewById(R.id.editText);
editText2 = (EditText) findViewById(R.id.editText2);
button = (Button) findViewById(R.id.button);
show_password = (CheckBox) findViewById(R.id.show_hide_password);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
// SQLite database handler
db = new SQLiteHandler(getApplicationContext());
// Session manager
session = new SessionManager(getApplicationContext());
// get the show/hide password Checkbox
// 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
show_password.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// checkbox status is changed from uncheck to checked.
if (!isChecked) {
// show password
editText2.setTransformationMethod(PasswordTransformationMethod.getInstance());
} else {
// hide password
editText2.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
}
}
});
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String username = editText.getText().toString().trim();
String password = editText2.getText().toString().trim();
// Check for empty data in the form
if (!username.isEmpty() && !password.isEmpty()) {
// login user
checkLogin(username, password);
} else {
// Prompt user to enter credentials
Toast.makeText(getApplicationContext(),
"Please enter the credentials!", Toast.LENGTH_LONG)
.show();
}
}
});
}
/**
* function to verify login details in mysql db
*/
private void checkLogin(final String username, final String password) {
pDialog.setMessage("Logging in ...");
showDialog();
RequestQueue requestQueue = Volley.newRequestQueue(this);
String URL= "http://crm.sparshnow.com/api/index.php?username="+username+"&password="+password;
final JsonObjectRequest strReq = new JsonObjectRequest(URL,null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, "Login Response: " + response);
hideDialog();
try {
String success = response.getString("success");
Log.d("response_value", success);
if (success.equals("TRUE")) {
user_fullname=response.getString("user_fullname");
email=response.getString("email");
user_id=response.getString("user_id");
user_mobile=response.getString("user_mobile");
session_id=response.getString("session_id");
Intent intent = new Intent(LoginActivity.this,
MainActivity.class);
intent.putExtra("user_fullname",user_fullname);
intent.putExtra("email",email);
intent.putExtra("user_mobile",user_mobile);
intent.putExtra("session_id", session_id);
session.setLogin(true);
startActivity(intent);
finish();
} else {
Toast.makeText(getApplicationContext(), "Enter Correct Detail ", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError success) {
Log.e(TAG, "Login Error: " + success.getMessage());
Toast.makeText(getApplicationContext(),
success.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
});
requestQueue.add(strReq);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
A little code
and how to use it will be very useful for me.. please Help me
Related
I have a fragment which has two buttons. I have implemented view.OnclickListener methods, and set onclickistener on both buttons:
btn_password = (ImageButton) v.findViewById(R.id.btn_password);
btnEditar = (Button) v.findViewById(R.id.btnEditar);
btn_password.setOnClickListener(this);
btnEditar.setOnClickListener(this);
Then I have implemented the onclick method:
#Override
public void onClick(View view) {
Fragment fragment = null;
switch (view.getId()) {
case R.id.btnEditar:
registerUser(empresa,nombre,direccion,cif,tel,cuenta,id );
break;
case R.id.btn_password:
Log.d(TAG, "Register Response: id" + "clicked Change Password" );
Intent intent1 = new Intent(getActivity(), CambiarPasswordActivity.class);
startActivity(intent1);
break;
}
}
To check that btn_password is clicked, I have included a log, that confirms that the button is clicked.
My issue is that the intent is not launching the activity, it opens MainActivity which is the activity that holds the current fragment.
Any help is welcome
EDITED
CambiarPasswordActivity code
public class CambiarPasswordActivity extends AppCompatActivity {
private static final String URL = "https://.../update_password.php";
public static final String USERNAME = "username";
public static final String USERID = "unique_id";
private String user_uid,pass, pass2,usuario;
ProgressDialog progreso;
private TextView userName;
private SQLiteHandler db;
private SessionManager session;
private ProgressDialog loading;
private EditText password, password2;
public static String MISDATOS= "MisDatos";
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cambiar_password);
Log.d("CAMBIAR", "Register Response: id" + "clicked Change Password ESTOY EN CAMBIAR PASSWORD" );
password=(EditText) findViewById(R.id.password);
password2=(EditText) findViewById(R.id.password2);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pass = password.getText().toString().trim();
pass2 = password2.getText().toString().trim();
SharedPreferences prefs2 =
getSharedPreferences(MISDATOS, Context.MODE_PRIVATE);
usuario = prefs2.getString("ID", "por_defecto#email.com");
if(TextUtils.isEmpty(pass) || pass.length() < 6)
{
Toast.makeText(getApplicationContext(),
"Password too short, at least 6 characters!", Toast.LENGTH_LONG)
.show();
return;
}
if(TextUtils.isEmpty(pass2) || pass2.length() < 6)
{
Toast.makeText(getApplicationContext(),
"Password too short, at least 6 characters!", Toast.LENGTH_LONG)
.show();
return;
}
if (pass.equals(pass2) ){
Log.d("datis","CAMBIO "+pass+" "+usuario);
SendData();
}
else{
Toast.makeText(CambiarPasswordActivity.this,"Passwords donĀ“t match",Toast.LENGTH_LONG).show();
}
}
});
// SqLite database handler
db = new SQLiteHandler(getApplicationContext());
// session manager
session = new SessionManager(getApplicationContext());
if (!session.isLoggedIn()) {
logoutUser();
}
}
private void logoutUser() {
session.setLogin(false);
db.deleteUsers();
// Launching the login activity
Intent intent = new Intent(CambiarPasswordActivity.this, LoginActivity.class);
startActivity(intent);
//finish();
}
public void SendData()
{
progreso = ProgressDialog.show(this, "Changing Password",
"Please, wait...", true);
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println(response);
Log.d("datis","CAMBIO "+response);
Toast.makeText(CambiarPasswordActivity.this,response,Toast.LENGTH_LONG).show();
progreso.dismiss();
Intent intent = new Intent(CambiarPasswordActivity.this,
MainActivity.class);
startActivity(intent);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(CambiarPasswordActivity.this,error.toString(),Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("password",pass);
params.put("usuario", usuario);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
Try this one.
#Override
public void onClick(View view) {
Fragment fragment = null;
switch (view.getId()) {
case R.id.btnEditar:
registerUser(empresa,nombre,direccion,cif,tel,cuenta,id );
break;
case R.id.btn_password:
Log.d(TAG, "Register Response: id" + "clicked Change Password" );
Intent intent1 = new Intent(getActivity(), CambiarPasswordActivity.class);
getActivity().startActivity(intent1);
break;
}
}
So the actual problem is
if (!session.isLoggedIn()) {
logoutUser();
}
Your logoutUser() method was executing because of session.isLoggedIn() returning
false. As the above if condition is satisfying and from logoutUser() you are Launching Intent for LoginActivity.
Which become problem, so you need to handle session.isLoggedIn() according to your requirement.
Thanks
Try this:
In the activity that holds the fragment (MainActivity), create a method that launches CambiarPasswordActivity, and make it public.
MainActivity.class
public void launchCambiarPasswordActivity(){
startActivity(new Intent(this, CambiarPasswordActivity.class));
}
2. And call this method from the fragment:
YourFragment.class
#Override
public void onClick(View view) {
Fragment fragment = null;
switch (view.getId()) {
case R.id.btnEditar:
registerUser(empresa,nombre,direccion,cif,tel,cuenta,id );
break;
case R.id.btn_password:
Log.d(TAG, "Register Response: id" + "clicked Change Password" );
// Call the new method.
((MainActivity) getActivity()).launchCambiarPasswordActivity();
break;
}
}
facing problem in posting data to mysql database using rest api which is done in magento 2 from my android app.
RegisterActivity extends AppCompatActivity {
private static final String TAG = "RegisterActivity";
private static final String URL_FOR_REGISTRATION = "https://xyz/restapi/registration";
ProgressDialog progressDialog;
private EditText signupInputName, signupInputEmail, signupInputPassword, signupInputCnfPassword, signupInputAge;
private Button btnSignUp;
private Button btnLinkLogin;
private RadioGroup genderRadioGroup;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
// Progress dialog
progressDialog = new ProgressDialog(this);
progressDialog.setCancelable(false);
signupInputName = (EditText) findViewById(R.id.signup_input_name);
signupInputEmail = (EditText) findViewById(R.id.signup_input_email);
signupInputPassword = (EditText) findViewById(R.id.signup_input_password);
signupInputCnfPassword = (EditText) findViewById(R.id.signup_input_passwords);
signupInputAge = (EditText) findViewById(R.id.signup_input_age);
btnSignUp = (Button) findViewById(R.id.btn_signup);
btnLinkLogin = (Button) findViewById(R.id.btn_link_login);
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
submitForm();
}
});
btnLinkLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),LoginActivity.class);
startActivity(i);
}
});
}
private void submitForm() {
registerUser(signupInputName.getText().toString(),
signupInputEmail.getText().toString(),
signupInputPassword.getText().toString(),
signupInputCnfPassword.getText().toString(),
signupInputAge.getText().toString());
}
private void registerUser(final String name, final String email, final String password, final String cnfpassword, final String dob) {
// Tag used to cancel the request
String cancel_req_tag = "register";
progressDialog.setMessage("Adding you ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST,
URL_FOR_REGISTRATION, 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) {
String user = jObj.getJSONObject("user").getString("name");
Toast.makeText(getApplicationContext(), "Hi " + user +", You are successfully Added!", Toast.LENGTH_SHORT).show();
// Launch login activity
Intent intent = new Intent(
RegisterActivity.this,
LoginActivity.class);
startActivity(intent);
finish();
} else {
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("cust_username", name);
params.put("cust_firstname", email);
params.put("cust_pass", password);
params.put("cust_confirmpass", cnfpassword);
params.put("cust_phoneno", dob);
return params;
}
};
// Adding request to request queue
AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(strReq, cancel_req_tag);
}
private void showDialog() {
if (!progressDialog.isShowing())
progressDialog.show();
}
private void hideDialog() {
if (progressDialog.isShowing())
progressDialog.dismiss();
}
}
I am using Volley library for request.
I am getting this error
BasicNetwork.performRequest: Unexpected response code 503 for
https://xyz/restapi/registration.
My question is am I missing any thing or will there be constrain that should be checked in mysql to post the data.
I just wanted help in my android app actually scene is like ,I have made an android app that stores and fetch data from mysql database,so the twist is whenever I run app on android emulator it runs fine but as soon as I try to run it on actual device there seem to be nothing is happening however the login and register buttons seem to be doing nothing they don't call the api,I am using wamp as local server and my device and laptop is on same wifi network router so I am not getting it,btw the logcat shows no error at all and it also runs perfectly on emulator
my register activity to add user into database
public class Register extends AppCompatActivity {
private static final String TAG = Register.class.getSimpleName();
ProgressDialog progressDialog;
private EditText signupInputName, signupInputEmail, signupInputPassword;
public Button btnSignUp;
public Button btnLinkLogin;
private SQLiteHandler db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
progressDialog = new ProgressDialog(this);
progressDialog.setCancelable(false);
SessionManager session = new SessionManager(getApplicationContext());
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(Register.this,
Matchboard.class);
startActivity(intent);
finish();
}
signupInputName = (EditText) findViewById(R.id.name);
signupInputEmail = (EditText) findViewById(R.id.email);
signupInputPassword = (EditText) findViewById(R.id.password);
btnSignUp = (Button) findViewById(R.id.btnRegister);
btnLinkLogin = (Button) findViewById(R.id.btnLinkToLoginScreen);
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String name = signupInputName.getText().toString().trim();
String email = signupInputEmail.getText().toString().trim();
String password = signupInputPassword.getText().toString().trim();
if (!name.isEmpty() && !email.isEmpty() && !password.isEmpty()) {
registerUser(name, email, password);
} else {
Toast.makeText(getApplicationContext(),
"Please enter your details!", Toast.LENGTH_SHORT).show();
}
}
});
btnLinkLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),Login.class);
startActivity(i);
finish();
}
});
}
private void registerUser(final String name, final String email, final String password) {
// Tag used to cancel the request
String tag_string_req = "req_register";
progressDialog.setMessage("Adding you ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST,
AppConfig.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) {
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);
Toast.makeText(getApplicationContext(), "Hi "+name+",You are successfully Added!", Toast.LENGTH_SHORT).show();
// Launch login activity
Intent intent = new Intent(
Register.this,
Login.class);
startActivity(intent);
finish();
} else {
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_SHORT).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_SHORT).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("name", name);
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 (!progressDialog.isShowing())
progressDialog.show();
}
private void hideDialog() {
if (progressDialog.isShowing())
progressDialog.dismiss();
}
}
I believe when you are on your local machine the call to made to the localhost but when the app is on your actual device there might be some IP issue.You might be accessing it wrongly.
The thing is that your actual device and the system should be on the same network.
Check your IP using ipconfig command and then retry on same network.
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();
}
Hi in the below code when clicking the report button not going to login activity even though it's not happening anything.
In login activity first of all I am checking the login username and password using session object.
if the username and password working fine and then want to move to next activity.
Can any one help me from this issue.
Mainactivity.java
report1=(TextView)findViewById(R.id.report1);
report=(ImageView)findViewById(R.id.report);
report1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(getApplicationContext(),Login.class);
startActivity(i);
}
});
report.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(getApplicationContext(),Login.class);
startActivity(i);
}
});
In the below when I am putting comment for session then it's moving but after entering the username and password it was showing logcat Admin user found but not going to next activity.it was staying in same activity itself.
update Login
public class Login extends Activity {
ImageButton login;
private static final Pattern USERNAME_PATTERN = Pattern
.compile("[a-zA-Z0-9]{1,250}");
private static final Pattern PASSWORD_PATTERN = Pattern
.compile("[a-zA-Z0-9+_.]{4,16}");
EditText usname,pword,ustype;
TextView tv,tv1;
Boolean isInternetPresent = false;
String username,password;
HttpPost httppost;
StringBuffer buffer;
String queryString;
String data="";
int i;
HttpResponse response;
HttpClient httpclient;
CheckBox mCbShowPwd;
SessionManager session;
private ProgressDialog progressDialog;
ConnectionDetector cd;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.login);
// session = new SessionManager(getApplicationContext());
// session.checkLogin();
// final HashMap<String, String> user = session.getUserDetails();
login = (ImageButton)findViewById(R.id.login);
usname = (EditText)findViewById(R.id.username);
pword= (EditText)findViewById(R.id.password);
ustype= (EditText)findViewById(R.id.usertype);
tv = (TextView)findViewById(R.id.tv);
tv1 = (TextView)findViewById(R.id.tv1);
mCbShowPwd = (CheckBox) findViewById(R.id.cbShowPwd);
cd = new ConnectionDetector(getApplicationContext());
mCbShowPwd.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (!isChecked) {
pword.setTransformationMethod(PasswordTransformationMethod.getInstance());
} else {
pword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
}
}
});
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new LoadViewTask().execute();
isInternetPresent = cd.isConnectingToInternet();
if (!isInternetPresent) {
showAlertDialog(Login.this, "No Internet Connection",
"You don't have internet connection.", true);
return;
}
String username = usname.getText().toString();
String password = pword.getText().toString();
// String name = user.get(SessionManager.KEY_USERNAME);
if (username.equals("")) {
Toast.makeText(Login.this, "ENTER USERNAME",
Toast.LENGTH_LONG).show();
}
if (password.equals("")) {
Toast.makeText(Login.this, "ENTER PASSWORD",
Toast.LENGTH_LONG).show();
}
else if (!CheckUsername(username) && !CheckPassword(password)){
Toast.makeText(Login.this, "ENTER VALID USERNAME & PASSWORD",
Toast.LENGTH_LONG).show();
}
else{
queryString = "username=" + username + "&password="
+ password ;
String usertype = DatabaseUtility.executeQueryPhp("login",queryString);
System.out.print(usertype);
if(usertype.equalsIgnoreCase("Admin user Found")){
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(Login.this, "Login Sucess",
Toast.LENGTH_LONG).show();
}
});
Intent in=new Intent(Login.this, Reports.class);
startActivity(in);
}
else if(usertype.equalsIgnoreCase("No User Found")){
runOnUiThread(new Runnable() {
public void run() {
tv1.setText("InValid UserName and Password");
}
});
}
}
}
});
}
private class LoadViewTask extends AsyncTask<Void, Integer, Void>
{
//Before running code in separate thread
#Override
protected void onPreExecute()
{
progressDialog = ProgressDialog.show(Login.this,"Loading...",
"Loading application View, please wait...", false, false);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params)
{
try
{
synchronized (this)
{
int counter = 0;
while(counter <= 4)
{
this.wait(850);
counter++;
publishProgress(counter*25);
}
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values)
{
progressDialog.setProgress(values[0]);
}
#Override
protected void onPostExecute(Void result)
{
progressDialog.dismiss();
}
}
private boolean CheckPassword(String password) {
return PASSWORD_PATTERN.matcher(password).matches();
}
private boolean CheckUsername(String username) {
return USERNAME_PATTERN.matcher(username).matches();
}
#SuppressWarnings("deprecation")
public void showAlertDialog(Context context, String title, String message, Boolean status) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle(title);
alertDialog.setMessage(message);
alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
}
Do not use the application's context, use the context the view currently be presented.
report.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(v.getContext(), Login.class);
startActivity(i);
}
});