clicking report activity nothing was happening in android - android

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);
}
});

Related

Can't log out on button click on my android app

i made an app using java language, Retrofit2 and REST API for server side. in me API class i have login and register parameters like
public interface ApiInterface {
#FormUrlEncoded
#POST("/login")
void login(#Field("email") String email, #Field("password") String password, Callback<LoginResult> cb);
public static class LoginResult
{
public int status;
public String user_api_hash;
}
#GET("/registration_status")
void registrationStatus(#Query("lang") String lang, Callback<RegistrationStatusResult> cb);
public static class RegistrationStatusResult
{
public int status;
}
#GET("/get_user_data")
void getMyAccountData(#Query("user_api_hash") String user_api_hash, #Query("lang") String lang, Callback<GetMyAccountDataResult> cb);
public static class GetMyAccountDataResult
{
public String email, expiration_date, plan;
public int days_left, devices_limit;
}
my login class is working properly i can login and register any time. when logged in i receive api_kay then it's saved and use in all the app for requests DataSaver.getInstance(LoginActivity.this).save("api_key", loginResult.user_api_hash); my loginActivity looks like :
public class LoginActivity extends AppCompatActivity {
private static final String TAG = "EditObjectActivity";
#Bind(R.id.username)
EditText username;
#Bind(R.id.password)
EditText password;
#Bind(R.id.signin)
Button signin;
#Bind(R.id.register)
Button pwreset;
private String UrlPrefix;
private String customServerAddress="https://voila_voila_mon_url.com/";
ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
final ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if(activeNetwork == null) {
Intent intent = new Intent(LoginActivity.this, NoInternetActivity.class);
startActivity(intent);
}
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_WIFI_STATE}, PackageManager.PERMISSION_GRANTED);
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.INTERNET}, PackageManager.PERMISSION_GRANTED);
progressDialog = new ProgressDialog(this);
signin = (Button) findViewById(R.id.signin);
pwreset = (Button) findViewById(R.id.register);
password = findViewById(R.id.password);
username = findViewById(R.id.username);
String ip = getResources().getString(R.string.ip);
String httpsOn = getResources().getString(R.string.https_on);
String server_base = customServerAddress;
DataSaver.getInstance(LoginActivity.this).save("server_base", server_base);
DataSaver.getInstance(LoginActivity.this).save("server", server_base + "api/");
if (ip.isEmpty()) {
enableRegistration();
}
else {
API.getApiInterface(LoginActivity.this).registrationStatus("en", new Callback<ApiInterface.RegistrationStatusResult>()
{
#Override
public void success(ApiInterface.RegistrationStatusResult result, Response response)
{
if (result.status == 1) {
enableRegistration();
}
}
#Override
public void failure(RetrofitError retrofitError) {
Log.e(TAG, "failure: retrofitError" + retrofitError.getMessage());
Toast.makeText(LoginActivity.this, getString(R.string.errorHappened), Toast.LENGTH_SHORT).show();
}
});
}
signin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(customServerAddress != null) {
String server_base = customServerAddress;
server_base = UrlPrefix + server_base;
DataSaver.getInstance(LoginActivity.this).save("server_base", server_base);
DataSaver.getInstance(LoginActivity.this).save("server", server_base + "api/");
}
API.getApiInterface(LoginActivity.this).login(username.getText().toString(), password.getText().toString(), new Callback<ApiInterface.LoginResult>()
{
#Override
public void success(ApiInterface.LoginResult loginResult, Response response)
{ // progress dialogue
progressDialog = new ProgressDialog(LoginActivity.this);
progressDialog.setMessage("En cours..."); // Setting Message
progressDialog.setTitle("Connexion au serveur"); // Setting Title
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); // Progress Dialog Style Spinner
progressDialog.show(); // Display Progress Dialog
progressDialog.setCancelable(false);
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(10000);
} catch (Exception e) {
e.printStackTrace();
}
progressDialog.dismiss();
}
}).start();
//end progress dialogue
DataSaver.getInstance(LoginActivity.this).save("api_key", loginResult.user_api_hash);
Log.d("LoginActivity", "api_key: " + loginResult.user_api_hash);
if(customServerAddress == null)
{
String url = "https://voila_voila_mon_url.com/";
DataSaver.getInstance(LoginActivity.this).save("server_base", url);
DataSaver.getInstance(LoginActivity.this).save("server", url + "api/");
}
Intent intent = new Intent(LoginActivity.this, MapActivity.class);
startActivity(intent);
finish();
}
#Override
public void failure(RetrofitError retrofitError)
{
Toast.makeText(LoginActivity.this, getString(R.string.wrongLogin), Toast.LENGTH_SHORT).show();
}
});
}
});
}
}
now the thing is i'd look to log out in my mean activity. in my reseachs i have been told that once logged out the api_key in DataSaver.getInstance(LoginActivity.this).save("api_key", loginResult.user_api_hash); should be null like api_key =null.also when i open the app it show that i am logged. i want to log out.here is my example on my_logout button i did this :
disconnect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String log_out = null;
if(DataSaver.getInstance(this).load("api_key") != null){
DataSaver.getInstance(this).load("api_key") == log_out;
finish();
}else{
//Toast.......(Toast with message ->>>>unable to log out).
}
});
This DataSaver.getInstance(this).load("api_key") is used in all the app when requesting for GET method when fetching users datas. the api_key saved in the app allow me to make some requests as said before. but when this is null it's impossible to make requests. i want to destroy the session when logged in by loggin out. if you understand what i say and can help please.
my account activity after logged in
public class MyAccountActivity extends AppCompatActivity
{
#Bind(R.id.back) View back;
#Bind(R.id.expandable_list) ExpandableListView expandable_list;
#Bind(R.id.loading_layout) View loading_layout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_account);
ButterKnife.bind(this);
loading_layout.setVisibility(View.VISIBLE);
API.getApiInterface(this).getMyAccountData((String) DataSaver.getInstance(this).load("api_key"), getResources().getString(R.string.lang), new Callback<ApiInterface.GetMyAccountDataResult>() {
#Override
public void success(ApiInterface.GetMyAccountDataResult dataResult, Response response)
{
MyAccountAdapter adapter = new MyAccountAdapter(MyAccountActivity.this, dataResult);
expandable_list.setAdapter(adapter);
Utils.setGroupClickListenerToNotify(expandable_list, adapter);
loading_layout.setVisibility(View.GONE);
expandable_list.setVisibility(View.VISIBLE);
}
#Override
public void failure(RetrofitError retrofitError) {
Toast.makeText(MyAccountActivity.this, R.string.errorHappened, Toast.LENGTH_SHORT).show();
}
});
}
i did this but it's not enough to log out #Syed Ibrahim
like this
but not working this is juste to stay connected not to log out
if (DataSaver.getInstance(this).load("api_key") == null)
{
startActivity(new Intent(MapActivity.this, LoginActivity.class));
finish();
return;
}
what i need is to set this api_key null whatever the app is running or not.

How to Access Oauth 1.0 ?? I am working on SugarCrm

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

when i am pressing back button(up button) it is showing "app stopped unfortunately" after using volley

#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation);
but1=(Button)findViewById(R.id.btnlogin);
//
final String Token=getIntent().getExtras().getString("token");
// Toast.makeText(getApplicationContext(),Token, Toast.LENGTH_SHORT).show();
final String firstName=getIntent().getExtras().getString("firstname");
//getting cardview data's
String url =
com.android.volley.toolbox.JsonObjectRequest jsonRequest = new com.android.volley.toolbox.JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// the response is already constructed as a JSONObject!
try {
JSONArray obj = response.getJSONArray("result");
int o = obj.length();
Log.v("Length", String.valueOf(o));
for (int i = 0; i < obj.length(); i++) {
JSONObject jsonObject = obj.getJSONObject(i);
//listname.add(jsonObject.getString("templateId"));
listehr.add(jsonObject.getString("templateId"));
listdate.add(jsonObject.getString("startTime"));
listtime.add(jsonObject.getString("category"));
// ehrUid.add(jsonObject.getString("ehrUid"));
List<String> compositionUid = new ArrayList<>();
// String startTime = jsonObject.getString("startTime");
// Log.v("startTime",startTime);
}
Log.v("listtime", String.valueOf(listtime.size()));
Log.v("Response", response.toString());
String total = response.getString("total");
Log.v("Total",total);
String result = response.getString("result");
Log.v("Result",result);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
System.out.println(error);
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
headers.put("Authorization",Token);
return headers;
}
};
com.android.volley.toolbox.Volley.newRequestQueue(NavigationActivity.this).add(jsonRequest);
//
You have to send String Values for these two Keys "token","firstname".
final String Token=getIntent().getExtras().getString("token");
final String firstName=getIntent().getExtras().getString("firstname");
If you cant find it send the code snippet of intent in another class.
Punithapriya this is the code for main activity
public class MainActivity extends AppCompatActivity {
TextView t;
private EditText username;
private EditText password;
EditText showPsd;
CheckBox mCbShowPwd;
public Button but1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//login page using json
but1=(Button)findViewById(R.id.btnlogin);
username=(EditText)findViewById(R.id.editText2);
password=(EditText)findViewById(R.id.btnpass);
but1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//validation for login
if(username.getText().toString().length()==0){
username.setError("Username not entered");
username.requestFocus();
}
else if(password.getText().toString().length()==0){
password.setError("Password not entered");
password.requestFocus();
}
//
String url = ;
JsonObjectRequest jsonRequest = new JsonObjectRequest
(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// the response is already constructed as a JSONObject!
try {
Log.v("Hai", response.toString());
String firstName = response.getString("firstName");
Log.v("firstName", firstName);
String organizationList = response.getString("organizationList");
Log.v("organizationList",organizationList);
String token = response.getString("token");
Log.v("token",token);
Toast.makeText(getApplicationContext(),"Logged in Suceessfully", Toast.LENGTH_SHORT).show();
Intent i = new Intent(MainActivity.this,NavigationActivity.class);
i.putExtra("token",token);
i.putExtra("firstname",firstName);
startActivity(i);
finish();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
System.out.println(error);
Toast.makeText(getApplicationContext(),"Login Error", Toast.LENGTH_SHORT).show();
}
});
Volley.newRequestQueue(MainActivity.this).add(jsonRequest);
}
});
//password
showPsd = (EditText) findViewById(R.id.btnpass);
// get the show/hide password Checkbox
mCbShowPwd = (CheckBox) findViewById(R.id.btnshow);
// add onCheckedListener on checkbox
// when user clicks on this checkbox, this is the handler.
mCbShowPwd.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// checkbox status is changed from uncheck to checked.
if (!isChecked) {
// show password
showPsd.setTransformationMethod(PasswordTransformationMethod.getInstance());
EditText et = (EditText)findViewById(R.id.btnpass);
et.setSelection(et.getText().length());
} else {
// hide password
showPsd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
EditText et = (EditText)findViewById(R.id.btnpass);
et.setSelection(et.getText().length());
}
}
});
//
//Textview calling
final TextView regLink=(TextView)findViewById(R.id.register1);
final TextView forLink=(TextView)findViewById(R.id.forgot);
//register
regLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent regIntent=new Intent(MainActivity.this,RegisterActivity.class);
MainActivity.this.startActivity(regIntent);
}
});
//forgot
forLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent forIntent=new Intent(MainActivity.this,ForgotActivity.class);
MainActivity.this.startActivity(forIntent);
}
});
}
//exit dialog box
#Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("EHR Store");
builder.setIcon(R.drawable.sd);
builder.setMessage("Do you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}

Login Screen issues and data verification

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);
}
});

Using android generated LoginActivity with Parse.com

I am attempting to use the android built in login view and parse together.
code
public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
#Override
protected Boolean doInBackground(Void... params) {
// TODO: attempt authentication against a network service.
try {
// Simulate network access.
Thread.sleep(2000);
} catch (InterruptedException e) {
return false;
}
for (String credential : DUMMY_CREDENTIALS) {
String[] pieces = credential.split(":");
if (pieces[0].equals(mEmail)) {
// Account exists, return true if the password matches.
return pieces[1].equals(mPassword);
}
}
// TODO: register the new account here.
ParseUser newUser = new ParseUser();
newUser.setEmail(mEmail);
newUser.setPassword(mPassword);
newUser.signUpInBackground(new SignUpCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
// Success!
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
} else {
// Oops!
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
builder.setMessage(e.getMessage().toUpperCase())
.setTitle("Oops!")
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
}
});
return true;
}
When I run it, I type in my email / password and the application fails.
Have look at this code:
public class LoginActivity extends PlanndActivity
{
public EditText emailField;
public EditText passwordField;
public Button loginButton;
public View.OnClickListener loginButtonListener;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
PushService.setDefaultPushCallback(getApplicationContext(), PlanndActivity.class);
ParseInstallation.getCurrentInstallation().saveInBackground(
new SaveCallback() {
#Override
public void done(ParseException e) {
if(e!= null)
Log.e(Constants.TAG, "ERROR adding callback", e);
}
}
);
emailField = (EditText) findViewById(R.id.email_login);
passwordField = (EditText) findViewById(R.id.password_login);
loginButton = (Button) findViewById(R.id.login_button);
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loginButton.setEnabled(false);
String email = ((EditText) findViewById(R.id.email_login)).getText().toString().trim();
String password = ((EditText) findViewById(R.id.password_login)).getText().toString().trim();
ParseUser.logInInBackground(email, password, new LogInCallback() {
#Override
public void done(ParseUser parseUser, ParseException e) {
if(parseUser != null)
{
// User is valid and is now logged in
Log.i(Constants.TAG, "Successful login for user " + parseUser.getUsername());
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
PushService.subscribe(getApplicationContext(), "user_" + ParseUser.getCurrentUser().getObjectId(), PlanndActivity.class);
}
else
{
loginButton.setEnabled(true);
Log.i(Constants.TAG, "Unsuccessful login for user");
// sign up failed and the problems
// needs to go and do the sign up activity
}
}
});
}
});
((Button)findViewById(R.id.register_button)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), RegisterActivity.class));
}
});
((Button)findViewById(R.id.fake_login)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
emailField.setText("rberidon#gmail.com");
passwordField.setText("test");
}
});
}
}
Source: plannd
Try implement this with animation of view like use inline progress bar when user clicks sign in, switch the content and progress bar depending on your logic!
The problem is that your are executing signUpInBackground() inside AsyncTask.doInBackground(). doInBackground is already using a background thread. Just use newUser.signUp()

Categories

Resources