I am trying to create a login page. Onclick of the button, I am calling a method to verify the login credentials if already present in the backend django server. I am able to fetch the values of the username and password. The problem that I am currently facing is, if I give the login credentials already present in the backend server, the application works fine. But if I give login credentials which are not in the backend database, the application crashes. Kindly help
Code for Login.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/login_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:background="#drawable/login_background"
android:focusable="true"
android:focusableInTouchMode="true"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin" >
<TextView
android:id="#+id/appName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="50dp"
android:text="Teacher Diary"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#color/white" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="By"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#color/white" />
<ImageView
android:id="#+id/logo"
android:layout_width="100sp"
android:layout_height="100sp"
android:layout_gravity="center"
android:contentDescription="#string/home_screen_description"
android:src="#drawable/lo_logo" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="#string/app_name"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#color/white" />
<EditText
android:id="#+id/etUserName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="25dp"
android:background="#drawable/apptheme_edit_text_holo_light"
android:ems="10"
android:hint="#string/edit_text_username"
android:singleLine="true"
android:textColor="#color/blue" />
<EditText
android:id="#+id/etPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:background="#drawable/apptheme_edit_text_holo_light"
android:ems="10"
android:hint="#string/edit_text_password"
android:imeOptions="actionGo"
android:inputType="textPassword"
android:textColor="#color/blue" />
<Button
android:id="#+id/btLogin"
android:layout_width="match_parent"
android:layout_height="45dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="20dp"
android:background="#drawable/button_background"
android:text="#string/login"
android:textColor="#color/white"
android:textSize="20dp" />
<TextView
android:id="#+id/tvDisplayMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="5dp"
android:text=""
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#color/white" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="150dp"
android:text="The easiest way to conduct assessments!"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#color/white" />
</LinearLayout>
Code for login.java
public class Login extends Activity implements View.OnClickListener {
private SQLiteDatabase m_database;
private LODatabaseHelper m_databaseHelper;
private Button m_btLogin;
private Animation m_anim;
private EditText m_etUsername, m_etPassword;
private String m_username, m_password, m_role, m_schoolId;
private TextView m_displayMessage;
private String ACCESS_TOKEN = "f59Gh28E6#2h13Y";
private static RequestToServiceCallback mGetRequestToServiceCallback;
public static void setCallback(RequestToServiceCallback callback) {
mGetRequestToServiceCallback = callback;
}
public interface RequestToServiceCallback {
void statusReporting(int id);
void stopService();
}
boolean login = true;
ProgressDialog pDialog;
//List of type books this list will store type Book which is our data model
private static List<LoginModel> logindata;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// getActionBar().hide();
ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#CC25AAE2")));
int titleId = getResources().getIdentifier("action_bar_title", "id",
"android");
TextView abTitle = (TextView) findViewById(titleId);
abTitle.setTextSize(15.5f);
abTitle.setTextColor(Color.WHITE);
SharedPreferences prefs = this.getSharedPreferences("global_settings",
Context.MODE_PRIVATE);
m_username = prefs.getString("username", "");
m_role = prefs.getString("role", "");
if (m_username.contentEquals("")) {
// do Nothing and continue further the user hasn't logged in yet.
// mSync.adminSync("2");
} else {
Intent intent;
if (m_role.contentEquals("admin"))
intent = new Intent(getApplicationContext(), AdminSync.class);
else
intent = new Intent(getApplicationContext(), Home.class);
finish();
startActivity(intent);
}
setContentView(R.layout.login);
/** Initialise m_database variables */
m_databaseHelper = LODatabaseHelper.getHelper(getApplicationContext());
m_database = m_databaseHelper.getWritableDatabase();
LODatabaseUtility.getInstance().setDatabase(m_database);
m_btLogin = (Button) findViewById(R.id.btLogin);
m_btLogin.setOnClickListener(this);
m_displayMessage = (TextView) findViewById(R.id.tvDisplayMessage);
m_etUsername = (EditText) findViewById(R.id.etUserName);
m_etPassword = (EditText) findViewById(R.id.etPassword);
/* Put the last login credentials into the edit texts */
String lastUsername = prefs.getString("username_last", "");
String lastPassword = prefs.getString("password_last", "");
if (lastUsername.contentEquals("")) {
/* Do Nothing */
} else {
m_etUsername.setText(lastUsername);
m_etPassword.setText(lastPassword);
}
setAnimationValue();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
private void setAnimationValue() {
m_anim = new AlphaAnimation(0.0f, 1.0f);
m_anim.setDuration(100); // You can manage the time of the blink with
// this parameter
m_anim.setStartOffset(20);
m_anim.setRepeatMode(Animation.REVERSE);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btLogin:
/* check the username and password */
if (m_etUsername.getText().length() == 0) {
m_displayMessage.setText("Enter User Name");
if (m_etPassword.getText().length() == 0) {
m_displayMessage.setText("Enter User Name and Password");
}
return;
}
if (m_etPassword.getText().length() == 0) {
m_displayMessage.setText("Enter User Password");
return;
}
m_username = m_etUsername.getText().toString();
m_password = m_etPassword.getText().toString();
//Calling the method that will fetch data
getLoginDetails(m_username, m_password, ACCESS_TOKEN);
break;
}
}
private void getLoginDetails(final String m_username, final String m_password, final String ACCESS_TOKEN) {
//While the app fetched data we are displaying a progress dialog
final ProgressDialog loading = ProgressDialog.show(Login.this, "Please wait... ", "Login in progress", false, false);
Log.e("m_username:", m_username);
Log.e("m_password:", m_password);
App.getRestClient()
.getLoginService()
.getLoginData(m_username, m_password, ACCESS_TOKEN,
new Callback<List<LoginAPIModel>>() {
#Override
public void failure(RetrofitError arg0) {
if(arg0.getKind() == RetrofitError.Kind.CONVERSION || arg0.getKind() == RetrofitError.Kind.NETWORK){
Log.e("Exception","");
}
/*Log.e( "TAG" + "ERROR", "Logindetails table: start = "
+ "" + retrofitError.getMessage());
if (retrofitError.getKind() == RetrofitError.Kind.CONVERSION
|| retrofitError.getKind() == RetrofitError.Kind.NETWORK) {
getLoginDetails(m_username, m_password, ACCESS_TOKEN);
} else {
mGetRequestToServiceCallback.stopService();
}*/
}
#Override
public void success(List<LoginAPIModel> arg0,
Response response) {
//Dismissing the loading progressbar
loading.dismiss();
Log.e("schoolid", arg0.get(0).getSchoolId());
Log.e("username:", arg0.get(0).getUsername());
Log.e("role:", arg0.get(0).getRole());
SharedPreferences prefs = getSharedPreferences(
"global_settings",
Context.MODE_PRIVATE);
Editor editor = prefs.edit();
editor.putString("school_id",
arg0.get(0).getSchoolId());
editor.putString("username",
arg0.get(0).getUsername());
editor.putString("password",
arg0.get(0).getPassword());
editor.putString("role",
arg0.get(0).getRole());
editor.putString("email",
arg0.get(0).getEmail());
editor.putString("user",
arg0.get(0).getUser());
editor.putString("otp",
arg0.get(0).getOtp());
editor.putString("telephone_no",
arg0.get(0).getTelephoneNo());
editor.commit();
String temp1 = arg0.get(0).getRole();
Log.e("Temp1 values:", temp1);
String tempUsername=arg0.get(0).getUsername();
Log.e("username values:", tempUsername);
String tempPassword=arg0.get(0).getPassword();
Log.e("password values:", tempPassword);
Intent intent = null;
if (temp1.contentEquals("admin")) {
intent = new Intent(Login.this, AdminSync.class);
intent.putExtra("mSchoolId", m_schoolId);
finish();
startActivity(intent);
new loginUser().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}else if (temp1.contentEquals("teacher")) {
loading.dismiss();
m_displayMessage.setText("Invalid username password !");
} else {
//intent = new Intent(Login.this, Home.class);
}
//
}
});
}
My Logcat:
05-03 13:02:17.156 13719-13719/? E/m_username:: GChjvbj
05-03 13:02:17.156 13719-13719/? E/m_password:: chknmnvv
05-03 13:02:17.293 7409-7419/? E/Parcel: Reading a NULL string not supported here.
05-03 13:02:17.555 13719-13719/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.learningoutcomes, PID: 13719
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)
at com.learningoutcomes.Login$1.success(Login.java:206)
at com.learningoutcomes.Login$1.success(Login.java:184)
at retrofit.CallbackRunnable$1.run(CallbackRunnable.java:45)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5341)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:825)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:641)
at dalvik.system.NativeStart.main(Native Method)
Related
I can't solve the following problem for hours.
I try to get user-entered values from EditText so I can work with them.
public class Registrace extends AppCompatActivity implements View.OnClickListener {
private static final Pattern PASSWORD_PATTERN =
Pattern.compile("^" + "(?=.*[0-9])" +
"(?=.*[a-z])" + "(?=.*[A-Z])" + "(?=.*[##$%^&+=])" + "(?=\\s+$)" + ".{6,}" + "$");
public EditText editPrijmeni, editJmeno, editEmail, editPwd, editPwd2;
public String Mess = null;
public String jmeno, prijmeni, email, heslo, heslo2;
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_registrace);
TextView login = (TextView) findViewById(R.id.lnkLogin);
login.setMovementMethod(LinkMovementMethod.getInstance());
login.setOnClickListener(this);
editJmeno = (EditText) findViewById(R.id.txtJmeno);
jmeno = editJmeno.getText().toString().trim();
editPrijmeni = (EditText) findViewById(R.id.txtPrijmeni);
prijmeni = editPrijmeni.getEditableText().toString().trim();
editEmail = (EditText) findViewById(R.id.txtEmail);
email = editEmail.getEditableText().toString().trim();
editPwd = (EditText) findViewById(R.id.txtPassword);
heslo = editPwd.getEditableText().toString().trim();
editPwd2 = (EditText) findViewById(R.id.txtPassword2);
heslo2 = editPwd2.getEditableText().toString().trim();
btn = (Button) findViewById(R.id.btnRegistrace);
btn.setOnClickListener(this);
}
public boolean validujPrijmeni() {
if(prijmeni.isEmpty()) {
Mess = "Příjmení" + "\n";
return false;
} else {
return true;
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.lnkLogin:
Intent intent = new Intent(Registrace.this, Login.class);
startActivity(intent);
break;
case R.id.btnRegistrace:
Toast.makeText(this, "Registrace", Toast.LENGTH_SHORT).show();
if(!prijmeni.isEmpty()) {
Toast.makeText(this, prijmeni, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Zadej příjmení", Toast.LENGTH_SHORT).show();
}
break;
}
}
}
To make sure EditText values are stored correctly, I try to display them using Toast text.
But after filling in the value and pressing the button I still get the "else" block from the if statement for an empty EditText from the "switch". I'm not sure if the constructor declaration should be in the onCreate body or outside.
Could anyone help me please ???
Thank you very much.
Here is layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center">
<TextView
android:id="#+id/loginscrn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="30dp"
android:text="Registrace"
android:textSize="20dp"
android:textStyle="bold" />
<TextView
android:id="#+id/fstTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:layout_marginTop="15dp"
android:text="Příjmení" />
<EditText
android:id="#+id/txtPrijmeni"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:ems="10" />
<TextView
android:id="#+id/secTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:layout_marginTop="15dp"
android:text="Jméno"/>
<EditText
android:id="#+id/txtJmeno"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:ems="10"/>
<TextView
android:id="#+id/thirdTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Email"
android:layout_marginLeft="100dp" />
<EditText
android:id="#+id/txtEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:ems="10" />
<TextView
android:id="#+id/fourTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Heslo"
android:layout_marginLeft="100dp" />
<EditText
android:id="#+id/txtPassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:inputType="textPassword"
android:ems="10" />
<TextView
android:id="#+id/fiveTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Heslo, znova pro kontrolu"
android:layout_marginLeft="100dp" />
<EditText
android:id="#+id/txtPassword2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:inputType="textPassword"
android:ems="10" />
<Button
android:id="#+id/btnRegistrace"
android:onClick="Registrace"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:text="Registrovat" />
<TextView android:id="#+id/lnkLogin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:text="Jste již registrován?? Přihlaste se zde."
android:gravity="center"
android:textSize="20dp"
android:textColor="#3F51B5"
android:onClick="test"/>
Do this: prijmeni = editPrijmeni.getEditableText().toString().trim(); in the onClick() method.
You are doing it at the creation of the Activity so the EditText control is empty. It won't automatically update the prijmeni string on change.
Here is how your code could look like with some small improvements.
It could also be further refined but it seems you just begin so it's already fine.
public class Registrace extends AppCompatActivity implements View.OnClickListener {
private static final Pattern PASSWORD_PATTERN =
Pattern.compile("^" + "(?=.*[0-9])" +
"(?=.*[a-z])" + "(?=.*[A-Z])" + "(?=.*[##$%^&+=])" + "(?=\\s+$)" + ".{6,}" + "$");
private EditText editPrijmeni;
private EditText editJmeno;
private EditText editEmail;
private EditText editPwd;
private EditText editPwd2;
private Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_registrace);
// Shouldn't you use a button instead of a text view?
// It seems you want a "Login" button to go to a LoginActivity
final TextView login = (TextView) findViewById(R.id.lnkLogin);
login.setMovementMethod(LinkMovementMethod.getInstance());
login.setOnClickListener(this);
// You could use https://jakewharton.github.io/butterknife which simplifies this boilerplate code a lot
editJmeno = (EditText) findViewById(R.id.txtJmeno);
editPrijmeni = (EditText) findViewById(R.id.txtPrijmeni);
editEmail = (EditText) findViewById(R.id.txtEmail);
editPwd = (EditText) findViewById(R.id.txtPassword);
editPwd2 = (EditText) findViewById(R.id.txtPassword2);
btn = (Button) findViewById(R.id.btnRegistrace);
btn.setOnClickListener(this);
}
public boolean validujPrijmeni() {
// if 'Mess' was for a validation message don't set it in the validation method.
// define a string in your resources.
// show/hide a TextView with that message from where you use the validation method.
final String prijmeni = editPrijmeni.getEditableText().toString().trim();
return !prijmeni.isEmpty();
}
// I would not declare the activity as a OnClickListener but use anonymous classes in the onCreate method
// calling method on this class.
// or if you use ButterKnife you can do so with OnClick annotations.
// This is to prevent the use of switch which is not great code.
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.lnkLogin:
Intent intent = new Intent(Registrace.this, Login.class);
startActivity(intent);
break;
case R.id.btnRegistrace:
Toast.makeText(this, "Registrace", Toast.LENGTH_SHORT).show();
final String prijmeni = editPrijmeni.getEditableText().toString().trim();
if (this.validujPrijmeni()) {
Toast.makeText(this, prijmeni, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Zadej příjmení", Toast.LENGTH_SHORT).show();
}
break;
}
}
}
you are getting values from edittext in on create.it's actually wrong cause in that time those edittexts are empty.the correct action is to get text from edittext in on click of register button
before
case R.id.btnRegistrace:
Toast.makeText(this, "Registrace", Toast.LENGTH_SHORT).show();
if(!prijmeni.isEmpty()) {
Toast.makeText(this, prijmeni, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Zadej příjmení", Toast.LENGTH_SHORT).show();
}
break;
after
case R.id.btnRegistrace:
Toast.makeText(this, "Registrace", Toast.LENGTH_SHORT).show();
if(!editJmeno.getText().toString().isEmpty()) {
Toast.makeText(this, editJmeno.getText().toString(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Zadej příjmení", Toast.LENGTH_SHORT).show();
}
break;
I am new to Android Programming. I successfully integrated the Google sign-in and successful in Passing data to another Activity. But When I am going back to the activity through the navigation drawer where I passed the data it sowing empty screen. I Want to Save user Profile in that Activity. I want to save user details by clicking the save button permanently in the app to show as a user profile. Please help me in solving this Problem. Thanks, in Advance for the Solution.
Here are my java files and XML files.
activity_main3.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main3"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".Main3Activity">
<LinearLayout
android:id="#+id/prof_section"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="50dp"
android:orientation="horizontal">
<ImageView
android:id="#+id/prof_pic"
android:layout_width="90dp"
android:layout_height="125dp"
android:src="#drawable/profilep" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="28dp"
android:layout_marginTop="20dp"
android:orientation="vertical">
<TextView
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Disply Name Here"
android:textSize="18dp"
android:textStyle="bold" />
<TextView
android:id="#+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:gravity="center"
android:text="Disply Email Here"
android:textSize="18dp"
android:textStyle="bold" />
<Button
android:id="#+id/butn_logout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Logout"
/>
</LinearLayout>
</LinearLayout>
<com.google.android.gms.common.SignInButton
android:id="#+id/butn_login"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
android:layout_marginTop="60dp" >
</com.google.android.gms.common.SignInButton>
activity_detail.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".Detail">
<ImageView
android:id="#+id/dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp" />
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp" />
<TextView
android:id="#+id/email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp" />
<Button
android:id="#+id/button_save"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="SAVE" />
Detail.Java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
dp = (ImageView) findViewById(R.id.dp);
name = (TextView) findViewById(R.id.name);
email = (TextView) findViewById(R.id.email);
Intent i = getIntent();
final String i_name, i_email, i_url;
i_name = i.getStringExtra("p_name");
i_email = i.getStringExtra("p_email");
i_url = i.getStringExtra("p_url");
name.setText(i_name);
email.setText(i_email);
new Thread(new Runnable() {
#Override
public void run() {
try {
URL url = new URL(i_url);
InputStream is = url.openConnection().getInputStream();
final Bitmap bmp = BitmapFactory.decodeStream(is);
runOnUiThread(new Runnable() {
#Override
public void run() {
dp.setImageBitmap(bmp);
}
});
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
Main3Activity.Java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
preferenceConfig = new SharedPreferenceConfig(getApplicationContext());
if (preferenceConfig.readLoginStatus()) {
startActivity(new Intent(this, Main2Activity.class));
finish();
}
Prof_Section = (LinearLayout) findViewById(R.id.prof_section);
SignOut = (Button) findViewById(R.id.butn_logout);
SignIn = (SignInButton) findViewById(R.id.butn_login);
Name = (TextView) findViewById(R.id.name);
Email = (TextView) findViewById(R.id.email);
Prof_Pic = (ImageView) findViewById(R.id.prof_pic);
SignIn.setOnClickListener(this);
SignOut.setOnClickListener(this);
Prof_Section.setVisibility(View.GONE);
GoogleSignInOptions signInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail().requestProfile().build();
googleApiClient = new GoogleApiClient.Builder(this).enableAutoManage(this, this).addApi(Auth.GOOGLE_SIGN_IN_API, signInOptions).build();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.butn_login:
signIn();
break;
case R.id.butn_logout:
signOut();
break;
}
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
private void signIn() {
Intent intent = Auth.GoogleSignInApi.getSignInIntent(googleApiClient);
startActivityForResult(intent, REQ_CODE);
}
private void signOut() {
Auth.GoogleSignInApi.signOut(googleApiClient).setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(#NonNull Status status) {
updateUI(false);
}
});
}
private void updateUI(boolean isLogin) {
if (isLogin) {
Prof_Section.setVisibility(View.VISIBLE);
SignIn.setVisibility(View.GONE);
} else {
Prof_Section.setVisibility(View.GONE);
SignIn.setVisibility(View.VISIBLE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQ_CODE) {
GoogleSignInResult googleSignInResult = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
GoogleSignInAccount account = googleSignInResult.getSignInAccount();
String name = account.getDisplayName();
String email = account.getEmail();
String img_url = account.getPhotoUrl().toString();
Name.setText(name);
Email.setText(email);
Glide.with(this).load(img_url).into(Prof_Pic);
updateUI(true);
preferenceConfig.writeLoginStatus(true);
try {
Intent sendData = new Intent(Main3Activity.this, Detail.class);
name = account.getDisplayName();
email = account.getEmail();
img_url = account.getPhotoUrl().toString();
sendData.putExtra("p_name", name);
sendData.putExtra("p_email", email);
sendData.putExtra("p_url", img_url);
startActivity(sendData);
} catch (Exception e) {
Toast.makeText(Main3Activity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(Main3Activity.this, "Login Failed", Toast.LENGTH_SHORT).show();
}
}
Use shared preferences for your purpose. You can read more about it here.
An example is provided here sharedPreferences
I developing app with ccavenue payment gateway Integration. I searched in google, I download code. but it works fine in eclipse, then comes in studio it crashes. I tried. but I didn't get output. please any one help me.
public class WebViewActivity extends Activity {
private ProgressDialog dialog;
Intent mainIntent;
String html, encVal;
public static final String TAG = "WebViewStatus : ";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_webview);
mainIntent = getIntent();
Log.d(TAG,"main 1 ");
new RenderView().execute();
}
private class RenderView extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(WebViewActivity.this);
dialog.setMessage("Please wait...");
dialog.setCancelable(false);
dialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler sh = new ServiceHandler();
Log.d(TAG,"main 3 ");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add((NameValuePair) new BasicNameValuePair(AvenuesParams.ACCESS_CODE, mainIntent.getStringExtra(AvenuesParams.ACCESS_CODE)));
params.add((NameValuePair) new BasicNameValuePair(AvenuesParams.ORDER_ID, mainIntent.getStringExtra(AvenuesParams.ORDER_ID)));
String vResponse = sh.makeServiceCall(mainIntent.getStringExtra(AvenuesParams.RSA_KEY_URL), ServiceHandler.POST,params);//, params
System.out.println(vResponse);
if(!ServiceUtility.chkNull(vResponse).equals("")
&& ServiceUtility.chkNull(vResponse).toString().indexOf("ERROR")==-1){
StringBuffer vEncVal = new StringBuffer("");
vEncVal.append(ServiceUtility.addToPostParams(AvenuesParams.AMOUNT, mainIntent.getStringExtra(AvenuesParams.AMOUNT)));
vEncVal.append(ServiceUtility.addToPostParams(AvenuesParams.CURRENCY, mainIntent.getStringExtra(AvenuesParams.CURRENCY)));
encVal = RSAUtility.encrypt(vEncVal.substring(0,vEncVal.length()-1), vResponse);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (dialog.isShowing())
dialog.dismiss();
Log.d(TAG,"main 4 ");
#SuppressWarnings("unused")
class MyJavaScriptInterface
{
#JavascriptInterface
public void processHTML(String html)
{
// process the html as needed by the app
String status = null;
if(html.indexOf("Failure")!=-1){
status = "Transaction Declined!";
}else if(html.indexOf("Success")!=-1){
status = "Transaction Successful!";
}else if(html.indexOf("Aborted")!=-1){
status = "Transaction Cancelled!";
}else{
status = "Status Not Known!";
}
Intent intent = new Intent(getApplicationContext(),StatusActivity.class);
intent.putExtra("transStatus", status);
startActivity(intent);
}
}
final WebView webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
webview.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");
webview.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(webview, url);
if(url.indexOf("/ccavResponseHandler.jsp")!=-1){
webview.loadUrl("javascript:window.HTMLOUT.processHTML('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
}
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(getApplicationContext(), "Oh no! " + description, Toast.LENGTH_SHORT).show();
}
});
StringBuffer params = new StringBuffer();
params.append(ServiceUtility.addToPostParams(AvenuesParams.ACCESS_CODE,mainIntent.getStringExtra(AvenuesParams.ACCESS_CODE)));
params.append(ServiceUtility.addToPostParams(AvenuesParams.MERCHANT_ID,mainIntent.getStringExtra(AvenuesParams.MERCHANT_ID)));
params.append(ServiceUtility.addToPostParams(AvenuesParams.ORDER_ID,mainIntent.getStringExtra(AvenuesParams.ORDER_ID)));
params.append(ServiceUtility.addToPostParams(AvenuesParams.REDIRECT_URL,mainIntent.getStringExtra(AvenuesParams.REDIRECT_URL)));
params.append(ServiceUtility.addToPostParams(AvenuesParams.CANCEL_URL,mainIntent.getStringExtra(AvenuesParams.CANCEL_URL)));
params.append(ServiceUtility.addToPostParams(AvenuesParams.ENC_VAL,URLEncoder.encode(encVal)));
String vPostParams = params.substring(0,params.length()-1);
try {
webview.postUrl(Constants.TRANS_URL, EncodingUtils.getBytes(vPostParams, "UTF-8"));
} catch (Exception e) {
showToast("Exception occured while opening webview.");
}
}
}
public void showToast(String msg) {
Toast.makeText(this, "Toast: " + msg, Toast.LENGTH_LONG).show();
}
}
The Error is :
--------- beginning of crash
11-16 11:19:56.256 21909-21909/com.reports.com.ccavenueseamless
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.reports.com.ccavenueseamless, PID: 21909
java.lang.IllegalStateException: Could not find method Next(View)
in a parent or ancestor Context for android:onClick attribute defined on
view class android.support.v7.widget.AppCompatButton with id 'nextButton'
at android.support.v7.app.AppCompatViewInflater
$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:325)
at android.support.v7.app.AppCompatViewInflater
$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:284)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit
$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main
(ZygoteInit.java:698)
The MainActivity is----
public class MainActivity extends AppCompatActivity {
private EditText accessCode, merchantId, currency, amount, orderId, rsaKeyUrl, redirectUrl, cancelUrl;
private Button webview;
private void init() {
accessCode = (EditText) findViewById(R.id.accessCode);
merchantId = (EditText) findViewById(R.id.merchantId);
orderId = (EditText) findViewById(R.id.orderId);
currency = (EditText) findViewById(R.id.currency);
amount = (EditText) findViewById(R.id.amount);
rsaKeyUrl = (EditText) findViewById(R.id.rsaUrl);
redirectUrl = (EditText) findViewById(R.id.redirectUrl);
cancelUrl = (EditText) findViewById(R.id.cancelUrl);
webview = (Button) findViewById(R.id.nextButton);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
setContentView(R.layout.activity_main);
init();
webview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Next();
}
});
//generating order number
Integer randomNum = ServiceUtility.randInt(0, 9999999);
orderId.setText(randomNum.toString());
}
public void Next() {
//Mandatory parameters. Other parameters can be added if required.
String vAccessCode = ServiceUtility.chkNull(accessCode.getText()).toString().trim();
String vMerchantId = ServiceUtility.chkNull(merchantId.getText()).toString().trim();
String vCurrency = ServiceUtility.chkNull(currency.getText()).toString().trim();
String vAmount = ServiceUtility.chkNull(amount.getText()).toString().trim();
if(!vAccessCode.equals("") && !vMerchantId.equals("") && !vCurrency.equals("") && !vAmount.equals("")){
Intent intent = new Intent(this,WebViewActivity.class);intent.putExtra(AvenuesParams.ACCESS_CODE, ServiceUtility.chkNull(accessCode.getText()).toString().trim());
intent.putExtra(AvenuesParams.MERCHANT_ID, ServiceUtility.chkNull(merchantId.getText()).toString().trim());
intent.putExtra(AvenuesParams.ORDER_ID, ServiceUtility.chkNull(orderId.getText()).toString().trim());
intent.putExtra(AvenuesParams.CURRENCY, ServiceUtility.chkNull(currency.getText()).toString().trim());
intent.putExtra(AvenuesParams.AMOUNT, ServiceUtility.chkNull(amount.getText()).toString().trim());
intent.putExtra(AvenuesParams.REDIRECT_URL, ServiceUtility.chkNull(redirectUrl.getText()).toString().trim());
intent.putExtra(AvenuesParams.CANCEL_URL, ServiceUtility.chkNull(cancelUrl.getText()).toString().trim());
intent.putExtra(AvenuesParams.RSA_KEY_URL, ServiceUtility.chkNull(rsaKeyUrl.getText()).toString().trim());
startActivity(intent);
}else{
showToast("All parameters are mandatory.");//09438576355
}
}
public void showToast(String msg) {
Toast.makeText(this, "Toast: " + msg, Toast.LENGTH_LONG).show();
}
}
the activity_main.xml is---
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="left"
android:orientation="vertical" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:paddingLeft="10dp"
android:text="#string/access_code" />
<EditText
android:id="#+id/accessCode"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:text="AVPE07CL82AO87EPOA" >
</EditText>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:paddingLeft="10dp"
android:text="#string/merchant_id" />
<EditText
android:id="#+id/merchantId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:text="84472"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:paddingLeft="10dp"
android:text="Order Id" />
<EditText
android:id="#+id/orderId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:paddingLeft="10dp"
android:text="#string/currency" />
<EditText
android:id="#+id/currency"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:text="INR"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:paddingLeft="10dp"
android:text="#string/amount" />
<EditText
android:id="#+id/amount"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:text="1.00"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:paddingLeft="10dp"
android:text="#string/redirect_url" />
<EditText
android:id="#+id/redirectUrl"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textUri"
android:text="http://122.182.6.216/merchant/ccavResponseHandler.jsp"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:paddingLeft="10dp"
android:text="#string/cancel_url" />
<EditText
android:id="#+id/cancelUrl"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textUri"
android:text="http://122.182.6.216/merchant/ccavResponseHandler.jsp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:paddingLeft="10dp"
android:text="#string/rsa_url" />
<EditText
android:id="#+id/rsaUrl"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textUri"
android:text="http://122.182.6.216/merchant/GetRSA.jsp" />
<Button
android:id="#+id/nextButton"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="48dp"
android:text="#string/pay_button" />
</LinearLayout>
</ScrollView>
i don't know why after login, into main activity username and password doesn't appear.....i see only logout button...why?
I hope that you can help me!
LOGIN ACTIVITY:
public class LoginActivity extends Activity {
private static final String TAG = RegisterActivity.class.getSimpleName();
private Button btnLogin;
private Button btnLinkToRegister;
private EditText inputNumeroTelefonico;
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);
inputNumeroTelefonico = (EditText) findViewById(R.id.numero_telefonico);
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 numero_telefonico = inputNumeroTelefonico.getText().toString().trim();
String password = inputPassword.getText().toString().trim();
// Check for empty data in the form
if (!numero_telefonico.isEmpty() && !password.isEmpty()) {
// login user
checkLogin(numero_telefonico, 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 numero_telefonico, 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 cognome = user.getString("cognome");
String numero_telefonico = user.getString("numero_telefonico");
String created_at = user
.getString("created_at");
// Inserting row in users table
db.addUser(name,cognome, numero_telefonico, 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("numero_telefonico", numero_telefonico);
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();
}
}
MAIN ACTIVITY:
public class MainActivity extends Activity {
private TextView txtName;
private TextView txtNumeroTelefonico;
private Button btnLogout;
private SQLiteHandler db;
private SessionManager session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtName = (TextView) findViewById(R.id.name);
txtNumeroTelefonico = (TextView) findViewById(R.id.numero_telefonico);
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 numero_telefonico = user.get("numero_telefonico");
// Displaying the user details on the screen
System.out.println(name+""+numero_telefonico);
txtName.setText(name);
txtNumeroTelefonico.setText(numero_telefonico);
// 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();
}
}
LOGIN ACTIVITY.XML:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white"
android:gravity="center"
android:orientation="vertical"
android:padding="10dp"
android:fitsSystemWindows="true">
<LinearLayout
android:layout_gravity="center_vertical"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="100dp"
android:paddingTop="56dp"
android:paddingLeft="24dp"
android:paddingRight="24dp" >
<ImageView
android:background="#drawable/signor_pomidor"
android:layout_gravity="center_horizontal"
android:layout_width="150dp"
android:layout_height="150dp" />
<EditText
android:id="#+id/numero_telefonico"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:background="#color/btn_login_bg"
android:hint="#string/hint_numero_telefonico"
android:inputType="textEmailAddress"
android:padding="10dp"
android:singleLine="true"
android:textColor="#color/input_login"
android:textColorHint="#color/input_login_hint" />
<EditText
android:id="#+id/password"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:background="#color/btn_login_bg"
android:hint="#string/hint_password"
android:inputType="textPassword"
android:padding="10dp"
android:singleLine="true"
android:textColor="#color/input_login"
android:textColorHint="#color/input_login_hint" />
<!-- Login Button -->
<Button
android:id="#+id/btnLogin"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dip"
android:background="#color/btn_login_bg"
android:text="#string/btn_login"
android:textColor="#color/btn_logut_bg" />
<!-- Link to Login Screen -->
<Button
android:id="#+id/btnLinkToRegisterScreen"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:background="#null"
android:text="#string/btn_link_to_register"
android:textAllCaps="false"
android:textColor="#color/btn_logut_bg"
android:textSize="15dp" />
</LinearLayout>
</ScrollView>
MAIN ACTIVITY.XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/welcome"
android:textSize="20dp" />
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:textColor="#color/lbl_name"
android:textSize="24dp" />
<TextView
android:id="#+id/numero_telefonico"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="13dp" />
<Button
android:id="#+id/btnLogout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dip"
android:background="#color/btn_logut_bg"
android:text="#string/btn_logout"
android:textAllCaps="false"
android:textColor="#color/white"
android:textSize="15dp" />
</LinearLayout>
</RelativeLayout>
GET USER DETAIL:
if (isset($_POST['numero_telefonico']) && isset($_POST['password'])) {
// receiving the post params
$numero_telefonico = $_POST['numero_telefonico'];
$password = $_POST['password'];
// get the user by email and password
$user = $db->getUserByEmailAndPassword($numero_telefonico, $password);
if ($user != false) {
// use is found
$response["error"] = FALSE;
$response["uid"] = $user["unique_id"];
$response["user"]["name"] = $user["name"];
$response["user"]["cognome"] = $user["cognome"];
$response["user"]["numero_telefonico"] = $user["numero_telefonico"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
echo json_encode($response);
}
public function getUserByEmailAndPassword($numero_telefonico, $password) {
$stmt = $this->conn->prepare("SELECT * FROM users WHERE numero_telefonico = ?");
$stmt->bind_param("s", $numero_telefonico);
if ($stmt->execute()) {
$user = $stmt->get_result()->fetch_assoc();
$stmt->close();
// verifying user password
$salt = $user['salt'];
$encrypted_password = $user['encrypted_password'];
//$hash = $this->checkhashSSHA($salt, $password);
$hash = $password;
// check for password equality
if ($encrypted_password == $hash) {
// user authentication details are correct
return $user;
}
} else {
return NULL;
}
}
enter image description here
Issue in your MAIN ACTIVITY.XML
Just follow the below codes. I have changed the weight & some of the colors ,but u can change it as per ur requirement. In main Relative Layout i have taken the background as white.
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:gravity="center"
android:orientation="vertical"
android:weightSum="4">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/welcome"
android:textSize="20dp"
android:textColor="#color/black"
android:layout_weight="1"/>
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#color/black"
android:textSize="24dp"
android:text="#string/welcome" />
<TextView
android:id="#+id/numero_telefonico"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="13dp"
android:layout_weight="1"
android:textColor="#color/black"
android:text="#string/welcome"/>
<Button
android:id="#+id/btnLogout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dip"
android:background="#color/btn_logut_bg"
android:text="#string/btn_logout"
android:textAllCaps="false"
android:textColor="#color/black"
android:textSize="15dp"
android:layout_weight="1" />
</LinearLayout>
Hope this will help u.
I did the login attempt but the problem is I want to have duration to log. I mean, if the attempt is gone, I want to put an extra information saying "Your attempt reach 0, please wait 3 minutes to log again" or something like that.
Login Form XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" tools:context=".Mobile_Grocery"
android:id="#+id/mobile_grocery"
>
<ImageView
android:id="#+id/mobile_grocery_bckgrnd"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/mobile_grocery"
android:scaleType="centerCrop"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/mobile_grocery_main"
android:id="#+id/mobilegrocery"
android:layout_marginTop="40dp"
android:textSize="50dp"
android:textColor="#000000"
android:textStyle="bold|italic"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<EditText
android:layout_width="200dp"
android:layout_height="wrap_content"
android:id="#+id/Email"
android:hint="#string/email_text"
android:textColorHint="#000000"
android:layout_above="#+id/Password"
android:layout_alignLeft="#+id/Password"
android:layout_alignStart="#+id/Password" />
<EditText
android:layout_width="200dp"
android:layout_height="wrap_content"
android:id="#+id/Password"
android:hint="#string/password_text"
android:textColorHint="#000000"
android:layout_marginBottom="119dp"
android:layout_alignParentBottom="true"
android:layout_alignLeft="#+id/mobilegrocery"
android:layout_alignStart="#+id/mobilegrocery"
android:layout_marginLeft="37dp"
android:layout_marginStart="37dp"
android:password="true" />
<ImageButton
android:layout_width="100dp"
android:layout_height="45dp"
android:id="#+id/Login"
android:layout_marginTop="43dp"
android:layout_below="#+id/Email"
android:layout_alignLeft="#+id/Password"
android:layout_alignStart="#+id/Password"
android:src="#drawable/login_button"
android:scaleType="centerCrop"
android:layout_marginLeft="48dp"
android:layout_marginStart="48dp"
android:onClick="ocLogin"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/attempt_text"
android:id="#+id/attleft"
android:textSize="20dp"
android:textColor="#000000"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<ImageButton
android:layout_width="100dp"
android:layout_height="45dp"
android:id="#+id/register"
android:src="#drawable/register"
android:scaleType="centerCrop"
android:layout_below="#+id/Login"
android:layout_alignLeft="#+id/Login"
android:layout_alignStart="#+id/Login" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/number"
android:textColor="#000000"
android:textSize="20dp"
android:layout_alignParentBottom="true"
android:layout_alignLeft="#+id/register"
android:layout_alignStart="#+id/register"
android:password="false" />
Login Java
public class Mobile_Grocery extends ActionBarActivity {
private static EditText email;
private static EditText password;
private static TextView attempts;
private static ImageButton login_btn;
int attempt_counter = 3 ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mobile__grocery);
ocLogin();
}
public void ocLogin () {
email = (EditText) findViewById(R.id.Email);
password = (EditText) findViewById(R.id.Password);
attempts = (TextView) findViewById(R.id.number);
login_btn = (ImageButton) findViewById(R.id.Login);
attempts.setText(Integer.toString(attempt_counter));
login_btn.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
if (email.getText().toString().equals("admin") &&
password.getText().toString().equals("pass")) {
Toast.makeText(Mobile_Grocery.this, "Email and Password is correct",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent("com.example.admin.mobile_grocery.Method");
startActivity(intent);
} else {
Toast.makeText(Mobile_Grocery.this, "Email and Password is incorrect",
Toast.LENGTH_SHORT).show();
attempt_counter--;
attempts.setText(Integer.toString(attempt_counter));
if (attempt_counter == 0) {
login_btn.setEnabled(false);
}
}
}
}
);
}
How can I do that?
You can do something like this,
First define
private static final int WAIT_TIME = 3 * 60 * 1000;
private int loginAttempts = 3;
In your login button click listener,
login_btn.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
if(loginAttempts == 0) {
Toast.makeText(Mobile_Grocery.this, "Your attempt reach 0, please wait 3 minutes to log again", Toast.LENGTH_SHORT).show();
return;
}
if (email.getText().toString().equals("admin") &&
password.getText().toString().equals("pass")) {
Toast.makeText(Mobile_Grocery.this, "Email and Password is correct",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent("com.example.admin.mobile_grocery.Method");
startActivity(intent);
} else {
loginAttempts--;
Toast.makeText(Mobile_Grocery.this, "Email and Password is incorrect",
Toast.LENGTH_SHORT).show();
if(loginAttempts == 2) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
loginAttempts = 3;
}
}, WAIT_TIME);
}
}
}
}
);
I recommend as following.
login(){
//show your loading text visible
new Thread(new Runnable() {
#Override
public void run() {
boolean loginTrue = //request your web login method
//You don'y need handler to pause thread. Http request will pause until response from server
runOnUiThread(new Runnable() {
#Override
public void run() {
//set invisible your laoding text
if(loginTrue){
Toast.makeText(Mobile_Grocery.this, "Email and Password is correct",
Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(Mobile_Grocery.this, "Email and Password is incorrect",
Toast.LENGTH_SHORT).show();
}
}
});
}
}).start();
}