I was trying to build an OTP system in Android Studio and I came up with the code given below, however, the app is crashing every time I try to send OTP to my phone number. Here is the code:
Signp3rdClass.java
public class Signup3rdClass extends AppCompatActivity {
TextInputLayout phoneNumber;
CountryCodePicker countryCodePicker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_signup3rd_class);
//Hooks
countryCodePicker = findViewById(R.id.country_code_picker);
phoneNumber = findViewById(R.id.signup_phone_number);
}
public void callVerifyOTPScreen(View view) {
if (!validatePhoneNumber()) {
return;
}
Intent intent = new Intent(getApplicationContext(), VerifyOTP.class);
String _fullName = getIntent().getStringExtra("fullname");
String _username = getIntent().getStringExtra("username");
String _email = getIntent().getStringExtra("email");
String _password = getIntent().getStringExtra("password");
String _gender = getIntent().getStringExtra("gender");
String _date = getIntent().getStringExtra("date");
String _getUserPhoneNumber = phoneNumber.getEditText().getText().toString().trim();
String _phoneNo = "+" + countryCodePicker.getFullNumber() + _getUserPhoneNumber;
intent.putExtra("fullName", _fullName);
intent.putExtra("username", _username);
intent.putExtra("email", _email);
intent.putExtra("password", _password);
intent.putExtra("date", _date);
intent.putExtra("gender", _gender);
intent.putExtra("phoneNo", _phoneNo);
startActivity(intent);
}
private boolean validatePhoneNumber() {
String val = phoneNumber.getEditText().getText().toString().trim();
String checkNo = "[7-9][0-9]{9}";
if (val.isEmpty()) {
phoneNumber.setError("Enter valid Phone Number!");
return false;
} else if (!val.matches(checkNo)) {
phoneNumber.setError("Enter valid Phone Number!");
return false;
} else {
phoneNumber.setError(null);
phoneNumber.setErrorEnabled(false);
return true;
}
}
}
Signup3rd.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Common.LoginSingup.Signup3rdClass"
android:background="#color/offwhite">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="30dp"
android:orientation="vertical">
<ImageView
android:id="#+id/signup_back_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:src="#drawable/back_btn"
android:transitionName="transition_back_btn"/>
<TextView
android:id="#+id/create_account"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:fontFamily="sans-serif-medium"
android:text="#string/create_account"
android:textAllCaps="true"
android:textColor="#color/black"
android:textSize="40sp"
android:transitionName="transition_title_text"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginTop="40dp">
<com.hbb20.CountryCodePicker
android:id="#+id/country_code_picker"
android:layout_height="match_parent"
android:layout_width="match_parent"
app:ccp_autoDetectCountry="true"
app:ccp_showFlag="true"
app:ccp_showNameCode="true"
app:ccp_showFullName="true"
android:background="#drawable/black_border"/>
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/signup_phone_number"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:startIconDrawable="#drawable/field_phone_number_icon"
style="#style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
app:hintTextColor="#color/black"
app:endIconMode="clear_text"
app:endIconTint="#color/black"
app:boxStrokeWidthFocused="2dp"
app:boxStrokeColor="#color/black">
<com.google.android.material.textfield.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/enter_phone_no"/>
</com.google.android.material.textfield.TextInputLayout>
</LinearLayout>
<Button
android:id="#+id/signup_next_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/otp_code_btn"
android:layout_marginTop="20dp"
android:onClick="callVerifyOTPScreen"
android:elevation="5dp"
android:background="#color/colorPrimaryDark"
android:textColor="#color/white"
android:fontFamily="#font/montserrat_regular"
android:textSize="20sp"
android:transitionName="transition_next_btn"/>
<Button
android:id="#+id/signup_login_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/login"
android:layout_marginTop="20dp"
android:elevation="5dp"
android:background="#color/transparant"
android:fontFamily="#font/montserrat_regular"
android:textSize="20sp"
android:textColor="#color/black"
android:transitionName="transition_login_btn"/>
</LinearLayout>
Here is my OTP Verification Class:
VerifyOTP.java
public class VerifyOTP extends AppCompatActivity {
PinView pinFromUser;
String codeBySystem;
FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_verify_o_t_p);
pinFromUser = findViewById(R.id.pin_view);
String _phoneNumber = getIntent().getStringExtra("phoneNo");
mAuth = FirebaseAuth.getInstance();
sendVerificationCodeToUser(_phoneNumber);
}
private void sendVerificationCodeToUser(String phoneNumber) {
PhoneAuthOptions options =
PhoneAuthOptions.newBuilder(mAuth)
.setPhoneNumber(phoneNumber) // Phone number to verify
.setTimeout(60L, TimeUnit.SECONDS) // Timeout and unit
.setActivity(this) // Activity (for callback binding)
.setCallbacks(mCallbacks) // OnVerificationStateChangedCallbacks
.build();
PhoneAuthProvider.verifyPhoneNumber(options);
}
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks =
new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onCodeSent(#NonNull String s, #NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
codeBySystem = s;
}
#Override
public void onVerificationCompleted(#NonNull PhoneAuthCredential phoneAuthCredential) {
String code = phoneAuthCredential.getSmsCode();
if(code != null){
pinFromUser.setText(code);
verifyCode(code);
}
}
#Override
public void onVerificationFailed(#NonNull FirebaseException e) {
Toast.makeText(VerifyOTP.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
};
private void verifyCode(String code) {
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(codeBySystem, code);
signInWithPhoneAuthCredential(credential);
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(VerifyOTP.this, "Verification Completed!", Toast.LENGTH_SHORT).show();
} else {
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
Toast.makeText(VerifyOTP.this, "Verification failed! Please try again", Toast.LENGTH_LONG).show();
}
}
}
});
}
Logs:
E/CCP: getFullNumber: Could not parse number
I/Timeline: Timeline: Activity_launch_request time:218578976
W/ActivityThread: handleWindowVisibility: no activity for token android.os.BinderProxy#a4a9614
E/zza: Problem retrieving SafetyNet Token: 7:
I/Timeline: Timeline: Activity_launch_request time:218581077
W/ActivityThread: handleWindowVisibility: no activity for token android.os.BinderProxy#5459e2f
W/xample.desikha: Accessing hidden method Lsun/misc/Unsafe;->getInt(Ljava/lang/Object;J)I (greylist, linking, allowed)
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.desikhao, PID: 19549
java.lang.NoClassDefFoundError: Failed resolution of: Landroidx/browser/customtabs/CustomTabsIntent$Builder;
at com.google.firebase.auth.internal.RecaptchaActivity.zza(com.google.firebase:firebase-auth##20.0.0:92)
at com.google.firebase.auth.api.internal.zzeq.zza(com.google.firebase:firebase-auth##20.0.0:79)
at com.google.firebase.auth.api.internal.zzeq.onPostExecute(com.google.firebase:firebase-auth##20.0.0:88)
at android.os.AsyncTask.finish(AsyncTask.java:755)
at android.os.AsyncTask.access$900(AsyncTask.java:192)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:772)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:224)
at android.app.ActivityThread.main(ActivityThread.java:7562)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
Caused by: java.lang.ClassNotFoundException: Didn't find class "androidx.browser.customtabs.CustomTabsIntent$Builder" on path: DexPathList[[zip file "/data/app/com.example.desikhao-Z6Qez6I7lCc14bx6bjFINg==/base.apk"],nativeLibraryDirectories=[/data/app/com.example.desikhao-Z6Qez6I7lCc14bx6bjFINg==/lib/arm64, /system/lib64, /system/product/lib64]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:230)
at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
at com.google.firebase.auth.internal.RecaptchaActivity.zza(com.google.firebase:firebase-auth##20.0.0:92)
at com.google.firebase.auth.api.internal.zzeq.zza(com.google.firebase:firebase-auth##20.0.0:79)
at com.google.firebase.auth.api.internal.zzeq.onPostExecute(com.google.firebase:firebase-auth##20.0.0:88)
at android.os.AsyncTask.finish(AsyncTask.java:755)
at android.os.AsyncTask.access$900(AsyncTask.java:192)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:772)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:224)
at android.app.ActivityThread.main(ActivityThread.java:7562)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
Please let me know what am I doing wrong here.
implementation "androidx.browser:browser:1.2.0" in build.gradle (:app)
Related
It is allowing me to login through Gmail and its showing display picture, my name etc. but its not working with other random people's id.
I've added more owners on developer.google.com and its also allowing them but not me.
public class MainActivity extends AppCompatActivity implements View.OnClickListener, GoogleApiClient.OnConnectionFailedListener{
private LinearLayout Prof_Section;
private Button SignOut;
private SignInButton SignIn;
private TextView Name,Email;
private ImageView Prof_Pic;
private GoogleApiClient googleApiClient;
private static final int REQ_CODE=9001;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Prof_Section = (LinearLayout)findViewById(R.id.Prof_Section);
SignOut = (Button)findViewById(R.id.bn_logout);
SignIn = (SignInButton)findViewById(R.id.bn_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().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.bn_login:
signIn();
break;
case R.id.bn_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 handleResult(GoogleSignInResult result)
{if(result.isSuccess())
{
GoogleSignInAccount account = result.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);
// Glide.with(this)
// .load(img_url)
// // .override(300, 200)
// .into(Prof_Pic);
// Glide.with(this).load(img_url).into(Prof_pic);
updateUI(true);
}
else
{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 result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
handleResult(result);
}
}
}
<?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:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
tools:context=".MainActivity">
<LinearLayout
android:id="#+id/Prof_Section"
android:layout_width="match_parent"
android:layout_height="176dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="50dp"
android:orientation="horizontal">
<ImageView
android:id="#+id/prof_pic"
android:layout_width="113dp"
android:layout_height="match_parent"
android:src="#drawable/myalpha"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:orientation="vertical">
<TextView
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="37dp"
android:layout_marginTop="20dp"
android:gravity="center"
android:text="Name display here"
android:textSize="18dp"
android:textStyle="bold" />
<TextView
android:id="#+id/email"
android:layout_width="match_parent"
android:layout_height="35dp"
android:layout_marginTop="10dp"
android:gravity="center"
android:text="Email display here"
android:textSize="12dp"
android:textStyle="bold" />
<Button
android:id="#+id/bn_logout"
android:layout_width="match_parent"
android:layout_height="61dp"
android:text="Logout Google Account" />
</LinearLayout>
</LinearLayout>
<com.google.android.gms.common.SignInButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="60dp"
android:layout_marginRight="50dp"
android:layout_marginLeft="50dp"
android:id="#+id/bn_login"
>
</com.google.android.gms.common.SignInButton>
</LinearLayout>
Its logging me and showing me my details but not others people details.
I want that if they try to login, they also get there details
SignInButton Signin = findViewById(R.id.);
findViewById(R.id.bn_login).setOnClickListener(this);
findViewById(R.id.bn_login).setVisibility(View.GONE);
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
The app keeps crashing whenever edit Text is empty. When I enter an e-mail it works fine. I don't know what I'm doing wrong, I already tried changing height value, checked manually when it's empty but still, the issue remains. Can anyone please let me know if there's something wrong with the code.
Error:
--------- beginning of crash
09-07 10:39:53.791 15985-15985/com.app.androidnewsapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.app.androidnewsapp, PID: 15985
android.view.InflateException: Binary XML file line #17: Binary XML file line #17: Error inflating class TextView
at android.view.LayoutInflater.inflate(LayoutInflater.java:539)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
at android.widget.Editor.showError(Editor.java:430)
at android.widget.Editor.setError(Editor.java:466)
at android.widget.TextView.setError(TextView.java:4960)
at android.widget.TextView.setError(TextView.java:4945)
at com.app.androidnewsapp.activities.ActivityForgotPassword.onValidationFailed(ActivityForgotPassword.java:132)
at com.app.androidnewsapp.utils.validation.Validator$1.onPostExecute(Validator.java:195)
at com.app.androidnewsapp.utils.validation.Validator$1.onPostExecute(Validator.java:183)
at android.os.AsyncTask.finish(AsyncTask.java:651)
at android.os.AsyncTask.access$500(AsyncTask.java:180)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:168)
at android.app.ActivityThread.main(ActivityThread.java:5885)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:687)
Caused by: android.view.InflateException: Binary XML file line #17: Error inflating class TextView
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:782)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
at android.widget.Editor.showError(Editor.java:430)
at android.widget.Editor.setError(Editor.java:466)
at android.widget.TextView.setError(TextView.java:4960)
at android.widget.TextView.setError(TextView.java:4945)
at com.app.androidnewsapp.activities.ActivityForgotPassword.onValidationFailed(ActivityForgotPassword.java:132)
at com.app.androidnewsapp.utils.validation.Validator$1.onPostExecute(Validator.java:195)
at com.app.androidnewsapp.utils.validation.Validator$1.onPostExecute(Validator.java:183)
at android.os.AsyncTask.finish(AsyncTask.java:651)
at android.os.AsyncTask.access$500(AsyncTask.java:180)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:168)
at android.app.ActivityThread.main(ActivityThread.java:5885)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:687)
Caused by: java.lang.UnsupportedOperationException: Failed to resolve attribute at index 24: TypedValue{t=0x3/d=0x4a3 "res/color/secondary_text_material_light.xml" a=1 r=0x106011a}
at android.content.res.TypedArray.getColor(TypedArray.java:447)
at android.widget.TextView.<init>(TextView.java:753)
Code:
#Required(order = 1)
#Email(order = 2, message = "Please Check and Enter a valid Email Address")
EditText edtEmail;
String strEmail, strMessage;
private Validator validator;
Button btn_forgot;
ProgressBar progressBar;
LinearLayout layout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_forgot);
if (Config.ENABLE_RTL_MODE) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.BLACK);
}
edtEmail = findViewById(R.id.etUserName);
btn_forgot = findViewById(R.id.btnForgot);
progressBar = findViewById(R.id.progressBar);
layout = findViewById(R.id.view);
btn_forgot.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validator.validateAsync();
}
});
validator = new Validator(this);
validator.setValidationListener(this);
setupToolbar();
}
public void setupToolbar() {
final Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setHomeButtonEnabled(false);
getSupportActionBar().setTitle("");
}
AppBarLayout appBarLayout = findViewById(R.id.appBarLayout);
if (appBarLayout.getLayoutParams() != null) {
CoordinatorLayout.LayoutParams layoutParams = (CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams();
AppBarLayout.Behavior appBarLayoutBehaviour = new AppBarLayout.Behavior();
appBarLayoutBehaviour.setDragCallback(new AppBarLayout.Behavior.DragCallback() {
#Override
public boolean canDrag(#NonNull AppBarLayout appBarLayout) {
return false;
}
});
layoutParams.setBehavior(appBarLayoutBehaviour);
}
}
#Override
public void onValidationSucceeded() {
strEmail = edtEmail.getText().toString();
if (NetworkCheck.isNetworkAvailable(ActivityForgotPassword.this)) {
new MyTaskForgot().execute(Constant.FORGET_PASSWORD_URL + strEmail);
} else {
Toast.makeText(getApplicationContext(), getResources().getString(R.string.msg_no_network), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onValidationFailed(View failedView, Rule<?> failedRule) {
String message = failedRule.getFailureMessage();
if (failedView instanceof EditText) {
failedView.requestFocus();
((EditText) failedView).setError(message);
} else {
Toast.makeText(this, "Record Not Saved", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onBackPressed() {
//Log.d(TAG, "onBackPressed: Si entra +++++++++");
// moveTaskToBack(true);
startActivity(new Intent(getApplicationContext(), ActivityUserLogin.class));
finish();
}
private class MyTaskForgot extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.setVisibility(View.VISIBLE);
layout.setVisibility(View.INVISIBLE);
}
#Override
protected String doInBackground(String... params) {
return NetworkCheck.getJSONString(params[0]);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (null == result || result.length() == 0) {
Toast.makeText(getApplicationContext(), getResources().getString(R.string.msg_no_network), Toast.LENGTH_SHORT).show();
} else {
try {
JSONObject mainJson = new JSONObject(result);
JSONArray jsonArray = mainJson.getJSONArray(Constant.CATEGORY_ARRAY_NAME);
JSONObject objJson = null;
for (int i = 0; i < jsonArray.length(); i++) {
objJson = jsonArray.getJSONObject(i);
strMessage = objJson.getString(Constant.MSG);
Constant.GET_SUCCESS_MSG = objJson.getInt(Constant.SUCCESS);
}
} catch (JSONException e) {
e.printStackTrace();
}
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
progressBar.setVisibility(View.GONE);
setResult();
}
}, Constant.DELAY_PROGRESS_DIALOG);
}
}
}
public void setResult() {
if (Constant.GET_SUCCESS_MSG == 0) {
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle(R.string.whops);
dialog.setMessage(R.string.forgot_failed_message);
dialog.setPositiveButton(R.string.dialog_ok, null);
dialog.setCancelable(false);
dialog.show();
layout.setVisibility(View.VISIBLE);
edtEmail.setText("");
edtEmail.requestFocus();
} else {
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle(R.string.dialog_success);
dialog.setMessage(R.string.forgot_success_message);
dialog.setPositiveButton(R.string.dialog_ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = new Intent(ActivityForgotPassword.this, ActivityUserLogin.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
});
dialog.setCancelable(false);
dialog.show();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case android.R.id.home:
onBackPressed();
break;
default:
return super.onOptionsItemSelected(menuItem);
}
return true;
}
XML:
<android.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusableInTouchMode="true">
<android.support.design.widget.AppBarLayout
android:id="#+id/appBarLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true"
android:theme="#style/ThemeOverlay.AppCompat.ActionBar">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/collapsingToolbarLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true"
android:background="#color/colorBlackary"
app:contentScrim="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways|enterAlwaysCollapsed"
app:titleEnabled="false">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="5dp"
android:padding="10dp"
android:text="#string/title_forgot_password"
android:textColor="#color/colorRed"
android:textSize="15sp" />
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_collapseMode="pin"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" />
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:foreground="?android:attr/selectableItemBackground"
app:behavior_overlapTop="64dp"
app:cardCornerRadius="3dp"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
card_view:cardElevation="6sp"
card_view:cardPreventCornerOverlap="false"
card_view:cardUseCompatPadding="true">
<RelativeLayout
android:id="#+id/lyt_form"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<ImageView
android:layout_width="match_parent"
android:layout_height="470dp"
android:scaleType="fitXY"
android:src="#drawable/fondopeleadorkary" />
<LinearLayout
android:id="#+id/view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:orientation="vertical"
android:padding="20dp">
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/TextLabel">
<EditText
android:id="#+id/etUserName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:layout_marginTop="20dp"
android:drawablePadding="15dp"
android:hint="#string/edt_email"
android:textColor="#color/colorWhite"
android:inputType="textEmailAddress" />
</android.support.design.widget.TextInputLayout>
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:gravity="center"
android:textColor="#color/colorWhite"
android:text="#string/forgot_message" />
<com.balysv.materialripple.MaterialRippleLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:layout_marginTop="20dp"
app:mrl_rippleAlpha="0.2"
app:mrl_rippleColor="#color/colorRipple"
app:mrl_rippleHover="true"
app:mrl_rippleOverlay="true">
<Button
android:id="#+id/btnForgot"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="#color/colorRed"
android:text="#string/btn_send"
android:textColor="#color/colorWhite"
android:textStyle="bold" />
</com.balysv.materialripple.MaterialRippleLayout>
</LinearLayout>
<ProgressBar
android:id="#+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:visibility="gone" />
</RelativeLayout>
</android.support.v7.widget.CardView>
</android.support.design.widget.CoordinatorLayout>
Try this
#Override
public void onValidationFailed(View failedView, Rule<?> failedRule) {
String message = failedRule.getFailureMessage();
if (failedView instanceof EditText) {
failedView.requestFocus();
if(!TextUtils.isEmpty(message){
((EditText) failedView).setError(message);
}
} else {
Toast.makeText(this, "Record Not Saved", Toast.LENGTH_SHORT).show();
}
I found the problem :
android:theme="#style/TextLabel"
Had to create a theme first and than a style and use it like :
<style name="TextLabel" parent="BellicTheme">
Thanks everyone
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 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)