Hi I am developing and android app in which a login and signup page is there when user enters the username and password a passcode will be sent to the mobile number and after that he will enter to registation page where he needs to enter username,password and passcode for verification.. So I need is a random value has to be given to the table like'1' or something for successful registration..else '0' like that.. can anyone help..
Register Activity
public class RegisterActivity extends Activity {
LoginDataBaseAdapter loginDataBaseAdapter;
Button btnReg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register_xm);
loginDataBaseAdapter=new LoginDataBaseAdapter(this);
loginDataBaseAdapter=loginDataBaseAdapter.open();
btnReg = (Button) findViewById (R.id.buttonRegister);
final EditText editTextUserName=(EditText)findViewById(R.id.editTextUserNameToLogin);
final EditText editTextPassword=(EditText)findViewById(R.id.editTextPasswordToLogin);
final EditText editTextMobileNumber = (EditText)findViewById(R.id.editText1);
btnReg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String userName=editTextUserName.getText().toString();
String password=editTextPassword.getText().toString();
String mobileNumber = editTextMobileNumber.getText().toString();
// fetch the Password form database for respective user name
String storedPassword=loginDataBaseAdapter.getSinlgeEntry(userName);
String sd = getIntent().getStringExtra("number");
String name = editTextUserName.getText().toString();
// check if the Stored password matches with Password entered by user
if(password.equals(storedPassword) && (mobileNumber.equals(sd)))
{
Toast.makeText(RegisterActivity.this, "Congrats: Registration Successfull", Toast.LENGTH_LONG).show();
Intent in = new Intent(RegisterActivity.this,HomePageActivity.class);
startActivity(in);
}
else
{
Toast.makeText(RegisterActivity.this, "User Name, Passcode or Password does not match", Toast.LENGTH_LONG).show();
}
}
});
}
#Override
protected void onDestroy()
{
super.onDestroy();
// Close The Database
loginDataBaseAdapter.close();
}
}
signup Activity
public class SignUpActivity extends Activity
{
EditText editTextUserName,editTextPassword,editTextConfirmPassword, editMobileNumber;
Button btnCreateAccount;
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
Random r = new Random();
int number =r.nextInt(9999 - 1000) + 1000;
LoginDataBaseAdapter loginDataBaseAdapter;
private static String url_create_data = "http://iascpl.com/app/create_data1.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.signup_xm);
// get Instance of Database Adapter
loginDataBaseAdapter=new LoginDataBaseAdapter(this);
loginDataBaseAdapter=loginDataBaseAdapter.open();
// Get References of Views
editTextUserName=(EditText)findViewById(R.id.editTextUserName);
editTextPassword=(EditText)findViewById(R.id.editTextPassword);
editTextConfirmPassword=(EditText)findViewById(R.id.editTextConfirmPassword);
editMobileNumber = (EditText)findViewById(R.id.mobileNumber);
btnCreateAccount=(Button)findViewById(R.id.buttonCreateAccount);
btnCreateAccount.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String name=editTextUserName.getText().toString();
String password=editTextPassword.getText().toString();
String confirmPassword=editTextConfirmPassword.getText().toString();
String phoneNo = editMobileNumber.getText().toString();
String sms = Integer.toString(number);
//Intent intent = new Intent(SignUpActivity.this, RegisterActivity.class);
//intent.putExtra("number", sms + "");
//startActivity(intent);
//new CreateNewProduct().execute();
StringTokenizer st=new StringTokenizer(phoneNo,",");
while (st.hasMoreElements())
{
String tempMobileNumber = (String)st.nextElement();
if(tempMobileNumber.length()>0 && sms.trim().length()>0)
{
sendSMS(tempMobileNumber, sms);
}
else
{
Toast.makeText(getBaseContext(),
"Please enter both phone number and message.",
Toast.LENGTH_SHORT).show();
}
}
// check if any of the fields are vacant
if(name.equals("")||password.equals("")||confirmPassword.equals(""))
{
Toast.makeText(getApplicationContext(), "Field Vaccant", Toast.LENGTH_LONG).show();
return;
}
// check if both password matches
if(!password.equals(confirmPassword))
{
Toast.makeText(getApplicationContext(), "Password does not match", Toast.LENGTH_LONG).show();
return;
}
else
{
// Save the Data in Database
loginDataBaseAdapter.insertEntry(name, password);
Toast.makeText(getApplicationContext(), "Passcode is sent to the mobile number you provided. ", Toast.LENGTH_LONG).show();
new CreateNewProduct().execute();
// Intent intent = new Intent(SignUpActivity.this, RegisterActivity.class);
// intent.putExtra("number", sms + "");
// startActivity(intent);
}
}
});
}
private void sendSMS(String phoneNumber, String message)
{
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
new Intent(SENT), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
new Intent(DELIVERED), 0);
//---when the SMS has been sent---
registerReceiver(new BroadcastReceiver(){
#Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode())
{
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS sent",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getBaseContext(), "Generic failure",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getBaseContext(), "No service",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getBaseContext(), "Null PDU",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getBaseContext(), "Radio off",
Toast.LENGTH_SHORT).show();
break;
}
}
},new IntentFilter(SENT));
//---when the SMS has been delivered---
registerReceiver(new BroadcastReceiver(){
#Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode())
{
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS delivered",
Toast.LENGTH_SHORT).show();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(getBaseContext(), "SMS not delivered",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(DELIVERED));
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
loginDataBaseAdapter.close();
}
/**
* Background Async Task to Create new product
* */
class CreateNewProduct extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SignUpActivity.this);
pDialog.setMessage("Creating a new account..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
String name = editTextUserName.getText().toString();
String password = editTextPassword.getText().toString();
String mobile = editMobileNumber.getText().toString();
String sms = Integer.toString(number);
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("password", password));
params.add(new BasicNameValuePair("mobile", mobile));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_data,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(SignUpActivity.this, RegisterActivity.class);
i.putExtra("number", sms + "");
startActivity(i);
//closing this screen
//finish();
} else {
// failed to create product
return "false";
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
/*protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}*/
protected void onPostExecute(String result)
{
// TODO Auto-generated method stub
super.onPostExecute(result);
if (result == "false")
Toast.makeText(SignUpActivity.this, "User Name already exists. Please choose another user name ", Toast.LENGTH_LONG).show();
pDialog.dismiss();
}
}
}
You can generate different random values like this.
System.currentTimeMillis(); //It return long value of current time. This value always will be unique.
Related
I try to connect Login and Registration form through PHP API, But I get the error and I don't understand how its will be resolve. I check the solution regarding this error but I don't understand it. Thank you in advance!
Error :-
W/System.err: org.json.JSONException: Value null of type org.json.JSONObject$1 cannot be converted to JSONObject
Here is my code for Registration form (Login.java)
Login. java (This is the java file where for Registration)
public class Login extends Activity {
EditText editname, editemail, editpassword, editmobile;
Button btnRegister;
private static final String TAG = "Login";
private static final String URL_FOR_REGISTRATION = "http://codexpertise.com/codexpertise.com/apitest/signup.php";
ProgressDialog progressDialog;
ImageButton btnfb;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
// Progress dialog
progressDialog = new ProgressDialog(this);
progressDialog.setCancelable(false);
editname = (EditText) findViewById(R.id.editname);
editemail = (EditText) findViewById(R.id.editemail);
editpassword = (EditText) findViewById(R.id.editpassword);
editmobile = (EditText) findViewById(R.id.editmobile);
btnRegister = (Button) findViewById(R.id.btnRegister);
btnfb = (ImageButton)findViewById(R.id.btnfb);
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
submitForm();
}
private void submitForm() {
registerUser(editname.getText().toString(),
editemail.getText().toString(),
editpassword.getText().toString(),
editmobile.getText().toString());
}
private void registerUser(final String name, final String email, final String password,
final String mobile) {
// 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(
Login.this,
MainActivity.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("name", name);
params.put("email", email);
params.put("password", password);
params.put("gender", mobile);
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();
}
});
btnfb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Uri uri = Uri.parse("https://www.facebook.com/"); // missing 'http://' will cause crashed
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
}
}
Here is the some image which i test it on postman
[1
Check this
[2
Try this
your response not any boolean error = jObj.getBoolean("error"); so you can read your response code and change your condition as your requirement..
try
{
JSONObject jObj = new JSONObject(response);
String respCode = jObj.getString("resp_code");
//boolean error = jObj.getBoolean("error");
if (respCode.equals("200")) {
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(
Login.this,
MainActivity.class);
startActivity(intent);
finish();
} else {
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
I am currently building an app in which students from an university/school log in and see their marks and other specific info about themselves. I would like to know if it's possible to retrieve data from a table just for the user that logged in and display it, and how exactly could I do that?
Eg. If user A logs in and he wants to see his marks, the he would just go to the marks activity and that would display his marks
LoginActivity.java
public class LoginActivity extends Activity {
private static final String TAG = RegisterActivity.class.getSimpleName();
private Button btnLogin;
private Button btnLinkToRegister;
private EditText inputEmail;
private EditText inputPassword;
private ProgressDialog pDialog;
private SessionManager session;
private SQLiteHandler db;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
// SQLite database handler
db = new SQLiteHandler(getApplicationContext());
// Session manager
session = new SessionManager(getApplicationContext());
// Check if user is already logged in or not
if (session.isLoggedIn()) {
// User is already logged in. Take him to main activity
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String email = inputEmail.getText().toString().trim();
String password = inputPassword.getText().toString().trim();
// Check for empty data in the form
if (!email.isEmpty() && !password.isEmpty()) {
// login user
checkLogin(email, password);
} else {
// Prompt user to enter credentials
Toast.makeText(getApplicationContext(),
"Please enter the credentials!", Toast.LENGTH_LONG)
.show();
}
}
});
// Link to Register Screen
btnLinkToRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(i);
finish();
}
});
}
/**
* function to verify login details in mysql db
* */
private void checkLogin(final String email, final String password) {
// Tag used to cancel the request
String tag_string_req = "req_login";
pDialog.setMessage("Logging in ...");
showDialog();
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_LOGIN, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
// user successfully logged in
// Create login session
session.setLogin(true);
// 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 main activity
Intent intent = new Intent(LoginActivity.this,
MainActivity.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();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("email", email);
params.put("password", password);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
MainActivity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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(MainActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
}
I made an app that requires the user to register. The first time user opens the app - login screen opens. They need to click on the "go to register" button to go to register activity. After they register, they are automatically logged in.
Now here is the issue - when the user first registers he is sent to MainActivity. He should press back and the app should close. But when he tries to exit the app he presses the back button and instead of app closing it goes back to login screen.
The next time I try to sign in, I have no problem - it goes straight to the MainActivity.
This is how my activities look like:
LoginActivity:
public class LoginActivity extends AppCompatActivity {
private static final String TAG = "LoginActivity";
private static final int REQUEST_REGISTER = 0;
#InjectView(R.id.input_email) EditText _emailText;
#InjectView(R.id.input_password) EditText _passwordText;
#InjectView(R.id.btn_login) Button _loginButton;
#InjectView(R.id.link_register) TextView _registerLink;
CheckBox checkBoxShowPassword;
private SessionManager session;
private SQLiteHandler db;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
ButterKnife.inject(this);
// SQLite database handler
db = new SQLiteHandler(getApplicationContext());
// Session manager
session = new SessionManager(getApplicationContext());
// Check if user is already logged in or not
if (session.isLoggedIn()) {
// User is already logged in. Take him to main activity
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
_loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = _emailText.getText().toString().trim();
String password = _passwordText.getText().toString().trim();
if (!email.isEmpty() && !password.isEmpty()) {
// login user
login(email, password);
} else {
// Prompt user to enter credentials
Toast.makeText(getApplicationContext(),
"Please enter the credentials!", Toast.LENGTH_LONG)
.show();
}
}
});
// Go to register screen
_registerLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Start the Register activity
Intent intent = new Intent(getApplicationContext(), RegisterActivity.class);
startActivityForResult(intent, REQUEST_REGISTER);
}
});
// Password checkbox
checkBoxShowPassword = (CheckBox) findViewById(R.id.checkBoxShowPassword);
checkBoxShowPassword.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// checkbox status is changed from uncheck to checked.
if (!isChecked) {
// show password
_passwordText.setTransformationMethod(PasswordTransformationMethod.getInstance());
} else {
// hide password
_passwordText.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
}
}
});
}
// Login
public void login(final String email, final String password) {
Log.d(TAG, "Login");
if (!validate()) {
onLoginFailed();
return;
}
// Change to false for disabling after error
_loginButton.setEnabled(true);
String tag_string_req = "req_login";
final ProgressDialog progressDialog = new ProgressDialog(LoginActivity.this,
R.style.AppTheme_Dark_Dialog);
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Authenticating...");
progressDialog.show();
// TODO: Implementing authentication logic
StringRequest strReq = new StringRequest(Request.Method.POST,
AppConfig.URL_LOGIN, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
progressDialog.dismiss();
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);
// 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 main activity
Intent intent = new Intent(LoginActivity.this,
MainActivity.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();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast toast = Toast.makeText(getApplicationContext(),
"Registration failed due to connectivity issues", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
// _loginButton.setEnabled(true);
progressDialog.dismiss();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("email", email);
params.put("password", password);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
#Override
public void onBackPressed() {
// disable going back to the MainActivity
moveTaskToBack(true);
}
public void onLoginSuccess() {
_loginButton.setEnabled(true);
finish();
}
public void onLoginFailed() {
Toast.makeText(getBaseContext(), "Login failed", Toast.LENGTH_LONG).show();
_loginButton.setEnabled(true);
}
// Validation
public boolean validate() {
boolean valid = true;
String email = _emailText.getText().toString();
String password = _passwordText.getText().toString();
if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
_emailText.setError("Enter a valid email address");
valid = false;
} else {
_emailText.setError(null);
}
if (password.isEmpty() || password.length() < 4 || password.length() > 20) {
_passwordText.setError("Enter between 4 and 20 alphanumeric characters");
valid = false;
} else {
_passwordText.setError(null);
}
return valid;
}
}
RegisterActivity
public class RegisterActivity extends AppCompatActivity {
private static final String TAG = "RegisterActivity";
#InjectView(R.id.input_name) EditText _nameText;
#InjectView(R.id.input_email) EditText _emailText;
#InjectView(R.id.input_password) EditText _passwordText;
#InjectView(R.id.btn_register) Button _registerButton;
#InjectView(R.id.link_login) TextView _loginLink;
CheckBox checkBoxShowPassword;
private SessionManager session;
private SQLiteHandler db;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
ButterKnife.inject(this);
// 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(RegisterActivity.this,
MainActivity.class);
startActivity(intent);
finish();
}
// Register button
_registerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name = _nameText.getText().toString().trim();
String email = _emailText.getText().toString().trim();
String password = _passwordText.getText().toString().trim();
String phone = getMyPhoneNumber();
if (!name.isEmpty() && !email.isEmpty() && !password.isEmpty()) {
register(name, email, password, phone);
} else {
Toast.makeText(getApplicationContext(),
"Please enter your details!", Toast.LENGTH_LONG)
.show();
}
}
});
// Go to login screen
_loginLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Finish the registration screen and return to the Login activity
finish();
}
});
// Password checkbox
checkBoxShowPassword = (CheckBox) findViewById(R.id.checkBoxShowPassword);
checkBoxShowPassword.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// checkbox status is changed from uncheck to checked.
if (!isChecked) {
// show password
_passwordText.setTransformationMethod(PasswordTransformationMethod.getInstance());
} else {
// hide password
_passwordText.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
}
}
});
}
// Register
public void register(final String name, final String email, final String password, final String phone) {
Log.d(TAG, "Register");
if (!validate()) {
onRegisterFailed();
return;
}
_registerButton.setEnabled(false);
String tag_string_req = "req_register";
final ProgressDialog progressDialog = new ProgressDialog(RegisterActivity.this,
R.style.AppTheme_Dark_Dialog);
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Creating Account...");
progressDialog.show();
// TODO: Implementing register logic
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());
progressDialog.dismiss();
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);
//TODO: insert contacts to local db
String[] PROJECTION = new String[] {
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER
};
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, PROJECTION, null, null, null);
while (phones.moveToNext()) {
if (phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER) != -1)
{
String username = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
db.addContact(username, phoneNumber);
}
}
phones.close();
Toast.makeText(getApplicationContext(), "Registration successful!", Toast.LENGTH_LONG).show();
// Auto login
session.setLogin(true);
// Launch login activity
Intent intent = new Intent(
RegisterActivity.this,
MainActivity.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 toast = Toast.makeText(getApplicationContext(),
"Registration failed due to connectivity issues", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
_registerButton.setEnabled(true);
progressDialog.dismiss();
}
}) {
#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);
params.put("phone", phone);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
public void onRegisterSuccess() {
_registerButton.setEnabled(true);
setResult(RESULT_OK, null);
finish();
}
public void onRegisterFailed() {
Toast.makeText(getBaseContext(), "Registration failed", Toast.LENGTH_LONG).show();
_registerButton.setEnabled(true);
}
// Validation
public boolean validate() {
boolean valid = true;
String name = _nameText.getText().toString();
String email = _emailText.getText().toString();
String password = _passwordText.getText().toString();
if (name.isEmpty() || name.length() < 3) {
_nameText.setError("Enter at least 3 characters");
valid = false;
} else {
_nameText.setError(null);
}
if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
_emailText.setError("Enter a valid email address");
valid = false;
} else {
_emailText.setError(null);
}
if (password.isEmpty() || password.length() < 4 || password.length() > 20) {
_passwordText.setError("Enter between 4 and 20 alphanumeric characters");
valid = false;
} else {
_passwordText.setError(null);
}
return valid;
}
// Get users phone number
private String getMyPhoneNumber() {
TelephonyManager tMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String MyPhoneNumber = "0000000000";
try
{
MyPhoneNumber =tMgr.getLine1Number();
}
catch(NullPointerException ex)
{
}
if(MyPhoneNumber.equals("")){
MyPhoneNumber = tMgr.getSubscriberId();
}
return MyPhoneNumber;
}
private String getMy10DigitPhoneNumber() {
String s = getMyPhoneNumber();
return s.substring(2);
}
}
As per my idea you just do one thing that when you are passing from login activity to register_activity just finish the login_activity like this
// Go to register screen
_registerLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Start the Register activity
Intent intent = new Intent(getApplicationContext(), RegisterActivity.class);
startActivityForResult(intent, REQUEST_REGISTER);
LoginActivity.this.finish();
}
});
If you still facing the same problem then when you are opens the login_activity first then create a variable of that class and assign the value to that variable like this
public static LoginActivity mLogin_activity;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLogin_activity=LoginActivity.this;
Then check this value is null or not in onBackPressed() method in Main_Activity if that value is null then finish that main_activity otherwise finish that login_activity too; Something like this:
#Override
public void onBackPressed() {
super.onBackPressed();
if (LoginActivity.mLogin_activity!=null) {
LoginActivity.mLogin_activity.finish();
MainActivity.this.finish();
}else {
MainActivity.this.finish();
}
}
Hope i had answered your question...
when you write
Intent intent = new Intent(getApplicationContext(), RegisterActivity.class);
startActivityForResult(intent, REQUEST_REGISTER);
This must need to override onActivityResult method to handle that result.
In that code you just write
Intent intent = new Intent(getApplicationContext(), RegisterActivity.class);
startActivity(intent);
finish();
I hope this could be help you.
For me, I found out that I was calling a variable from another activity which was on my Register.xml (the progressbarBtn) instead of the progressbar that I inserted on Login.Java which was ProgressbarBtn3
thats why it is taking me back to the register page
I am trying to develop a chat application with a login and registration. The app is working without any errors, when I register it adds the right information in SQLite but when i log in with those details the app says "Logging in" but nothing happens. Does anyone know what is wrong with my code?
LoginActivity.java
public class LoginActivity extends Activity {
// LogCat tag
private static final String TAG = RegisterActivity.class.getSimpleName();
private Button btnLogin;
private Button btnLinkToRegister;
private EditText inputEmail;
private EditText inputPassword;
private ProgressDialog pDialog;
private SessionManager session;
#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(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String email = inputEmail.getText().toString();
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(),
RegisterActivity.class);
startActivity(i);
finish();
}
});
}
/**
* function to verify login details in mysql db
* */
private void checkLogin(final String email, final String password) {
// Tag used to cancel the request
String tag_string_req = "req_login";
pDialog.setMessage("Logging in ...");
showDialog();
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_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(LoginActivity.this,
MainActivity.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();
}
}
MainActivity.java
public class MainActivity extends Activity
{
private TextView txtName;
private TextView txtEmail;
private Button btnLogout;
private SQLiteHandler db;
private SessionManager session;
public Socket sender;
public BufferedReader br;
public PrintStream bw;
class SocketListener implements Runnable
{
String str;
public void run()
{
try
{
sender = new Socket("127.0.0.1", 1234);
br = new BufferedReader (new InputStreamReader(sender.getInputStream()));
bw = new PrintStream (sender.getOutputStream());
bw.println("Connected");
while (true)
{
final TextView t = (TextView)findViewById(R.id.textView);
String s = br.readLine ();
CharSequence cs = t.getText ();
str = cs + "\r\n" + s;
Log.i("Chat-str:", str);
t.post(new Runnable()
{
public void run()
{
t.setText(str);
}
}
);
}
}
catch (IOException e)
{
Log.e(getClass().getName(), e.getMessage());
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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();
}
});
TextView tv = (TextView)findViewById(R.id.textView);
tv.setMovementMethod(new ScrollingMovementMethod());
Button send1 = (Button)findViewById(R.id.button);
send1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
final EditText et = (EditText)findViewById(R.id.editText);
Editable e = et.getText();
final String s = e.toString();
new Thread ()
{
public void run ()
{
bw.println (s);
}
}.start();
}
});
Thread t = new Thread (new SocketListener ());
t.start();
}
/**
* 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(MainActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
}
it doesnt look like you ever log them in. look here
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();
}
}
});
what is checkLogin(email, password);
and if it is returning a boolean you should be saying
if(checkLogin){
//log them in
}
can you post the checklogin code?
I am developing an android app in which , a sigin , and signup option is there . when a new user enters to the application for first time he needs to signup.. when he presses the sigin option he is directed to the account creation page.where he needs to gve the username,password and mobile number. all these three values are stored in sqlite ( applications memory ) and a passcode is created and send to the mobile number provided by user. and next page is registration page, where users username and password is checked along with the passcode which he recieved. This process I did to verify the mobile number. So my problem is if once the user created the account and go back to signin option and enter the username and password .. he is directing to the applications first page... because when account creation process is done his details are saved in the applications databse for verification. so user dont need to verify the passcode.. so is there any way to make the signin button view only after a registration process.. or something like that ... I am posting here the siginactivity, signupactivity and register activity.. pls check it and if found any error pls help me...
Signup Activity
public class SignUpActivity extends Activity
{
EditText editTextUserName,editTextPassword,editTextConfirmPassword, editMobileNumber;
Button btnCreateAccount;
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
Random r = new Random();
int number =r.nextInt(9999 - 1000) + 1000;
LoginDataBaseAdapter loginDataBaseAdapter;
private static String url_create_data = "http://iascpl.com/app/create_data1.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.signup_xm);
// get Instance of Database Adapter
loginDataBaseAdapter=new LoginDataBaseAdapter(this);
loginDataBaseAdapter=loginDataBaseAdapter.open();
// Get References of Views
editTextUserName=(EditText)findViewById(R.id.editTextUserName);
editTextPassword=(EditText)findViewById(R.id.editTextPassword);
editTextConfirmPassword=(EditText)findViewById(R.id.editTextConfirmPassword);
editMobileNumber = (EditText)findViewById(R.id.mobileNumber);
btnCreateAccount=(Button)findViewById(R.id.buttonCreateAccount);
btnCreateAccount.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String name=editTextUserName.getText().toString();
String password=editTextPassword.getText().toString();
String confirmPassword=editTextConfirmPassword.getText().toString();
String phoneNo = editMobileNumber.getText().toString();
String sms = Integer.toString(number);
//Intent intent = new Intent(SignUpActivity.this, RegisterActivity.class);
//intent.putExtra("number", sms + "");
//startActivity(intent);
//new CreateNewProduct().execute();
StringTokenizer st=new StringTokenizer(phoneNo,",");
while (st.hasMoreElements())
{
String tempMobileNumber = (String)st.nextElement();
if(tempMobileNumber.length()>0 && sms.trim().length()>0)
{
sendSMS(tempMobileNumber, sms);
}
else
{
Toast.makeText(getBaseContext(),
"Please enter both phone number and message.",
Toast.LENGTH_SHORT).show();
}
}
// check if any of the fields are vacant
if(name.equals("")||password.equals("")||confirmPassword.equals(""))
{
Toast.makeText(getApplicationContext(), "Field Vaccant", Toast.LENGTH_LONG).show();
return;
}
// check if both password matches
if(!password.equals(confirmPassword))
{
Toast.makeText(getApplicationContext(), "Password does not match", Toast.LENGTH_LONG).show();
return;
}
else
{
// Save the Data in Database
loginDataBaseAdapter.insertEntry(name, password);
Toast.makeText(getApplicationContext(), "Passcode is sent to the mobile number you provided. ", Toast.LENGTH_LONG).show();
new CreateNewProduct().execute();
// Intent intent = new Intent(SignUpActivity.this, RegisterActivity.class);
// intent.putExtra("number", sms + "");
// startActivity(intent);
}
}
});
}
private void sendSMS(String phoneNumber, String message)
{
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
new Intent(SENT), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
new Intent(DELIVERED), 0);
//---when the SMS has been sent---
registerReceiver(new BroadcastReceiver(){
#Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode())
{
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS sent",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getBaseContext(), "Generic failure",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getBaseContext(), "No service",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getBaseContext(), "Null PDU",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getBaseContext(), "Radio off",
Toast.LENGTH_SHORT).show();
break;
}
}
},new IntentFilter(SENT));
//---when the SMS has been delivered---
registerReceiver(new BroadcastReceiver(){
#Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode())
{
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS delivered",
Toast.LENGTH_SHORT).show();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(getBaseContext(), "SMS not delivered",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(DELIVERED));
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
loginDataBaseAdapter.close();
}
/**
* Background Async Task to Create new product
* */
class CreateNewProduct extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SignUpActivity.this);
pDialog.setMessage("Creating a new account..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
String name = editTextUserName.getText().toString();
String password = editTextPassword.getText().toString();
String mobile = editMobileNumber.getText().toString();
String sms = Integer.toString(number);
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("password", password));
params.add(new BasicNameValuePair("mobile", mobile));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_data,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(SignUpActivity.this, RegisterActivity.class);
i.putExtra("number", sms + "");
startActivity(i);
//closing this screen
//finish();
} else {
// failed to create product
return "false";
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
/*protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}*/
protected void onPostExecute(String result)
{
// TODO Auto-generated method stub
super.onPostExecute(result);
if (result == "false")
Toast.makeText(SignUpActivity.this, "User Name already exists. Please choose another user name ", Toast.LENGTH_LONG).show();
pDialog.dismiss();
}
}
}
Register Activity
public class RegisterActivity extends Activity {
LoginDataBaseAdapter loginDataBaseAdapter;
Button btnReg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register_xm);
loginDataBaseAdapter=new LoginDataBaseAdapter(this);
loginDataBaseAdapter=loginDataBaseAdapter.open();
btnReg = (Button) findViewById (R.id.buttonRegister);
final EditText editTextUserName=(EditText)findViewById(R.id.editTextUserNameToLogin);
final EditText editTextPassword=(EditText)findViewById(R.id.editTextPasswordToLogin);
final EditText editTextMobileNumber = (EditText)findViewById(R.id.editText1);
btnReg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String userName=editTextUserName.getText().toString();
String password=editTextPassword.getText().toString();
String mobileNumber = editTextMobileNumber.getText().toString();
// fetch the Password form database for respective user name
String storedPassword=loginDataBaseAdapter.getSinlgeEntry(userName);
String sd = getIntent().getStringExtra("number");
String name = editTextUserName.getText().toString();
// check if the Stored password matches with Password entered by user
if(password.equals(storedPassword) && (mobileNumber.equals(sd)))
{
Toast.makeText(RegisterActivity.this, "Congrats: Registration Successfull", Toast.LENGTH_LONG).show();
Intent in = new Intent(RegisterActivity.this,HomePageActivity.class);
startActivity(in);
}
else
{
Toast.makeText(RegisterActivity.this, "User Name, Passcode or Password does not match", Toast.LENGTH_LONG).show();
}
}
});
}
#Override
protected void onDestroy()
{
super.onDestroy();
// Close The Database
loginDataBaseAdapter.close();
}
}
Signin activity
public class SignInActivity extends Activity
{
/*LoginDataBaseAdapter loginDataBaseAdapter;*/
Button btnsignin;
EditText username,userpassword;
TextView txtName;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
// single product url
private static String url_get_name = "http://iascpl.com/app/get_name_details.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCT = "product";
private static final String TAG_PASSWORD = "password";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.signin_xm);
/*loginDataBaseAdapter=new LoginDataBaseAdapter(this);
loginDataBaseAdapter=loginDataBaseAdapter.open();*/
btnsignin = (Button) findViewById ( R.id.button401);
username=(EditText)findViewById(R.id.editText401);
userpassword=(EditText)findViewById(R.id.editText402);
btnsignin.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new GetProductDetails().execute();
/* String storedPassword=loginDataBaseAdapter.getSinlgeEntry(userName);*/
// check if the Stored password matches with Password entered by user
/*if(password.equals(storedPassword))
{
Toast.makeText(SignInActivity.this, "Login Successfull", Toast.LENGTH_LONG).show();
Intent i = new Intent(SignInActivity.this,HomePageActivity.class);
startActivity(i);
}
else
{
Toast.makeText(SignInActivity.this, "User Name or Password does not match", Toast.LENGTH_LONG).show();
}*/
}
});
}
class GetProductDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SignInActivity.this);
pDialog.setMessage("Loading the result... Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Getting product details in background thread
* */
protected String doInBackground(String... args)
{
String pid=username.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("pid", pid));
// getting product details by making HTTP request
// Note that product details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(
url_get_name, "GET", params);
// check your log for json response
Log.d("Single Product Details", json.toString());
// json success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received product details
JSONArray productObj = json
.getJSONArray(TAG_PRODUCT); // JSON Array
// get first product object from JSON Array
final JSONObject product = productObj.getJSONObject(0);
txtName = (TextView) findViewById(R.id.textView1);
// product with this pid found
// Edit Text
runOnUiThread(new Runnable() {
#Override
public void run()
{
// TODO Auto-generated method stub
try {
txtName.setText(product.getString(TAG_PASSWORD));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}else{
// product with pid not found
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/*
#Override
protected void onDestroy()
{
super.onDestroy();
// Close The Database
loginDataBaseAdapter.close();
}*/
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String result)
{
// dismiss the dialog once got all details
/*super.onPostExecute(result);
if (result == "false")
Toast.makeText(SignInActivity.this, "User Name already exists. Please choose another user name ", Toast.LENGTH_LONG).show();*/
pDialog.dismiss();
}
}
}
I understood your problem ... You are saving your signup details in sqlite so when user entering username and password it is saved in sqlite and next step is registration process where user has to enter the secret code.. But as as username and password is saved in sqlite user can press back button and go back and login with username and password and avoid registration process...
Here you can do something like this. use shared preference
for ex:In registration page after successful registration give value l.
SharedPreferences set = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor ed = set.edit();
ed.putString("l", "l");
ed.commit();
and check in your home page whether the value is l or not if value is l only then make your signin button visible. You can use something like this for making the button invisible.
btn3.setVisibility(View.INVISIBLE);
btn4.setVisibility(View.INVISIBLE);