Error with new intent ANDROID STUDIO [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
package com.example.alex.askii;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
//Alex Levin
public class Login extends AppCompatActivity {
Button login;
Button signUp;
EditText userNameET;
EditText passWordET;
DatabaseHelper helper = new DatabaseHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
login = (Button)findViewById(R.id.Login);
signUp = (Button)findViewById(R.id.signUp);
userNameET = (EditText)findViewById(R.id.username);
passWordET = (EditText)findViewById(R.id.password);
login.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
//get text valiues
String userName = userNameET.getText().toString();
String passWord = passWordET.getText().toString();
//Query in java the username
String actualPassword = helper.searchPass(userName);
//If Correct
if(passWord.equals(actualPassword)){
Toast.makeText(getApplicationContext(),
"Redirecting...", Toast.LENGTH_SHORT).show();
/*
Intent i = new Intent(mainActivity.this, display.class);
i.putExtra("UserName", str);
startActivity(i)
Example code to go to next activity ^^
*/
}else{
Toast.makeText(getApplicationContext(), "Invalid Username Or Password", Toast.LENGTH_SHORT).show();
}
}
});
signUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Login.this, signUP.class);
startActivity(i);
}
});
}
}
<?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"
tools:context="com.example.alex.askii.Login">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Askii Login"
android:textSize = "30dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.033"
tools:layout_constraintRight_creator="1"
tools:layout_constraintLeft_creator="1" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text= "Username:"
android:textSize="20dp"
app:layout_constraintRight_toLeftOf="#+id/username"
tools:layout_constraintRight_creator="1"
tools:layout_constraintBottom_creator="1"
app:layout_constraintBottom_toBottomOf="#+id/username"
android:layout_marginEnd="7dp"
android:layout_marginBottom="4dp"
android:layout_marginRight="7dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text= "Password:"
android:textSize="20dp"
android:id="#+id/textView"
tools:layout_constraintBottom_creator="1"
android:layout_marginStart="16dp"
app:layout_constraintBottom_toBottomOf="parent"
tools:layout_constraintLeft_creator="1"
android:layout_marginBottom="169dp"
app:layout_constraintLeft_toLeftOf="parent"
android:layout_marginLeft="16dp" />
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/Login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Login"
android:onClick="login"
tools:layout_constraintRight_creator="1"
tools:layout_constraintBottom_creator="1"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_marginEnd="84dp"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginBottom="88dp"
android:layout_marginRight="130dp" />
<EditText
android:id="#+id/password"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPassword"
tools:layout_constraintRight_creator="1"
app:layout_constraintRight_toRightOf="#+id/username"
app:layout_constraintBaseline_toBaselineOf="#+id/textView"
tools:layout_constraintBaseline_creator="1"
tools:layout_constraintLeft_creator="1"
app:layout_constraintLeft_toLeftOf="#+id/username" />
<EditText
android:id="#+id/username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:text="Enter Username"
tools:layout_constraintBottom_creator="1"
app:layout_constraintBottom_toTopOf="#+id/password"
android:layout_marginStart="11dp"
tools:layout_constraintLeft_creator="1"
android:layout_marginBottom="20dp"
app:layout_constraintLeft_toRightOf="#+id/textView"
android:layout_marginLeft="11dp" />
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/signUp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sign Up"
tools:layout_constraintRight_creator="1"
tools:layout_constraintBottom_creator="1"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_marginEnd="84dp"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginRight="216dp"
android:layout_marginBottom="47dp" />
</android.support.constraint.ConstraintLayout>
package com.example.alex.askii;
import android.app.Activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
/**
* Created by Alex on 12/30/2017.
*/
public class signUP extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.signup);
}
Button signUpOnPage = (Button)findViewById(R.id.signUpOnPage);
public void onSignUpOnPage(View v){
if(v.getId() == R.id.signUpOnPage){
EditText userName = (EditText)findViewById(R.id.newUserName);
EditText passWord = (EditText)findViewById(R.id.newPassWord);
EditText confPassword = (EditText)findViewById(R.id.newUserName);
String userNameString = userName.getText().toString();
String passWordString = passWord.getText().toString();
String confPasswordString = confPassword.getText().toString();
if(!passWordString.equals(confPasswordString)){
Toast check = Toast.makeText(signUP.this, "Passwords Don't Match", Toast.LENGTH_SHORT);
check.show();
}
}
}
}
For some reason I am getting the following error
12-30 02:39:59.308 1969-1969/com.example.alex.askii E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.alex.askii/com.example.alex.askii.signUP}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1880)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.support.v7.app.AppCompatDelegateImplBase.<init>(AppCompatDelegateImplBase.java:118)
at android.support.v7.app.AppCompatDelegateImplV9.<init>(AppCompatDelegateImplV9.java:152)
at android.support.v7.app.AppCompatDelegateImplV11.<init>(AppCompatDelegateImplV11.java:29)
at android.support.v7.app.AppCompatDelegateImplV14.<init>(AppCompatDelegateImplV14.java:53)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:204)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:184)
at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:518)
at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:189)
at com.example.alex.askii.signUP.<init>(signUP.java:16)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1319)
at android.app.Instrumentation.newActivity(Instrumentation.java:1023)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1871)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981) 
at android.app.ActivityThread.access$600(ActivityThread.java:123) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:4424) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:511) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) 
at dalvik.system.NativeStart.main(Native Method) 
I am really unsure why this is happening maybe it is something wrong with my manifests but I doubt it because the manifest was autogenerated. Please help I can't find the answer online because it seems like I followed everything online correctly this is the last place I came to for help I am so frustrated right now!

Move
signUpOnPage = (Button)findViewById(R.id.signUpOnPage);
to onCreate()

Related

App keeps crashing every time i click the Log in Button

I am new to android, i was following some tutorial and at this point, app keeps crashing when i click the login button.
When i run the app and click the login button, the app crashes and in the logcat, it shows this error of java RuntimeException.
This is my logcat, loginactivity.xml and loginactivity.java.
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.ugtunda/com.example.ugtunda.LoginActivity}:
java.lang.ClassCastException:
androidx.appcompat.widget.AppCompatTextView cannot be cast to
com.rey.material.widget.TextView
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2806)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2884)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1614)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6524)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:451)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:888)
Caused by: java.lang.ClassCastException: androidx.appcompat.widget.AppCompatTextView cannot be cast to
com.rey.material.widget.TextView
at com.example.ugtunda.LoginActivity.onCreate(LoginActivity.java:48)
at android.app.Activity.performCreate(Activity.java:7044)
at android.app.Activity.performCreate(Activity.java:7035)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2759)
Here is my login_activity_XML
<?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:background="#drawable/login"
tools:context=".LoginActivity">
<ImageView
android:id="#+id/login_applogo"
android:layout_width="300dp"
android:layout_height="100dp"
android:src="#drawable/applogo"
android:layout_centerHorizontal="true"
android:layout_marginTop="200dp"
/>
<EditText
android:id="#+id/login_phone_number_input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/login_applogo"
android:background="#drawable/input_design"
android:padding="20dp"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:hint="Phone Number"
android:inputType="number"
android:textColor="#color/colorPrimaryDark"
android:textColorHint="#color/colorPrimaryDark"
android:textSize="17sp"
android:textStyle="bold"
/>
<EditText
android:id="#+id/login_password_input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/login_phone_number_input"
android:background="#drawable/input_design"
android:padding="20dp"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_marginTop="6dp"
android:hint="Password"
android:inputType="textPassword"
android:textColor="#color/colorPrimaryDark"
android:textColorHint="#color/colorPrimaryDark"
android:textSize="17sp"
android:textStyle="bold"
/>
<LinearLayout
android:id="#+id/linear_layout_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_below="#id/login_password_input"
android:layout_marginTop="5dp"
>
<com.rey.material.widget.CheckBox
android:id="#+id/remember_me_chkb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="#style/Material.Drawable.CheckBox"
android:text="Remember Me"
android:textColor="#color/colorPrimaryDark"
app:cbd_strokeColor="#color/colorPrimaryDark"
android:gravity="center_vertical"
android:textSize="16sp"
android:textStyle="bold"
android:layout_marginLeft="17dp"
/>
<TextView
android:id="#+id/forget_password_link"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Forget Password"
android:textColor="#color/colorPrimaryDark"
android:textSize="15sp"
android:textStyle="bold"
android:layout_marginLeft="80dp"
/>
</LinearLayout>
<Button
android:id="#+id/login_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/linear_layout_1"
android:layout_marginTop="5dp"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:background="#drawable/buttons"
android:padding="17dp"
android:text="Login"
android:textAllCaps="false"
android:textColor="#android:color/white"
android:textSize="18sp" />
<TextView
android:id="#+id/admin_panel_link"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/login_button"
android:layout_alignParentEnd="true"
android:layout_marginLeft="80dp"
android:layout_marginEnd="23dp"
android:text="I'm an Admin"
android:textAppearance="#android:style/TextAppearance.Material.Small"
android:textColor="#color/colorPrimaryDark"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="#+id/not_admin_panel_link"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I'm not an Admin"
android:layout_alignParentStart="true"
android:layout_below="#+id/login_button"
android:textColor="#color/colorPrimaryDark"
android:textSize="20sp"
android:textStyle="bold"
android:layout_marginLeft="80dp"
android:layout_marginEnd="23dp"
android:layout_marginStart="25dp"
android:visibility="invisible"
/>
</RelativeLayout>
And lastly my loginactivity.java
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.ugtunda.Models.Users;
import com.example.ugtunda.Prevalent.Prevalent;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.rey.material.widget.CheckBox;
import com.rey.material.widget.TextView;
import io.paperdb.Paper;
public class LoginActivity extends AppCompatActivity
{
private EditText InputPhoneNumber, InputPassword;
private Button LoginButton;
private ProgressDialog loadingBar;
private TextView AdminLink, NotAdminLink;
private String parentDbName = "Users";
private CheckBox chkBoxRememberMe;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
LoginButton = findViewById(R.id.login_button);
InputPassword = findViewById(R.id.login_password_input);
InputPhoneNumber = findViewById(R.id.login_phone_number_input);
AdminLink = findViewById(R.id.admin_panel_link);
NotAdminLink = findViewById(R.id.not_admin_panel_link);
loadingBar = new ProgressDialog(this);
chkBoxRememberMe = findViewById(R.id.remember_me_chkb);
Paper.init(this);
LoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
LoginUser();
}
});
AdminLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
LoginButton.setText("Login Admin");
AdminLink.setVisibility(View.INVISIBLE);
NotAdminLink.setVisibility(View.VISIBLE);
parentDbName = "Admins";
}
});
NotAdminLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
LoginButton.setText("Login");
AdminLink.setVisibility(View.VISIBLE);
NotAdminLink.setVisibility(View.INVISIBLE);
parentDbName = "Users";
}
});
}
private void LoginUser()
{
String phone = InputPhoneNumber.getText().toString();
String password = InputPassword.getText().toString();
if (TextUtils.isEmpty(phone))
{
Toast.makeText(this, "Please write your phone number...", Toast.LENGTH_SHORT).show();
}
else if (TextUtils.isEmpty(password))
{
Toast.makeText(this, "Please write your password...", Toast.LENGTH_SHORT).show();
}
else
{
loadingBar.setTitle("Login Account");
loadingBar.setMessage("Please wait, while we are checking the credentials.");
loadingBar.setCanceledOnTouchOutside(false);
loadingBar.show();
AllowAccessToAccount(phone, password);
}
}
private void AllowAccessToAccount(final String phone, final String password)
{
if(chkBoxRememberMe.isChecked())
{
Paper.book().write(Prevalent.USER_PHONE_KEY, phone);
Paper.book().write(Prevalent.USER_PASSWORD_KEY, password);
}
final DatabaseReference RootRef;
RootRef = FirebaseDatabase.getInstance().getReference();
RootRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
{
if (dataSnapshot.child(parentDbName).child(phone).exists())
{
Users usersData = dataSnapshot.child(parentDbName).child(phone).getValue(Users.class);
if (usersData.getPhone().equals(phone))
{
if (usersData.getPassword().equals(password))
{
if (parentDbName.equals("Admins"))
{
Toast.makeText(LoginActivity.this, "Welcome Admin, you are logged in Successfully...", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
Intent intent = new Intent(LoginActivity.this, AdminCategoryActivity.class);
startActivity(intent);
}
else if (parentDbName.equals("Users"))
{
Toast.makeText(LoginActivity.this, "logged in Successfully...", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
Prevalent.currentOnlineUser = usersData;
startActivity(intent);
}
}
else
{
loadingBar.dismiss();
Toast.makeText(LoginActivity.this, "Password is incorrect.", Toast.LENGTH_SHORT).show();
}
}
}
else
{
Toast.makeText(LoginActivity.this, "Account with this " + phone + " number do not exists.", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
It looks like you're defining standard Android components in the XML layout, then attempting to inflate them into custom components (the com.rey.material package). Try going into your imports and deleting the com.rey.material lines. Then when your IDE prompts you to import the TextView and Checkbox, make sure you're importing the versions from android.widget, not com.rey.material. Alternatively, you could change your XML file to specify the com.rey.material components if you wanted to be using those instead of the default ones.
You used the wrong import so you need to
replace this import
import com.rey.material.widget.TextView;
with
import android.widget.TextView;
OR
You can use the corresponding view in the XML
Replace
<TextView
android:id="#+id/forget_password_link"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Forget Password"
android:textColor="#color/colorPrimaryDark"
android:textSize="15sp"
android:textStyle="bold"
android:layout_marginLeft="80dp"
/>
with
<com.rey.material.widget.TextView
android:id="#+id/forget_password_link"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Forget Password"
android:textColor="#color/colorPrimaryDark"
android:textSize="15sp"
android:textStyle="bold"
android:layout_marginLeft="80dp" />
in your XML file
Looks like you are using the AppCompat Button in your XML, but using the material button in your java code.
So they need to be the same.
First you need to use the right import for whatever view you're using, if you want to use the AppCompat button then import like this
import android.widget.Button;
If you want to use the Material button, then use this import:
import com.rey.material.widget.Button;
Same thing goes for the TextView.
Hope this helps!
androidx.appcompat.widget.AppCompatTextView cannot be cast to
com.rey.material.widget.TextView
In your xml, you're using the SDK TextView but in your code, you want the com.rey.material.widget one.
--> Change one of these

What may be the problem with this java and XML code?

Am getting a null pointer exception after setting the onclick listeners on the textview and the button. Where could be the error be please?
MainActivity.xml file
<?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="match_parent"
android:gravity="center"
android:orientation="vertical"
android:background="#drawable/background_design"
tools:context=".MainActivity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Login"
android:textAppearance="?android:textAppearanceLarge"
android:textColor="#ffffff"></TextView>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter your email..."
android:textColorHint="#android:color/white"
android:textColor="#ffffff"
android:background="#drawable/ed_design"
android:padding="10dp"
android:inputType="textEmailAddress"
android:layout_margin="10dp"
android:id="#+id/email_login"></EditText>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter your password..."
android:textColorHint="#android:color/white"
android:textColor="#ffffff"
android:background="#drawable/ed_design"
android:padding="10dp"
android:layout_margin="10dp"
android:inputType="textPassword"
android:id="#+id/pass_login"></EditText>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/login_button"
android:text="Login"
android:textAllCaps="false"
android:background="#drawable/ed_design"
android:padding="10dp"
android:textColor="#android:color/white"
android:textAppearance="?android:textAppearanceMedium"
android:layout_margin="10dp"></Button>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:textAppearanceSmall"
android:text="don't have an account? REGISTER here"
android:id="#+id/toRegisterActivity"
android:gravity="center"
android:textColor="#android:color/white"
android:padding="5dp"></TextView>
</LinearLayout>
</ScrollView>
</LinearLayout>
MainActivity.java file
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
public class MainActivity extends AppCompatActivity {
private EditText email, pass;
private Button login_button;
private TextView toRegisterActivity;
private ProgressDialog progressDialog;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
email = findViewById(R.id.email_login);
pass = findViewById(R.id.pass_login);
login_button = findViewById(R.id.login_button);
toRegisterActivity = findViewById(R.id.toRegisterActivity);
progressDialog = new ProgressDialog(this);
mAuth = FirebaseAuth.getInstance();
toRegisterActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent registerIntent = new Intent(MainActivity.this, RegistrationActivity.class);
startActivity(registerIntent);
}
});
login_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String mEmail = email.getText().toString().trim();
String mPass = pass.getText().toString().trim();
if (TextUtils.isEmpty(mEmail)){
email.setError("Email required!");
return;
}
if (TextUtils.isEmpty(mPass)){
pass.setError("Password required!");
return;
}
else {
progressDialog.setTitle("Login in ...");
progressDialog.setMessage("please wait as we log you in.");
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
mAuth.signInWithEmailAndPassword(mEmail,mPass).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
Toast.makeText(MainActivity.this, "Login Successful", Toast.LENGTH_SHORT).show();
Intent homeIntent = new Intent(MainActivity.this, HomeActivity.class);
homeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK |Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(homeIntent);
finish();
progressDialog.dismiss();
}else {
String errorMsg = task.getException().toString();
Toast.makeText(MainActivity.this, "Login Failed, please try again."+ errorMsg, Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}
});
}
}
});
}
}
StackTrace
11-04 21:25:31.840 16416-16416/com.example.checkmydailyspend E/Zygote: MountEmulatedStorage()
11-04 21:25:31.840 16416-16416/com.example.checkmydailyspend E/Zygote: v2
11-04 21:25:31.840 16416-16416/com.example.checkmydailyspend E/SELinux: [DEBUG] get_category: variable seinfo: default sensitivity: NULL, cateogry: NULL
11-04 21:25:33.202 16416-16416/com.example.checkmydailyspend E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.checkmydailyspend, PID: 16416
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.checkmydailyspend/com.example.checkmydailyspend.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3160)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3275)
at android.app.ActivityThread.access$1000(ActivityThread.java:218)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1744)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:7007)
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:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.checkmydailyspend.MainActivity.onCreate(MainActivity.java:43)
at android.app.Activity.performCreate(Activity.java:6609)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1134)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3113)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3275) 
at android.app.ActivityThread.access$1000(ActivityThread.java:218) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1744) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:145) 
at android.app.ActivityThread.main(ActivityThread.java:7007) 
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:1404) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
Change setContentView(R.layout.activity_registration); to setContentView(R.layout.MainActivity);

Clicking register causes android app to crash

Clicking on register makes the app crash when the email and password fields are empty, but when the name field is empty it works properly what seems to be the problem?
xml file:
<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"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:gravity="center_vertical|center_horizontal"
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="com.example.zachmarcelo.softcash.LoginActivity"
android:background="#fff"
>
<!-- Login progress -->
<ImageView
android:layout_width="match_parent"
android:layout_height="47dp"
android:layout_marginBottom="20dp"
android:visibility="visible"
app:srcCompat="#drawable/icon_ewallet_" />
<ProgressBar
android:id="#+id/login_progress"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:visibility="gone" />
<ScrollView
android:id="#+id/login_form"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center">
<LinearLayout
android:id="#+id/email_login_form"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical|center_horizontal"
android:orientation="vertical">
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textColorHint="#color/colorHint" >
<EditText
android:id="#+id/reg_username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Name"
android:inputType="text"
android:textSize="20sp"
android:textColor="#android:color/background_dark"
/>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/TextLabel"
android:textColorHint="#color/colorHint">
<EditText
android:id="#+id/reg_email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:backgroundTint="#android:color/darker_gray"
android:hint="Email"
android:maxLines="1"
android:singleLine="true"
android:textColor="#android:color/background_dark"
android:inputType="textEmailAddress"
/>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/TextLabel"
android:textColorHint="#color/colorHint">
<EditText
android:id="#+id/reg_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:backgroundTint="#android:color/background_dark"
android:hint="Password"
android:imeActionId="6"
android:imeActionLabel="#string/action_sign_in_short"
android:imeOptions="actionUnspecified"
android:inputType="textPassword"
android:maxLines="1"
android:singleLine="true"
android:textColor="#android:color/background_dark" />
</android.support.design.widget.TextInputLayout>
<Button
android:id="#+id/register"
style="?android:textAppearanceSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:background="#color/colorAccent"
android:gravity="center"
android:paddingLeft="20sp"
android:paddingRight="20sp"
android:text="Register"
android:textStyle="bold"
android:layout_marginBottom="20dp"/>
<TextView
android:id="#+id/signin"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="Already have an account?"
android:textAlignment="center"
android:textColor="#color/colorPrimary"
android:textSize="12dp" />
</LinearLayout>
</ScrollView>
<ProgressBar
android:id="#+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" />
code:
package com.example.zachmarcelo.softcash;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TextInputEditText;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.Patterns;
import android.view.View;
import android.view.WindowManager;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.FirebaseDatabase;
public class RegisterActivity extends AppCompatActivity implements
View.OnClickListener {
private EditText reg_password,
reg_username,
reg_email;
private FirebaseAuth mAuth;
private ProgressBar progressBar;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
progressBar = new ProgressBar(getApplicationContext());
reg_password = findViewById(R.id.reg_password);
reg_email = findViewById(R.id.reg_email);
reg_username = findViewById(R.id.reg_username);
progressBar = findViewById(R.id.progressBar);
progressBar.setVisibility(View.GONE);
mAuth = FirebaseAuth.getInstance();
findViewById(R.id.register).setOnClickListener(this);
findViewById(R.id.signin).setOnClickListener(this);
}
#Override
protected void onStart() {
super.onStart();
if (mAuth.getCurrentUser() != null) {
Intent i = new Intent(RegisterActivity.this, HomeActivity.class);
startActivity(i);
finish();
}
}
private void registerUser() {
final String username = reg_username.getText().toString().trim();
final String email = reg_email.getText().toString().trim();
String password = reg_password.getText().toString().trim();
if (username.equals("")) {
reg_username.setError(getString(R.string.input_error_name));
reg_username.requestFocus();
return;
}
if (email.equals("")) {
reg_email.setError(getString(R.string.input_error_email));
reg_email.requestFocus();
return;
}else{
if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
reg_email.setError(getString(R.string.input_error_email_invalid));
reg_email.requestFocus();
return;
}
}
if (password.equals("")) {
reg_password.setError(getString(R.string.input_error_password));
reg_password.requestFocus();
return;
}else{
if (password.length() < 8) {
reg_password.setError(getString(R.string.input_error_password_length));
reg_password.requestFocus();
return;
}
}
progressBar.setVisibility(View.VISIBLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
User user = new User(
username,
email
);
FirebaseDatabase.getInstance().getReference("Users")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
progressBar.setVisibility(View.GONE);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
if (task.isSuccessful()) {
Toast.makeText(RegisterActivity.this, getString(R.string.registration_success), Toast.LENGTH_LONG).show();
Intent i = new Intent(RegisterActivity.this, LoginActivity.class);
startActivity(i);
finish();
} else {
Toast.makeText(RegisterActivity.this, getString(R.string.registration_failed), Toast.LENGTH_LONG).show();
}
}
});
} else {
Toast.makeText(RegisterActivity.this, task.getException().getMessage(), Toast.LENGTH_LONG).show();
}
}
});
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.register:
registerUser();
break;
case R.id.signin:
Intent i = new Intent(this, LoginActivity.class);
startActivity(i);
finish();
break;
}
}
}
error log:
09-03 13:25:24.942 15875-15875/com.example.zachmarcelo.softcash E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.zachmarcelo.softcash, PID: 15875
android.view.InflateException: Binary XML file line #17: Binary XML file line #17: Error inflating class TextView
Caused by: android.view.InflateException: Binary XML file line #17: Error inflating class TextView
Caused by: java.lang.UnsupportedOperationException: Failed to resolve attribute at index 4: TypedValue{t=0x2/d=0x1010099 a=1}
at android.content.res.TypedArray.getColor(TypedArray.java:492)
at android.widget.TextView.<init>(TextView.java:955)
at android.widget.TextView.<init>(TextView.java:872)
at android.support.v7.widget.AppCompatTextView.<init>(AppCompatTextView.java:75)
at android.support.v7.widget.AppCompatTextView.<init>(AppCompatTextView.java:71)
at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:103)
at android.support.v7.app.AppCompatDelegateImplV9.createView(AppCompatDelegateImplV9.java:1024)
at android.support.v7.app.AppCompatDelegateImplV9.onCreateView(AppCompatDelegateImplV9.java:1081)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:783)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:741)
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:505)
at android.widget.Editor.onFocusChanged(Editor.java:1237)
at android.widget.TextView.onFocusChanged(TextView.java:9821)
at android.view.View.handleFocusGainInternal(View.java:6631)
at android.view.View.requestFocusNoSearch(View.java:10890)
at android.view.View.requestFocus(View.java:10869)
at android.view.View.requestFocus(View.java:10836)
at android.view.View.requestFocus(View.java:10778)
at com.example.zachmarcelo.softcash.RegisterActivity.registerUser(RegisterActivity.java:74)
at com.example.zachmarcelo.softcash.RegisterActivity.onClick(RegisterActivity.java:143)
at android.view.View.performClick(View.java:6291)
at android.view.View$PerformClick.run(View.java:24931)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:101)
at android.os.Looper.loop(Looper.java:166)
at android.app.ActivityThread.main(ActivityThread.java:7425)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921)
and this is what is supposed to be happening: (works perfectly in name text but not in other edittexts)
screenshot of mobile app
any help will be appreciated :D
My guess is that it has something to do with what you put into #style/TextLabel.
When you have an error with password or email you request focus programmatically. Which is fine, however when that happens something in your style is looking for a color resource which doesn't exist. That's what's causing the error.
The error seems to be for getColor() method of textview, your primary color has some problem, please check that.

FATAL EXCEPTION: main....java.lang.RuntimeException: Unable to instantiate activity ComponentInfo.? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I'm very new to Android Studio and I know a little java.So I'm trying a simple calculator app with simple layout.I hope all my code is correct but I don't know what's wrong in it.When I run the app it is not at all opening and showing a FATAL exception main.Here is the xml code,java code and logcat of my app.So please help me to make corrections.Thanks!
XML Code ::
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayoutxmlns: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="com.example.narendra.calculator.MainActivity"
tools:layout_editor_absoluteY="81dp"
tools:layout_editor_absoluteX="0dp">
<EditText
android:id="#+id/editText"
android:layout_width="360dp"
android:layout_height="159dp"
android:background="#android:color/holo_blue_light"
android:ems="10"
android:hint="#string/num"
android:inputType="number"
android:textAlignment="center"
android:textAllCaps="true"
android:textSize="50sp"
android:textStyle="bold"
tools:ignore="MissingConstraints,RtlHardcoded"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="16dp"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
android:layout_marginRight="8dp"
android:layout_marginLeft="8dp"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp" />
<EditText
android:id="#+id/editText2"
android:layout_width="360dp"
android:layout_height="159dp"
android:background="#android:color/holo_green_light"
android:ems="10"
android:hint="#string/Num2"
android:inputType="number"
android:textAlignment="center"
android:textAllCaps="true"
android:textSize="50sp"
android:textStyle="bold"
tools:ignore="MissingConstraints,RtlHardcoded"
tools:layout_editor_absoluteY="180dp"
tools:layout_editor_absoluteX="26dp" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onAddButtonClick"
android:text="#string/a"
android:textSize="50sp"
app:layout_constraintLeft_toLeftOf="#+id/editText2"
app:layout_constraintTop_toTopOf="#+id/editText"
android:layout_marginTop="323dp"
tools:ignore="RtlHardcoded"
app:layout_constraintRight_toLeftOf="#+id/button3"
app:layout_constraintHorizontal_bias="0.0"
android:layout_marginRight="5dp"
android:layout_marginEnd="5dp" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onSubtractionButtonClick"
android:text="#string/m"
android:textSize="50sp"
android:layout_marginLeft="5dp"
app:layout_constraintTop_toTopOf="#+id/editText"
android:layout_marginTop="323dp"
tools:ignore="RtlHardcoded"
app:layout_constraintLeft_toRightOf="#+id/button"
app:layout_constraintHorizontal_bias="0.03"
android:layout_marginRight="5dp"
app:layout_constraintRight_toRightOf="#+id/button3"
android:layout_marginStart="5dp"
android:layout_marginEnd="5dp" />
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onMultiplicationButtonClick"
android:text="#string/p"
android:textSize="50sp"
android:layout_marginLeft="5dp"
app:layout_constraintTop_toTopOf="#+id/editText"
android:layout_marginTop="323dp"
tools:ignore="RtlHardcoded"
app:layout_constraintLeft_toRightOf="#+id/button2"
android:layout_marginRight="5dp"
app:layout_constraintRight_toRightOf="#+id/button4"
app:layout_constraintHorizontal_bias="0.0"
android:layout_marginStart="5dp"
android:layout_marginEnd="5dp" />
<Button
android:id="#+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onDivisionButtonClick"
android:text="#string/d"
android:textSize="50sp"
android:layout_marginLeft="5dp"
app:layout_constraintRight_toRightOf="#+id/editText2"
app:layout_constraintTop_toTopOf="#+id/editText"
android:layout_marginTop="323dp"
tools:ignore="RtlHardcoded"
app:layout_constraintLeft_toRightOf="#+id/button3"
app:layout_constraintHorizontal_bias="0.0"
android:layout_marginStart="5dp"
android:layout_marginRight="5dp" />
<TextView
android:id="#+id/textView"
android:layout_width="360dp"
android:layout_height="100dp"
android:layout_marginBottom="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="16dp"
android:layout_marginTop="8dp"
android:background="#color/colorAccent"
android:text="#string/Result"
android:textAlignment="center"
android:textAllCaps="true"
android:textSize="50sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.771"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.839"
tools:ignore="RtlHardcoded" />
Java Code ::
package com.example.narendra.calculator;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
EditText e1=(EditText)findViewById(R.id.editText);
EditText e2=(EditText)findViewById(R.id.editText2);
TextView t1=(TextView)findViewById(R.id.textView);
int num1=Integer.parseInt(e1.getText().toString());
int num2=Integer.parseInt(e2.getText().toString());
public void conditionCheck(){
if(e1.getText().toString().isEmpty()){
e1.setError("Please Enter a valid number");
}
else if(e2.getText().toString().isEmpty()){
e2.setError("Please Enter a valid number");
}
}
public void onAddButtonClick(View v){
conditionCheck();
int sum=num1+num2;
t1.setText(sum);
Toast.makeText(MainActivity.this, " Thank You ", Toast.LENGTH_SHORT).show();
}
public void onSubtractionButtonClick(View v){
conditionCheck();
int diff=num1-num2;
t1.setText(diff);
Toast.makeText(MainActivity.this, " Thank You ", Toast.LENGTH_SHORT).show();
}
public void onMultiplicationButtonClick(View v){
conditionCheck();
int product=num1*num2;
t1.setText(product);
Toast.makeText(MainActivity.this, " Thank You ", Toast.LENGTH_SHORT).show();
}
public void onDivisionButtonClick(View v){
conditionCheck();
if(num2==0){
e2.setError(" Zero is not allowed here");
}
else {
int quotient = num1 / num2;
t1.setText(quotient);
Toast.makeText(MainActivity.this, " Thank You ", Toast.LENGTH_SHORT).show();
}
}
}
Logcat ::
06-14 12:31:23.216 4822-4822/? I/art: Not late-enabling -Xcheck:jni (already on)
06-14 12:31:23.216 4822-4822/? W/art: Unexpected CPU variant for X86 using defaults: x86
06-14 12:31:23.342 4822-4822/? W/System: ClassLoader referenced unknown path: /data/app/com.example.narendra.calculator-2/lib/x86
06-14 12:31:23.348 4822-4822/? I/InstantRun: starting instant run server: is main process
06-14 12:31:23.405 4822-4822/? D/AndroidRuntime: Shutting down VM
06-14 12:31:23.405 4822-4822/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.narendra.calculator, PID: 4822
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.narendra.calculator/com.example.narendra.calculator.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2548)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
at android.support.v7.app.AppCompatDelegateImplBase.<init>(AppCompatDelegateImplBase.java:120)
at android.support.v7.app.AppCompatDelegateImplV9.<init>(AppCompatDelegateImplV9.java:155)
at android.support.v7.app.AppCompatDelegateImplV11.<init>(AppCompatDelegateImplV11.java:31)
at android.support.v7.app.AppCompatDelegateImplV14.<init>(AppCompatDelegateImplV14.java:55)
at android.support.v7.app.AppCompatDelegateImplV23.<init>(AppCompatDelegateImplV23.java:33)
at android.support.v7.app.AppCompatDelegateImplN.<init>(AppCompatDelegateImplN.java:33)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:201)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:185)
at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:519)
at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:190)
at com.example.narendra.calculator.MainActivity.<init>(MainActivity.java:17)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1078)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2538)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6077) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756) 
Your onCreate() is closed early
Change it to
package com.example.narendra.calculator;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText e1,e2;
int num1,num2;
TextView t1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
e1 = (EditText) findViewById(R.id.editText);
e2 = (EditText) findViewById(R.id.editText2);
t1 = (TextView) findViewById(R.id.textView);
num1 = Integer.parseInt(e1.getText().toString());
num2 = Integer.parseInt(e2.getText().toString());
} public void conditionCheck(){
if(e1.getText().toString().isEmpty()){
e1.setError("Please Enter a valid number");
}
else if(e2.getText().toString().isEmpty()){
e2.setError("Please Enter a valid number");
}
}
public void onAddButtonClick(View v){
conditionCheck();
int sum=num1+num2;
t1.setText(sum);
Toast.makeText(MainActivity.this, " Thank You ", Toast.LENGTH_SHORT).show();
}
public void onSubtractionButtonClick(View v){
conditionCheck();
int diff=num1-num2;
t1.setText(diff);
Toast.makeText(MainActivity.this, " Thank You ", Toast.LENGTH_SHORT).show();
}
public void onMultiplicationButtonClick(View v){
conditionCheck();
int product=num1*num2;
t1.setText(product);
Toast.makeText(MainActivity.this, " Thank You ", Toast.LENGTH_SHORT).show();
}
public void onDivisionButtonClick(View v){
conditionCheck();
if(num2==0){
e2.setError(" Zero is not allowed here");
}
else {
int quotient = num1 / num2;
t1.setText(quotient);
Toast.makeText(MainActivity.this, " Thank You ", Toast.LENGTH_SHORT).show();
}
}
}
Just modify the code of (view init) position,
like this:
MainActivity{
onCreate(){
View view = findViewById(id);
}
}
Note: the Activity is a component that has self life-cycle. so can't apply it as a simple Pojo

Attempting to Save Data In a SQLite Database - Cleaned (no major issues) Still Force Closes

I'm a bit new to StackOverflow and I was wondering if I could have a bit of input on the following issue: I'm attempting to save a bit of data in a sqlite database but each time I attempt to do so the app force closes and I'm not sure why. I've cleaned the file and there are no issues. (I have no idea what I've done wrong - but something has been programmed incorrectly.)
JAVA:
import android.app.Activity;
import android.app.AlertDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.ViewGroup;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TimePicker;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.text.format.DateFormat;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.app.Activity;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.format.DateFormat;
import android.widget.TimePicker;
import com.nfc.linkingmanager.TimePickerFragment.TimePickedListener;
import java.util.Calendar;
public class AddEditCountry extends Activity implements TimePickedListener
{
private TextView mPickedTimeText;
private Button mPickTimeButton;
private long rowID;
private EditText nameEt;
private EditText capEt;
private EditText codeEt;
private TimePicker timeEt;
public static final String KEY_BUNDLE_TIME = "time";
public static final String KEY_BUNDLE_MIN = "min";
#Override
public void onCreate(Bundle savedInstanceState)
{
setContentView(R.layout.add_country); // where your_layout is the name of the xml file with the layout you want to use minus the .xml extention
//this layout must contain all of these views below that you are trying to initialize
nameEt = (EditText) findViewById(R.id.nameEdit);
capEt = (EditText) findViewById(R.id.capEdit);
codeEt = (EditText) findViewById(R.id.codeEdit);
timeEt = (TimePicker) findViewById(R.id.timeEdit);
Bundle extras = getIntent().getExtras();
if (extras != null)
{
rowID = extras.getLong("row_id");
nameEt.setText(extras.getString("name"));
capEt.setText(extras.getString("cap"));
codeEt.setText(extras.getString("code"));
String time = extras.getString("time");
String[] parts = time.split(":");
timeEt.setCurrentHour(Integer.valueOf(parts[0]));
timeEt.setCurrentMinute(Integer.valueOf(parts[1]));
timeEt.setIs24HourView(false);
}
Button saveButton =(Button) findViewById(R.id.saveBtn);
saveButton.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
if (nameEt.getText().length() != 0)
{
AsyncTask<Object, Object, Object> saveContactTask =
new AsyncTask<Object, Object, Object>()
{
#Override
protected Object doInBackground(Object... params)
{
saveContact();
return null;
}
#Override
protected void onPostExecute(Object result)
{
finish();
}
};
saveContactTask.execute((Object[]) null);
}
else
{
AlertDialog.Builder alert = new AlertDialog.Builder(AddEditCountry.this);
alert.setTitle(R.string.errorTitle);
alert.setMessage(R.string.errorMessage);
alert.setPositiveButton(R.string.errorButton, null);
alert.show();
}
}
});
}
private void saveContact()
{
DatabaseConnector dbConnector = new DatabaseConnector(this);
if (getIntent().getExtras() == null)
{
dbConnector.insertContact(nameEt.getText().toString(),
capEt.getText().toString(),
timeEt.getCurrentHour().toString() + ":"
+ timeEt.getCurrentMinute().toString(),
codeEt.getText().toString());
}
else
{
dbConnector.insertContact(nameEt.getText().toString(),
capEt.getText().toString(),
timeEt.getCurrentHour().toString() + ":"
+ timeEt.getCurrentMinute().toString(),
codeEt.getText().toString());
}
}
#Override
public void onTimePicked(Calendar time)
{
// display the selected time in the TextView
mPickedTimeText.setText(DateFormat.format("h:mm a", time));
}
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content" android:layout_weight="1">
<LinearLayout android:id="#+id/linearLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="5dp">
<EditText android:id="#+id/nameEdit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:imeOptions="actionNext"
android:hint="#string/name_hint"
android:inputType="textPersonName|textCapWords"/>
<EditText android:id="#+id/capEdit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:imeOptions="actionNext"
android:hint="#string/cap_hint"
android:inputType="textPersonName|textCapWords"/>
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Data Limit"
android:textColor="#ffffff"
android:textAppearance="?android:textAppearanceMedium" />
<SeekBar
android:id="#+id/seekBar1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1.0"
android:gravity="left"
android:textColor="#ffffff"
android:text="10MB" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1.0"
android:gravity="right"
android:textColor="#ffffff"
android:text="Unlimited Data" />
</LinearLayout>
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Bandwidth Limit"
android:textColor="#ffffff"
android:textAppearance="?android:textAppearanceMedium" />
<SeekBar
android:id="#+id/seekBar1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1.0"
android:gravity="left"
android:textColor="#ffffff"
android:text="10kbs" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1.0"
android:textColor="#ffffff"
android:gravity="right"
android:text="Unlimited Bandwidth" />
</LinearLayout>
<TextView
android:id="#+id/TextView02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:textAppearanceSmall" />
<TextView
android:id="#+id/TextView02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="WiFi Time Limit"
android:textColor="#ffffff"
android:textAppearance="?android:textAppearanceMedium" />
<TimePicker
android:id="#+id/timeEdit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:layout_weight="1.0" />
<EditText
android:id="#+id/codeEdit"
android:inputType="textUri"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:ems="10"
android:lines="1"
android:hint="#string/code_hint"
android:imeOptions="actionNext" />
<Button android:id="#+id/saveBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:layout_gravity="center_horizontal"
android:text="#string/save_btn"/>
</LinearLayout>
</ScrollView>
PROBLEMS:
Cleaned - No Problems
LOGCAT:
03-29 13:23:28.950: D/OpenGLRenderer(20744): Enabling debug mode 0
03-29 13:23:33.780: D/AndroidRuntime(20744): Shutting down VM
03-29 13:23:33.780: W/dalvikvm(20744): threadid=1: thread exiting with uncaught exception (group=0x41f7b930)
03-29 13:23:33.790: E/AndroidRuntime(20744): FATAL EXCEPTION: main
03-29 13:23:33.790: E/AndroidRuntime(20744): android.app.SuperNotCalledException: Activity {com.app.gamedemo/com.app.gamedemo.AddEditCountry} did not call through to super.onCreate()
03-29 13:23:33.790: E/AndroidRuntime(20744): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2146)
03-29 13:23:33.790: E/AndroidRuntime(20744): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
03-29 13:23:33.790: E/AndroidRuntime(20744): at android.app.ActivityThread.access$600(ActivityThread.java:141)
03-29 13:23:33.790: E/AndroidRuntime(20744): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
03-29 13:23:33.790: E/AndroidRuntime(20744): at android.os.Handler.dispatchMessage(Handler.java:99)
03-29 13:23:33.790: E/AndroidRuntime(20744): at android.os.Looper.loop(Looper.java:137)
03-29 13:23:33.790: E/AndroidRuntime(20744): at android.app.ActivityThread.main(ActivityThread.java:5041)
03-29 13:23:33.790: E/AndroidRuntime(20744): at java.lang.reflect.Method.invokeNative(Native Method)
03-29 13:23:33.790: E/AndroidRuntime(20744): at java.lang.reflect.Method.invoke(Method.java:511)
03-29 13:23:33.790: E/AndroidRuntime(20744): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
03-29 13:23:33.790: E/AndroidRuntime(20744): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
03-29 13:23:33.790: E/AndroidRuntime(20744): at dalvik.system.NativeStart.main(Native Method)
03-29 13:23:35.390: I/Process(20744): Sending signal. PID: 20744 SIG: 9
The problem is here in your onCreate()
#Override
public void onCreate(Bundle savedInstanceState)
{
nameEt = (EditText) findViewById(R.id.nameEdit);
capEt = (EditText) findViewById(R.id.capEdit);
codeEt = (EditText) findViewById(R.id.codeEdit);
timeEt = (TimePicker) findViewById(R.id.timeEdit);
You need to call setContentView() before trying to access your EditTexts and so on. Your Views "live" within your layout (xml file) so they are null until you inflate the layout. Change it to someting like
#Override
public void onCreate(Bundle savedInstanceState)
{
setContentView(R.layout.your_layout); // where your_layout is the name of the xml file with the layout you want to use minus the .xml extention
//this layout must contain all of these views below that you are trying to initialize
nameEt = (EditText) findViewById(R.id.nameEdit);
capEt = (EditText) findViewById(R.id.capEdit);
codeEt = (EditText) findViewById(R.id.codeEdit);
timeEt = (TimePicker) findViewById(R.id.timeEdit);
Edit
Just like the error says, you are trying to cast a TextView to a TimePicker. Here
timeEt = (TimePicker) findViewById(R.id.timeEdit);
(R.id.timeEdit) points to a TextView but here
private TimePicker timeEt;
you declare it as a TimePicker. If you want it to be a TimePicker then change it in your xml
`<TimePicker
android:id="#+id/timeEdit"
style="#style/StyleText"/> `
Also, you have multiple ids in your xml
android:id="#+id/codeText"
might want to change that
Second Edit
03-29 13:23:33.790: E/AndroidRuntime(20744): android.app.SuperNotCalledException: Activity {com.app.gamedemo/com.app.gamedemo.AddEditCountry} did not call through to super.onCreate()
This line in the logcat says it all. You didn't call super.onCreate(). Add the following line as the first line in your onCreate() method
super.onCreate(savedInstanceState);
When reading your logcat, look for where it says Fatal Exception. The next line should say what it is (Null Pointer Exception, Class Cast Exception, etc...) then look for the first line that references your package name and it will tell you where to start looking for the error. Ex. Main.java 57 tells you that whatever the fatal exception was occurs in your Main.java file at line 57. The problem may originally come from somewhere else but this is always a good place to start so you can narrow it down and post relevant code if you need help.

Categories