Hi In my application login form with username and password checking username and password existing in the database or not.If Exist means showing one text message user found and I want to move to next activity.otherwise No such user found.
Now,clicking login button it's showing user found and not moving to next activity.
Can any one please help me to resolve this issuse.
Login.java
public class Login extends Activity {
Button 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;
TextView tv;
String username,password;
HttpPost httppost;
StringBuffer buffer;
String data="";
HttpResponse response;
HttpClient httpclient;
CheckBox mCbShowPwd;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
login = (Button)findViewById(R.id.login);
usname = (EditText)findViewById(R.id.username);
pword= (EditText)findViewById(R.id.password);
tv = (TextView)findViewById(R.id.tv);
mCbShowPwd = (CheckBox) findViewById(R.id.cbShowPwd);
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) {
String username = usname.getText().toString();
String password = pword.getText().toString();
if (username.equals("") || password.equals("")) {
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{
final String queryString = "username=" + username + "&password="
+ password;
final String data = DatabaseUtility.executeQueryPhp("login",queryString);
System.out.println("data :: "+data);
tv.setText("Response from PHP : " + data);
if(data.equalsIgnoreCase("User Found"))
{
Toast.makeText(Login.this,"Login Success", Toast.LENGTH_SHORT).show();
Intent i = new Intent(Login.this, Home.class);
startActivity(i);
}
else
{
Toast.makeText(getApplicationContext(),"User not found, check query", Toast.LENGTH_SHORT).show();
}
}
}
});
}
private boolean CheckPassword(String password) {
return PASSWORD_PATTERN.matcher(password).matches();
}
private boolean CheckUsername(String username) {
return USERNAME_PATTERN.matcher(username).matches();
}
}
I think you are doing mistake here :
if(data.equalsIgnoreCase("User Found")){
Toast.makeText(getApplicationContext(),"Login Success", Toast.LENGTH_SHORT).show();
Intent i = new Intent(getApplicationContext(), Home.class);
startActivity(i);
}
in place of getApplicationContext() write :
if(data.equalsIgnoreCase("User Found")){
Toast.makeText(Login.this,"Login Success", Toast.LENGTH_SHORT).show();
Intent i = new Intent(getApplicationContext(), Home.class);
startActivity(i);
I think you are missing
<activity
android:name="package_name.Home"></activity>
In AndroidManifest.xml
You must define all activities in AndroidManifest.xml.
EDIT
System.out.println("data :: "+data);
if(data.equalsIgnoreCase("User Found"))
{
Toast.makeText(getApplicationContext(),"Login Success", Toast.LENGTH_SHORT).show();
Intent i = new Intent(getApplicationContext(), Home.class);
startActivity(i);
}
else
{
Toast.makeText(getApplicationContext(),"User not found, check query", Toast.LENGTH_SHORT).show();
}
Related
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
Here is my Login Activity code.
public class LoginActivity extends AppCompatActivity {
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
final EditText username = (EditText) findViewById(R.id.txtUsername);
final EditText password = (EditText) findViewById(R.id.txtRegisPassword);
final Bundle extras = getIntent().getExtras();
Button login = (Button) findViewById(R.id.btnLogin);
Button registerNow = (Button) findViewById(R.id.btnRegisterNow);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ArrayList<String> data = (ArrayList<String>) extras.getSerializable("array_list"); //this code always null at starter
if(extras!=null) {
if (username.getText().toString().length() == 0 || password.getText().toString().length() == 0) {
Toast.makeText(LoginActivity.this, "Username and Password must be filled!", Toast.LENGTH_SHORT).show();
} else if (!data.contains(username.getText().toString()) || !data.contains(password.getText().toString())) {
Toast.makeText(LoginActivity.this, "Username and Password must be registered!", Toast.LENGTH_SHORT).show();
} else {
Intent intent = new Intent(LoginActivity.this, MainMenu.class);
startActivity(intent);
}
}
}
});
registerNow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(intent);
}
});
}
}
And this is my register form code.
public class RegisterActivity extends AppCompatActivity {
ArrayList<String> addArray = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
final EditText Username = (EditText) findViewById(R.id.txtRegisUsername);
final EditText Password = (EditText) findViewById(R.id.txtRegisPassword);
final EditText ConfirmPassword = (EditText) findViewById(R.id.txtConfirmPassword);
final EditText FullName = (EditText) findViewById(R.id.txtRegisFullName);
final EditText PhoneNumber = (EditText) findViewById(R.id.txtRegisPhone);
final EditText DateOfBirth = (EditText) findViewById(R.id.txtRegisDateOfBirth);
final EditText Address = (EditText) findViewById(R.id.txtRegisAddress);
final RadioGroup rdGroup = (RadioGroup) findViewById(R.id.radioGroup);
RadioButton rdMale = (RadioButton) findViewById(R.id.rdMale);
RadioButton rdFemale = (RadioButton) findViewById(R.id.rdFemale);
Button Register = (Button) findViewById(R.id.btnRegister);
Button LoginNow = (Button) findViewById(R.id.btnLoginNow);
Register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(Username.getText().toString().length()==0 || Password.getText().toString().length()==0 ||
ConfirmPassword.getText().toString().length()==0 || FullName.getText().toString().length()==0 ||
PhoneNumber.getText().toString().length()==0 || DateOfBirth.getText().toString().length()==0 ||
Address.getText().toString().length()==0){
Toast.makeText(RegisterActivity.this, "All fields must be filled!", Toast.LENGTH_SHORT).show();
}else if(Username.getText().toString().length()<5 || Username.getText().toString().length()>20){
Toast.makeText(RegisterActivity.this, "Username must be between 5 and 20 characters.", Toast.LENGTH_SHORT).show();
}else if(Password.getText().toString().length()<5 || Password.getText().toString().length()>20){
Toast.makeText(RegisterActivity.this, "Password must be between 5 and 20 characters.", Toast.LENGTH_SHORT).show();
}else if(!ConfirmPassword.getText().toString().equals(Password.getText().toString())){
Toast.makeText(RegisterActivity.this, "Confirm Password must be match with Password.", Toast.LENGTH_SHORT).show();
}else if(!Address.getText().toString().endsWith(" Street")){
Toast.makeText(RegisterActivity.this, "Address must be ends with “Street”.", Toast.LENGTH_SHORT).show();
}else if(addArray.contains(Username.getText().toString())){
Toast.makeText(RegisterActivity.this, "Username already registered.", Toast.LENGTH_SHORT).show();
}else{
addArray.add(Username.getText().toString());
addArray.add(Password.getText().toString());
//ArrayAdapter<String> adapter = new ArrayAdapter<String>(RegisterActivity.this, android.R.layout.simple_list_item_1, addArray);
Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
intent.putExtra("array_list", addArray);
startActivity(intent);
}
}
});
LoginNow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
startActivity(intent);
}
});
}
}
please help me, i'm trying everything but can't solved my problem.
"my login form always forced to close because the value in register form still null at start", but if i register the user data for first, the login form works fine.
You need to check whether your bundle is null or not, then use it.
Secondly, you should use getStringArrayList instead of getSerializable as follows :
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(extras!=null) {
ArrayList<String> data = extras.getStringArrayList("array_list"); // use getStringArrayList instead of getSerializable
if (username.getText().toString().length() == 0 || password.getText().toString().length() == 0) {
Toast.makeText(LoginActivity.this, "Username and Password must be filled!", Toast.LENGTH_SHORT).show();
} else if (!data.contains(username.getText().toString()) || !data.contains(password.getText().toString())) {
Toast.makeText(LoginActivity.this, "Username and Password must be registered!", Toast.LENGTH_SHORT).show();
} else {
Intent intent = new Intent(LoginActivity.this, MainMenu.class);
startActivity(intent);
}
}
}
});
i have checked your code as per my debug report your list object is getting null when getting the list back.
you can also try #Suraj Makhija code. otherwise i am telling you
To resolve this issue you can approach 2 way.
i) you can use ArrayList<CharSequence>() instead of ArrayList<String>() this is the most simple why because it don't require any additional type casting to get it again which you have done here which cause NullPointerException some times.
ArrayList<String> data = (ArrayList<String>) extras.getSerializable("array_list");
there is two method to set data and get data from intent -->
// dataList type is ArrayList<CharSequence>()
intent.putCharSequenceArrayListExtra(KEY,dataList)
intent.getCharSequenceArrayExtra(KEY)//in return you will get list here
ii) 2nd is as a suggestion i will tell you to use a modeled array list with getter and setter it will help you much more instead of simple String type array list.
Example :
public class KeyValueModel implements Parcelable {
String mKey,mValue;
protected KeyValueModel(Parcel in) {
mKey = in.readString();
mValue = in.readString();
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(mKey);
dest.writeString(mValue);
}
#Override
public int describeContents() {
return 0;
}
public static final Creator<KeyValueModel> CREATOR = new Creator<KeyValueModel>() {
#Override
public KeyValueModel createFromParcel(Parcel in) {
return new KeyValueModel(in);
}
#Override
public KeyValueModel[] newArray(int size) {
return new KeyValueModel[size];
}
};
public String getmKey() {
return mKey;
}
public void setmKey(String mKey) {
this.mKey = mKey;
}
public String getmValue() {
return mValue;
}
public void setmValue(String mValue) {
this.mValue = mValue;
}
}
so, this is for my solution, and worked.. hope will help the others
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(extras!=null) { //this is for if i've register an account before (aka not null again after register).
ArrayList<String> data = extras.getStringArrayList("array_list");
if (username.getText().toString().length() == 0 || password.getText().toString().length() == 0) {
Toast.makeText(LoginActivity.this, "Username and Password must be filled!", Toast.LENGTH_SHORT).show();
} else if (!data.contains(username.getText().toString()) || !data.contains(password.getText().toString())) {
Toast.makeText(LoginActivity.this, "Username and Password must be registered!", Toast.LENGTH_SHORT).show();
} else {
Intent intent = new Intent(LoginActivity.this, MainMenu.class);
startActivity(intent);
}
} else { //this for null condition
ArrayList<String> nullData = new ArrayList<String>();
nullData.add(username.getText().toString());
nullData.add(password.getText().toString());
if (username.getText().toString().length() == 0 || password.getText().toString().length() == 0) {
Toast.makeText(LoginActivity.this, "Username and Password must be filled!", Toast.LENGTH_SHORT).show();
} else if (!nullData.equals(null)){
Toast.makeText(LoginActivity.this, "Username and Password must be registered!", Toast.LENGTH_SHORT).show();
}
}
}
});
i need to store user login and password details in shared preference but i am getting error. I need to maintain user login details in session. When user login user mail and password should be get stored in edit text. From next time user can click on login button to enter directly. What i need to do now. Here is my code. When i try below code i am getting unfortunately closed error. Where i need to modify the code. What is the problem in this code.
public class MainActivity extends Activity {
Button b;
EditText email,password;
HttpPost httppost;
StringBuffer buffer;
SharedPreferences sharedpreferences;
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String Name = "nameKey";
public static final String Phone = "phoneKey";
String email1,passw;
SharedPreferences sh_Pref;
Editor toEdit;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;
DBHelper db = new DBHelper(this);
private boolean isValidEmaillId(String email){
return Pattern.compile("^(([\\w-]+\\.)+[\\w-]+|([a-zA-Z]{1}|[\\w-]{2,}))#"
+ "((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
+ "[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\."
+ "([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
+ "[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
+ "([a-zA-Z]+[\\w-]+\\.)+[a-zA-Z]{2,4})$").matcher(email).matches();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button)findViewById(R.id.Button01);
email = (EditText)findViewById(R.id.username);
password= (EditText)findViewById(R.id.password);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(!isValidEmaillId(email.getText().toString().trim())){
Toast.makeText(getApplicationContext(), "Invalid Email Address", Toast.LENGTH_SHORT).show();
}
else if(password.getText().toString().equals(""))
{
Toast.makeText(getApplicationContext(), "Please enter password", Toast.LENGTH_SHORT).show();
}
else
{
email1 = email.getText().toString().trim();
passw = password.getText().toString().trim();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, email1);
editor.putString(Phone, passw);
editor.commit();
System.out.println("sharde :" +Name+Phone);
dialog = ProgressDialog.show(MainActivity.this, "",
"Validating user...", true);
new Thread(new Runnable() {
public void run() {
login();
}
}).start();
}
}
});
}
void login(){
try{
final User user = new User();
httpclient=new DefaultHttpClient();
httppost= new HttpPost("http://ip:8080/ActCFWeb/login"); // make sure the url is correct.
//add your data
nameValuePairs = new ArrayList<NameValuePair>(2);
// Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar,
nameValuePairs.add(new BasicNameValuePair("email",email1)); // $Edittext_value = $_POST['Edittext_value'];
nameValuePairs.add(new BasicNameValuePair("pass",passw));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Execute HTTP Post Request
System.out.println(response);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost, responseHandler);
System.out.println("Response : " + response);
runOnUiThread(new Runnable() {
public void run() {
dialog.dismiss();
}
});
if(response.contains("success")){
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(MainActivity.this,"Login Success", Toast.LENGTH_SHORT).show();
}
});
Intent nextScreen = new Intent(getApplicationContext(), FeedBack.class);
//Sending data to another Activity
nextScreen.putExtra("email", email.getText().toString());
Log.e("n", email.getText()+"."+ email.getText());
startActivity(nextScreen);
}else{
showAlert();
}
}catch(Exception e){
dialog.dismiss();
System.out.println("Exception : " + e.getMessage());
}
}
public void showAlert(){
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Login Error.");
builder.setMessage("User not Found.")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
public boolean isOnline() {
ConnectivityManager conMgr = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = conMgr.getActiveNetworkInfo();
if(netInfo == null || !netInfo.isConnected() || !netInfo.isAvailable()){
Toast.makeText(getApplicationContext(), "No Internet connection!", Toast.LENGTH_LONG).show();
return false;
}
return true;
}
}
I suppose that You call views methods from thread. You have login method in witch you probably call to dialog or other views .You cannot access from not main thread to ui elements. You have to use handler or asynck task.
May be you are talking about this
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, email1);
editor.putString(Phone, passw);
editor.commit();
System.out.println("sharde :" +sharedpreferences.getString(Name, "def").toString()+ ", "sharedpreferences.getString(Phone, "def");
Getting values from SharedPreferences storage.
SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
String emailString = sharedPreferences.getString("email", null);
String passwordString = sharedPreferences.getString("password", null);
In the onCreate method, first check whether the preferences has values for email and password.
if((emailString != null) && (passwordString != null)) {
//Populate the email and password edit texts using stored email and password values.
etEmail.setText(emailString);
etPassword.setText(passwordString);
}
Starting an activity should be performed in main(UI) thread. You can use Handler or runOnUiThread.
if(response.contains("success")){
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(MainActivity.this,"Login Success", Toast.LENGTH_SHORT).show();
Intent nextScreen = new Intent(getApplicationContext(), FeedBack.class);
//Sending data to another Activity
nextScreen.putExtra("email", email.getText().toString());
Log.e("n", email.getText()+"."+ email.getText());
startActivity(nextScreen);
}
});
}else{
showAlert();
}
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);
}
});
updated version my issues right now are the fact my login button doesn't do anything when i press it and also i want to be able for my login screen to verify if an account was created during my registration activity and access its info and processed to my main class
my login screen
public class LoginScreen extends Activity {
private Button btnLogin;
private TextView registerScreen;
private LoginDataBaseAdapter dataBaseAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setting default screen to login.xml
setContentView(R.layout.login);
registerScreen = (TextView) this.findViewById(R.id.link_to_register);
btnLogin = (Button) findViewById(R.id.btnLogin);
// create a instance of SQLite Database
dataBaseAdapter = new LoginDataBaseAdapter(this);
dataBaseAdapter.open();
final Dialog dialog = new Dialog(LoginScreen.this);
dialog.setContentView(R.layout.login);
dialog.setTitle("Login");
// get the References of views
final EditText loginUsername = (EditText) dialog
.findViewById(R.id.liUsername);
final EditText loginPassword = (EditText) dialog
.findViewById(R.id.liPassword);
btnLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String username = loginUsername.getText().toString();
String password = loginPassword.getText().toString();
login(username, password);
}
private void login(String username, String password) {
// fetch the Password form database for respective user name
String storedPassword = dataBaseAdapter
.getSingleEntry(username);
// check if the Stored password matches with Password entered by
// user
if (password.equals(storedPassword)) {
Toast.makeText(LoginScreen.this,
"Congrats: Login Successful", Toast.LENGTH_LONG)
.show();
dialog.dismiss();
Intent i = new Intent(LoginScreen.this, MainPage.class);
startActivity(i);
} else {
Toast.makeText(LoginScreen.this,
"User Name or Password does not match",
Toast.LENGTH_LONG).show();
}
// TODO Auto-generated method stub
}
});
registerScreen.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// This called whenever btnlogin is clicked:
startActivity(new Intent(LoginScreen.this, SignUp.class));
}
});
}
#Override
protected void onDestroy() {
try {
super.onDestroy();
dataBaseAdapter.close();
} catch (Exception e) {
Log.e("onDestroy - Error", e.getMessage());
}
}
}
and my registration class incase you would like to see it
public class SignUp extends Activity {
private EditText reg_fullname, reg_username, reg_email, reg_password ;
private Button btnRegister;
private LoginDataBaseAdapter dataBaseAdapter;
private TextView loginScreen;
protected DataBaseHelper DB = new DataBaseHelper(SignUp.this);
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Set View to register.xml
setContentView(R.layout.signup);
reg_fullname = (EditText) findViewById(R.id.reg_fullname);
reg_username = (EditText) findViewById(R.id.reg_username);
reg_email = (EditText) findViewById(R.id.reg_email);
reg_password = (EditText) findViewById(R.id.reg_password);
loginScreen = (TextView) this.findViewById(R.id.link_to_login);
//Listening to Login Screen Link
btnRegister = (Button) findViewById(R.id.btnRegister);
// get Instance of Database Adapter
dataBaseAdapter = new LoginDataBaseAdapter(this);
dataBaseAdapter.open();
loginScreen.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.link_to_login:
startActivity(new Intent(SignUp.this, LoginScreen.class));
finish();
break;
}
}
});
btnRegister.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()){
case R.id.btnRegister:
// I think they have to be final to be used in the onClickListener
final String fullname = reg_fullname.getText().toString();
final String username = reg_username.getText().toString();
final String password = reg_password.getText().toString();
final String email = reg_email.getText().toString();
boolean invalid = false;
if(fullname.equals(""))
{
invalid = true;
Toast.makeText(getApplicationContext(), "Enter your Firstname", Toast.LENGTH_SHORT).show();
}
else
if(username.equals(""))
{
invalid = true;
Toast.makeText(getApplicationContext(), "Please enter your Username", Toast.LENGTH_SHORT).show();
}
else
if(password.equals(""))
{
invalid = true;
Toast.makeText(getApplicationContext(), "Please enter your Password", Toast.LENGTH_SHORT).show();
}
else
if(email.equals(""))
{
invalid = true;
Toast.makeText(getApplicationContext(), "Please enter your Email ID", Toast.LENGTH_SHORT).show();
}
else
{
// btnLogin.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), "Account Successfully Created ", Toast.LENGTH_LONG).show();
Log.d("FULLNAME", fullname);
Log.d("PASSWORD",password);
Log.d("USERNAME",username);
Log.d("EMAIL",email);
Intent i=new Intent(SignUp.this,MainPage.class);
startActivity(i);
// Save the Data in Database
dataBaseAdapter.insertEntry(fullname, username,password,email);
}break;
}
}
});
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
try{
super.onDestroy();
dataBaseAdapter.close();
}catch(Exception e){
Log.e("onDestroy SignUp- Error", e.getMessage());
}
}
private void addEntry(String fullname, String username, String password, String email)
{
SQLiteDatabase db = DB.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("FULLNAME", fullname);
values.put("USERNAME", username);
values.put("PASSWORD", password);
values.put("EMAIL", email);
try
{
db.insert(DataBaseHelper.DATABASE_TABLE_NAME, null, values);
Toast.makeText(getApplicationContext(), "your details submitted Successfully...", Toast.LENGTH_SHORT).show();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
btnLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new login().execute();
}
});
Unless I am not understanding what you are doing I would move your click listener to the onCreate and then call login onClick with your values. So move this to the onCreate and then handle the data in a login(String username, String password) method. Untested but move something like this to the onCreate and remove the listener from the Login method
final Dialog dialog = new Dialog(LoginScreen.this);
dialog.setContentView(R.layout.login);
dialog.setTitle("Login");
// get the References of views
final EditText loginUsername = (EditText) dialog
.findViewById(R.id.liUsername);
final EditText loginPassword = (EditText) dialog
.findViewById(R.id.liPassword);
btnLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String username = loginUsername.getText().toString();
String password = loginPassword.getText().toString();
login(username, password);
}
});