Android crashing on empty EText - java

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

Related

App crashing while verifying OTP in Android Studio with firebase

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)

How to Save google profile after google signin in another activity

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

Attempt to invoke virtual method `MaterialEditText.getText()' on a null object reference

public class MainActivity extends AppCompatActivity {
MaterialEditText edtNewUser, edtNewPassword, edtNewEmail; //pentru Sign up
MaterialEditText edtUser, edtPassword, edtEmail; //pentru Sign in
Button btnSignUp, btnSignIn;
FirebaseDatabase database;
DatabaseReference users;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Firebase
database = FirebaseDatabase.getInstance();
users = database.getReference("Users");
edtUser = (MaterialEditText)findViewById(R.id.edtUser);
edtPassword = (MaterialEditText)findViewById(R.id.edtPassword);
btnSignIn = (Button)findViewById(R.id.btn_sign_in);
btnSignUp = (Button)findViewById(R.id.btn_sign_up);
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showSignUpDialog();
}
});
btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signIn(edtUser.getText().toString(), edtPassword.getText().toString());
}
});
}
private void signIn(final String user, final String pwd) {
users.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.child(user).exists()){
if(!user.isEmpty()){
User login = dataSnapshot.child(user).getValue(User.class);
if(login.getPassword().equals(pwd))
Toast.makeText(MainActivity.this, "Login ok!", Toast.LENGTH_SHORT).show();
else
Toast.makeText(MainActivity.this, "Parola incorecta!", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(MainActivity.this, "Va rog introduceti username!", Toast.LENGTH_SHORT).show();
}
}
else
Toast.makeText(MainActivity.this, "Username-ul nu exista!", Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void showSignUpDialog() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
alertDialog.setTitle("Sign up");
alertDialog.setMessage("Introduceti informatiile necesare");
LayoutInflater inflater = this.getLayoutInflater();
View sign_up_layout = inflater.inflate(R.layout.sign_up_layout,null);
edtNewUser = (MaterialEditText)sign_up_layout.findViewById(R.id.edtNewUserName);
edtNewEmail = (MaterialEditText)sign_up_layout.findViewById(R.id.edtNewEmail);
edtNewPassword = (MaterialEditText)sign_up_layout.findViewById(R.id.edtNewPassword);
alertDialog.setView(sign_up_layout);
alertDialog.setIcon(R.drawable.ic_account_circle_black_24dp);
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
final User user = new User(edtNewUser.getText().toString(),
edtNewPassword.getText().toString(),
edtNewEmail.getText().toString());
users.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.child(user.getUserName()).exists())
Toast.makeText(MainActivity.this, "User-ul exista deja!",Toast.LENGTH_SHORT).show();
else{
users.child(user.getUserName()).setValue(user);
Toast.makeText(MainActivity.this, "Inregistrat cu success!",Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
dialogInterface.dismiss();
}
});
alertDialog.show();
}
}
XML file
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout 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"
android:background="#color/colorPrimary"
tools:context=".MainActivity">
<RelativeLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" >
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/info_login"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
app:cardElevation="4dp"
>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.rengwuxian.materialedittext.MaterialEditText
android:id="#+id/edtNewUserName"
android:hint="Username"
android:textColorHint="#color/colorPrimary"
android:textColor="#color/colorPrimary"
android:textSize="24sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:met_baseColor="#color/colorPrimary"
app:met_floatingLabel="highlight"
app:met_primaryColor="#color/colorPrimary"
app:met_singleLineEllipsis="true"
/>
<com.rengwuxian.materialedittext.MaterialEditText
android:id="#+id/edtNewPassword"
android:hint="Password"
android:textColorHint="#color/colorPrimary"
android:textColor="#color/colorPrimary"
android:textSize="24sp"
android:inputType="textPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:met_baseColor="#color/colorPrimary"
app:met_floatingLabel="highlight"
app:met_primaryColor="#color/colorPrimary"
app:met_singleLineEllipsis="true"
/>
</LinearLayout>
</android.support.v7.widget.CardView>
<LinearLayout
android:layout_below="#id/info_login"
android:orientation="horizontal"
android:weightSum="2"
android:layout_margin="8dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="#id/btn_sign_up"
android:text="Sign up"
style="#style/Widget.AppCompat.Button.Colored"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content" />
<Button
android:id="#id/btn_sign_in"
android:text="Sign in"
style="#style/Widget.AppCompat.Button.Colored"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content" />
</LinearLayout>
</RelativeLayout>
</android.support.constraint.ConstraintLayout>
Please help me! I've tried anything I knew but nothing works
The program I work in is ANDROID STUDIO. I need to solve this to finish my app.
signIn(edtUser.getText().toString(), edtPassword.getText().toString());
This is the line that gives me ERROR. If I comment this line the app works properly but I need it for the rest of the app.
Your edtUser MaterialEditText and edtPassword are not present in your xml file, you have to change the ids in xml file to match the Activity ids, or remplace
edtUser = (MaterialEditText)findViewById(R.id.edtUser);
edtPassword = (MaterialEditText)findViewById(R.id.edtPassword);
by :
edtUser = (MaterialEditText)findViewById(R.id.edtNewUserName);
edtPassword = (MaterialEditText)findViewById(R.id.edtNewPassword);

How to add button in Zxing Scanner Camera View?

I want to add a button in Zxing Scanner Camera View, tried many procedures and seen many answers related to add button in Zxing library and refered this " How to add buttons in Zxing Scanner Camera View " , but it's not working anyone guide me, Thanks in advance, My code is
MainActivity.Java
public class MainActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler {
private static final int REQUEST_CAMERA = 1;
final static String serverUrl = "";
private ZXingScannerView scannerView;
String res;
ImageButton img;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
Log.e("OnCreate", "OnCreated");
//ZXingScannerView zxing=(ZXingScannerView)findViewById(R.id.zxscan);
scannerView = (ZXingScannerView) findViewById(R.id.zxscan);
img=(ImageButton)findViewById(R.id.img1);
//scannerView.setResultHandler(this);
//scannerView.startCamera();
//zxing.addView(scannerView);
//setContentView(scannerView);
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion >= android.os.Build.VERSION_CODES.M) {
if (checkPermission()) {
Log.e("M", "Permission");
Toast.makeText(getApplicationContext(), "Permission already granted", Toast.LENGTH_LONG).show();
} else {
Log.e("R", "Permission");
requestPermission();
}
}
}
private boolean checkPermission() {
return (ContextCompat.checkSelfPermission(getApplicationContext(), CAMERA) == PackageManager.PERMISSION_GRANTED);
}
private void requestPermission() {
ActivityCompat.requestPermissions(this, new String[]{CAMERA}, REQUEST_CAMERA);
}
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case REQUEST_CAMERA:
if (grantResults.length > 0) {
Log.e("Successfull", "Success");
boolean cameraAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
if (cameraAccepted) {
Log.e("accpt", "Accpt");
Toast.makeText(getApplicationContext(), "Permission Granted, Now you can access camera", Toast.LENGTH_LONG).show();
} else {
Log.e("ntaccpt", "Not Acpt");
Toast.makeText(getApplicationContext(), "Permission Denied, You cannot access and camera", Toast.LENGTH_LONG).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(CAMERA)) {
showMessageOKCancel("You need to allow access to both the permissions",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{CAMERA},
REQUEST_CAMERA);
}
}
});
return;
}
}
}
}
break;
}
}
private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
new android.support.v7.app.AlertDialog.Builder(MainActivity.this)
.setMessage(message)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", null)
.create()
.show();
}
#Override
public void onResume() {
super.onResume();
int capi = android.os.Build.VERSION.SDK_INT;
if (capi >= android.os.Build.VERSION_CODES.M) {
if (checkPermission()) {
if (scannerView == null) {
scannerView = new ZXingScannerView(this);
setContentView(scannerView);
}
scannerView.setResultHandler(this);
scannerView.startCamera();
} else {
requestPermission();
}
}
}
#Override
public void onDestroy() {
super.onDestroy();
scannerView.stopCamera();
scannerView = null;
}
#Override
public void handleResult(final Result result) {
res = result.getText();
Log.d("Scanner Result", result.getText());
Log.d("Scanner Result", result.getBarcodeFormat().toString());
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Scan Result");
builder.setPositiveButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
scannerView.resumeCameraPreview(MainActivity.this);
}
});
builder.setNeutralButton("Send", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
GetText();
scannerView.resumeCameraPreview(MainActivity.this);
}
});
builder.setMessage(result.getText());
AlertDialog alert = builder.create();
alert.show();
}
public void GetText() //throws UnsupportedEncodingException
{
String data = res;
String text = "";
BufferedReader reader = null;
Log.e("Datafirst", data);
String requesturi = serverUrl + data;
// Send data
try {
URL url = new URL(requesturi);
Log.e("DataSecond", requesturi);
if (Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
Log.e("Data Third", data);
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
Toast.makeText(MainActivity.this, "Readed Successfully", Toast.LENGTH_SHORT).show();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
Toast.makeText(MainActivity.this, "Readed Successfully", Toast.LENGTH_SHORT).show();
}
text = sb.toString();
} catch (Exception ex) {
Log.e("Exceptionio", "Error", ex);
ex.printStackTrace();
} finally {
try {
reader.close();
Log.e("Closed", "Closed");
} catch (Exception ex) {
Log.e("Except2", "Error", ex);
ex.printStackTrace();
}
}
Log.e("setText", data);
}
}
Main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<me.dm7.barcodescanner.zxing.ZXingScannerView
android:id="#+id/zxscan"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ImageButton
android:id="#+id/img1"
android:layout_marginBottom="15dp"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
android:src="#drawable/imgbut"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
Try my code, It will look like this
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
android:orientation="vertical"
tools:context="com.package.name.TakeSingleScanActivity">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbarAdjustScan"
android:layout_width="match_parent"
android:layout_height="56dp"
android:background="#color/colorPrimary"
android:elevation="6dp"
android:minHeight="56dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/titleToolbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="15dp"
android:ellipsize="end"
android:layout_weight="1"
android:maxLines="1"
android:textColor="#color/white"
android:textSize="18dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="right"
android:padding="10dp"
android:id="#+id/searchAdjustBtn"
android:layout_marginLeft="15dp"
android:ellipsize="end"
android:maxLines="1"
android:text="SEARCH "
android:textColor="#color/white"
android:textSize="13dp" />
</LinearLayout>
</android.support.v7.widget.Toolbar>
<TextView
android:id="#+id/textv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimaryDark"
android:gravity="center_horizontal"
android:paddingBottom="10dp"
android:paddingTop="10dp"
android:text="Point at any barcode to scan"
android:textColor="#color/white"
android:textSize="14sp"
android:textStyle="normal" />
<RelativeLayout
android:layout_marginBottom="120dp"
android:layout_below="#+id/textv"
android:id="#+id/relative_scan_take_single"
android:layout_width="match_parent"
android:layout_height="match_parent">
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:layout_alignParentBottom="true"
android:layout_width="match_parent"
android:background="#color/colorPrimaryDark"
android:layout_height="120dp"
android:orientation="horizontal">
<Button
android:id="#+id/doneBtn"
style="#style/Widget.AppCompat.Button.Colored"
android:layout_width="match_parent"
android:layout_height="80dp"
android:layout_gravity="bottom"
android:text="Done"
android:textAllCaps="true"
android:textColor="#color/white"
android:textSize="22dp" />
</LinearLayout>
</RelativeLayout>
Java code for Scanner :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_take_single_scan);
init();
}
private void init() {
//Scanner
mScannerView = new ZXingScannerView(this);
RelativeLayout rl = (RelativeLayout) findViewById(R.id.relative_scan_take_single);
rl.addView(mScannerView);
mScannerView.setResultHandler(this);
mScannerView.startCamera();
mScannerView.setSoundEffectsEnabled(true);
mScannerView.setAutoFocus(true);
}
#Override
public void onResume() {
super.onResume();
mScannerView.setResultHandler(this); // Register ourselves as a handler for scan results.
mScannerView.startCamera(); // Start camera on resume
}
#Override
public void onPause() {
super.onPause();
mScannerView.stopCamera(); // Stop camera on pause
}
#Override
public void handleResult(Result rawResult) {
// Do something with the result here
Log.e(TAG, rawResult.getText()); // Prints scan results
Log.e(TAG, rawResult.getBarcodeFormat().toString());
Log.e("SCAN_RESULT", "" + rawResult.getText());
//dataSingle.put("0",rawResult.getText());
}

Ccavenue Integration not working in Android studio

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>

Categories