Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 2 years ago.
Improve this question
I am new to Android Application Development and while working on a project. I receive the following error and I can't seem to figure out the solution and it makes my application crash.
I have a application which is conneting to firebase and registering user and saving its details to the database. But when I am opening the register user activity the app crashed and hence doesn't proceed further. Please help as I am quite new to android app development.
The logcat is here
2020-05-27 01:08:00.427 25788-25788/com.example.auth E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.auth, PID: 25788
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.auth/com.example.auth.RegisterActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ProgressBar.setVisibility(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ProgressBar.setVisibility(int)' on a null object reference
at com.example.auth.RegisterActivity.onCreate(RegisterActivity.java:35)
at android.app.Activity.performCreate(Activity.java:7136)
at android.app.Activity.performCreate(Activity.java:7127)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
2020-05-27 01:08:00.452 25788-25788/com.example.auth I/Process: Sending signal. PID: 25788 SIG: 9
Here is the RegisterActivity.java
package com.example.auth;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Patterns;
import android.view.View;
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 editTextName, editTextEmail, editTextPassword, editTextPhone;
private ProgressBar progressBar;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextName = findViewById(R.id.edit_text_name);
editTextEmail = findViewById(R.id.edit_text_email);
editTextPassword = findViewById(R.id.edit_text_password);
editTextPhone = findViewById(R.id.edit_text_phone);
progressBar = (ProgressBar) findViewById(R.id.progressbar);
**progressBar.setVisibility(View.GONE);**
mAuth = FirebaseAuth.getInstance();
findViewById(R.id.button_register).setOnClickListener(this);
}
#Override
protected void onStart() {
super.onStart();
if (mAuth.getCurrentUser() != null) {
//handle the already login user
}
}
private void registerUser() {
final String name = editTextName.getText().toString().trim();
final String email = editTextEmail.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();
final String phone = editTextPhone.getText().toString().trim();
if (name.isEmpty()) {
editTextName.setError(getString(R.string.input_error_name));
editTextName.requestFocus();
return;
}
if (email.isEmpty()) {
editTextEmail.setError(getString(R.string.input_error_email));
editTextEmail.requestFocus();
return;
}
if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
editTextEmail.setError(getString(R.string.input_error_email_invalid));
editTextEmail.requestFocus();
return;
}
if (password.isEmpty()) {
editTextPassword.setError(getString(R.string.input_error_password));
editTextPassword.requestFocus();
return;
}
if (password.length() < 6) {
editTextPassword.setError(getString(R.string.input_error_password_length));
editTextPassword.requestFocus();
return;
}
if (phone.isEmpty()) {
editTextPhone.setError(getString(R.string.input_error_phone));
editTextPhone.requestFocus();
return;
}
if (phone.length() != 10) {
editTextPhone.setError(getString(R.string.input_error_phone_invalid));
editTextPhone.requestFocus();
return;
}
progressBar.setVisibility(View.VISIBLE);
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
User user = new User(
name,
email,
phone
);
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);
if (task.isSuccessful()) {
Toast.makeText(RegisterActivity.this, getString(R.string.registration_success), Toast.LENGTH_LONG).show();
} else {
//display a failure message
}
}
});
} else {
Toast.makeText(RegisterActivity.this, task.getException().getMessage(), Toast.LENGTH_LONG).show();
}
}
});
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_register:
registerUser();
break;
}
}
}
Here is activity_register.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"
tools:context="com.example.auth.RegisterActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:orientation="vertical"
android:padding="#dimen/default_padding">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="cursive"
android:text="#string/app_name"
android:textAlignment="center"
android:textColor="#color/colorText"
android:textSize="#dimen/app_name_size" />
<EditText
android:id="#+id/edit_text_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:drawableLeft="#drawable/ic_name"
android:drawablePadding="#dimen/drawable_padding"
android:hint="#string/full_name"
android:nextFocusDown="#id/edit_text_email"
android:textColor="#color/colorText"
android:textColorHint="#color/colorHint" />
<EditText
android:id="#+id/edit_text_email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:drawableLeft="#drawable/ic_email"
android:drawablePadding="#dimen/drawable_padding"
android:hint="#string/email"
android:inputType="textEmailAddress"
android:nextFocusDown="#id/edit_text_password"
android:textColor="#color/colorText"
android:textColorHint="#color/colorHint" />
<EditText
android:id="#+id/edit_text_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:drawableLeft="#drawable/ic_password"
android:drawablePadding="#dimen/drawable_padding"
android:hint="#string/password"
android:inputType="textPassword"
android:nextFocusDown="#id/edit_text_phone"
android:textColor="#color/colorText"
android:textColorHint="#color/colorHint" />
<EditText
android:id="#+id/edit_text_phone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:digits="0123456789"
android:drawableLeft="#drawable/ic_phone"
android:drawablePadding="#dimen/drawable_padding"
android:hint="#string/phone"
android:inputType="number"
android:maxLength="10"
android:nextFocusDown="#id/button_register"
android:textColor="#color/colorText"
android:textColorHint="#color/colorHint" />
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:checkedButton="#id/radioButton1"
android:orientation="horizontal">
<RadioButton
android:id="#+id/radioButton1"
android:layout_width="118dp"
android:layout_height="wrap_content"
android:text="Student" />
<RadioButton
android:id="#+id/radioButton2"
android:layout_width="135dp"
android:layout_height="wrap_content"
android:text="Institute" />
<RadioButton
android:id="#+id/radioButton3"
android:layout_width="267dp"
android:layout_height="wrap_content"
android:text="Teacher" />
</RadioGroup>
<Button
android:id="#+id/button_register"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/bg_button_register"
android:text="#string/register"
android:textAllCaps="false"
android:textColor="#color/colorText" />
</LinearLayout>
<ProgressBar
android:id="#+id/progressbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" />
</RelativeLayout>
This is a typo:
setContentView(R.layout.activity_main);
but your layout is actually activity_register, not activity_main.
You probably meant:
setContentView(R.layout.activity_register);
The error message:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ProgressBar.setVisibility(int)' on a null object reference
Is telling you that progressBar is null. You can't call methods on a null object. It's null because findViewById couldn't find a view with the given ID. You will have to examine your inflated. layout to figure out why that is.
Seems like you are setting the wrong layout in:
setContentView(R.layout.activity_main);
But you posted activity_register.xml
You should do something like:
setContentView(R.layout.activity_register);
If you try to invoke any method on any of your editTexts, you should get an NPE there as well.
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
I made an app which has 1 Activity and 2 Classes, 1 Main and 1 for my Database.
But whenever i run my app on my virtual phone it stops
it says its prolly the Activity thingy, but i dont know much about it i m very begginer to android
thnx in advance,
this is wat i get in Log Cat
Process: com.example.test101, PID: 7666
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.test101/com.example.test101.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2843)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:159)
at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:157)
at android.content.Context.obtainStyledAttributes(Context.java:675)
at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:692)
at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:659)
at androidx.appcompat.app.AppCompatDelegateImpl.findViewById(AppCompatDelegateImpl.java:479)
at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:214)
at com.example.test101.MainActivity.<init>(MainActivity.java:20)
at java.lang.Class.newInstance(Native Method)
at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:69)
at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:45)
at android.app.Instrumentation.newActivity(Instrumentation.java:1215)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2831)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
2020-10-17 21:57:56.379 7666-7666/? I/Process: Sending signal. PID: 7666 SIG: 9
my code is
MAIN
package com.example.test101;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.google.android.material.snackbar.Snackbar;
public class MainActivity extends AppCompatActivity {
ConstraintLayout constraintLayout;
DBCreate db;
Button button = (Button) findViewById(R.id.button_reg);
EditText user = (EditText) findViewById(R.id.editTextTextPersonName);
EditText pass = (EditText) findViewById(R.id.editTextTextPassword);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new DBCreate(this);
regUser();
}
public void regUser(){
button.setOnKeyListener(
new View.OnKeyListener() {
#Override
public boolean onKey(View view, int i, KeyEvent keyEvent) {
boolean isInserted = db.insertData(user.getText().toString() ,pass.getText().toString());
if(isInserted){
Snackbar datI = Snackbar.make(constraintLayout, "Registered", Snackbar.LENGTH_SHORT);
datI.show();
}
return true;
}
}
);
}
public void onReg(View view){
if(user.getText().toString() == ""){
Snackbar snackbar1 = Snackbar.make(constraintLayout, "Please enter a valid username", Snackbar.LENGTH_SHORT);
snackbar1.show();
}
if(pass.getText().toString() == ""){
Snackbar snackbar1 = Snackbar.make(constraintLayout, "Please enter a valid password", Snackbar.LENGTH_SHORT);
snackbar1.show();
}
if(user.getText().toString() == "ADMIN"){
Snackbar snackbar1 = Snackbar.make(constraintLayout, "AAO PADHARO ADMIN SAAB", Snackbar.LENGTH_SHORT);
snackbar1.show();
if(!(pass.getText().toString() == "ADMIN")){
Snackbar snackbar2 = Snackbar.make(constraintLayout, "ADMIN SAAB PASSWORD TOH THIK DALO", Snackbar.LENGTH_SHORT);
snackbar2.show();
}
}
}
}
and 2nd
package com.example.test101;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBCreate extends SQLiteOpenHelper {
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "testoneoone.db";
public static final String TABLE_NAME = "up";
public static final String ID = "ID";
public static final String NAME = "NAME";
public static final String PASS = "PASS";
public DBCreate(Context context){
super(context,DATABASE_NAME,null,1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + "(ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, PASS TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean insertData( String name, String pass){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(NAME, name);
contentValues.put(PASS, pass);
long res = db.insert(TABLE_NAME, null,contentValues);
return res != -1;
}
}
my activity
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".MainActivity">
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginBottom="476dp"
android:text="Password"
android:textSize="36sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="96dp"
android:text="Username"
android:textSize="36sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="#+id/editTextTextPassword"
android:layout_width="306dp"
android:layout_height="45dp"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:ems="10"
android:inputType="textPassword"
app:layout_constraintBottom_toTopOf="#+id/button_reg"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView2"
app:layout_constraintVertical_bias="0.0" />
<EditText
android:id="#+id/editTextTextPersonName"
android:layout_width="306dp"
android:layout_height="45dp"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginBottom="16dp"
android:ems="10"
android:inputType="textPersonName"
app:layout_constraintBottom_toTopOf="#+id/textView2"
app:layout_constraintStart_toStartOf="parent" />
<Button
android:id="#+id/button_reg"
android:layout_width="174dp"
android:layout_height="0dp"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:layout_marginBottom="4dp"
android:onClick="onReg"
android:text="REGISTER"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView3" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="549dp"
android:layout_marginBottom="114dp"
android:text="Already have an account?"
app:layout_constraintBottom_toTopOf="#+id/button_reg"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
You should not assign views references immediately, as the layout for the activity is not inflated at the moment. Defer it till onCreate method.
So,
public class MainActivity extends AppCompatActivity {
ConstraintLayout constraintLayout;
DBCreate db;
Button button;
EditText user;
EditText pass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button_reg);
user = (EditText) findViewById(R.id.editTextTextPersonName);
pass = (EditText) findViewById(R.id.editTextTextPassword);
db = new DBCreate(this);
regUser();
}
// ... and so on
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I want to pass the value of the selected spinner item. In my activity there are 2 pairs of spinner and in every pair the second spinner is dependent on the value of the first spinner. As i need to pass the value to another activity, i took the values in different string variables and pass them to another activity. But the activity is maybe showing nullpointer execption in the Spinner.getSelectedItem().toString() method.
activityClass
package com.example.bohon_final__001;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
import java.util.List;
public class SqlitemainActivity extends AppCompatActivity {
Spinner pickupspinner1,pickupspinner2,destspinner1,destspinner2;
Button selectbtn;
EditText inputLabel;
String pickdistrict,pickarea,destdistrict,destarea,vehicletype;
ArrayList<String>disarray;
ArrayAdapter<String>disarray_adapter;
ArrayList<String>sylhet,moulovibazar,sunamgonj,habiganj;
ArrayAdapter<String>area;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sqlitemain);
pickupspinner1 = (Spinner)findViewById(R.id.pickupspinner1);
pickupspinner2 = (Spinner)findViewById(R.id.pickupspinner2);
destspinner1=(Spinner)findViewById(R.id.destinationspinner1);
destspinner2=(Spinner)findViewById(R.id.destinationspinner2);
selectbtn=findViewById(R.id.selectbutton);
String vehicletype=getIntent().getStringExtra("vehicleType");
disarray=new ArrayList<>();
disarray.add("Sylhet");
disarray.add("Sunamgonj");
disarray.add("Moulovibazar");
disarray.add("Habiganj");
disarray_adapter=new ArrayAdapter<>(getApplicationContext(),android.R.layout.simple_spinner_item,disarray);
pickupspinner1.setAdapter(disarray_adapter);
destspinner1.setAdapter(disarray_adapter);
sylhet=new ArrayList<>();
sylhet.add("Sylhet Sadar");
sylhet.add("Dakshin Surma");
sylhet.add("Moglabazar");
sylhet.add("Kanaighat");
sylhet.add("Bishwanath");
sunamgonj=new ArrayList<>();
sunamgonj.add("Sunamganj Sadar");
sunamgonj.add("Chhatak");
sunamgonj.add("Jagannathpur");
sunamgonj.add("Jamalganj");
sunamgonj.add("Derai");
moulovibazar=new ArrayList<>();
moulovibazar.add("Barlekha");
moulovibazar.add("Kulawra");
moulovibazar.add("Moulovibazar Sadar");
moulovibazar.add("Rajnagar");
moulovibazar.add("Sreemongol");
habiganj=new ArrayList<>();
habiganj.add("Ajmiriganj");
habiganj.add("Baniachang");
habiganj.add("Bahubal");
habiganj.add("Chunarughat");
habiganj.add("Habiganj Sadar");
pickupspinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if(i==0)
{
area=new ArrayAdapter<>(getApplicationContext(),android.R.layout.simple_spinner_item,sylhet);
}
if(i==1)
{
area=new ArrayAdapter<>(getApplicationContext(),android.R.layout.simple_spinner_item,sunamgonj);
}
if(i==2)
{
area=new ArrayAdapter<>(getApplicationContext(),android.R.layout.simple_spinner_item,moulovibazar);
}
else
{
area=new ArrayAdapter<>(getApplicationContext(),android.R.layout.simple_spinner_item,habiganj);
}
pickupspinner2.setAdapter(area);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
destspinner1.setOnItemSelectedListener(
new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if(i==0)
{
area=new ArrayAdapter<>(getApplicationContext(),android.R.layout.simple_spinner_item,sylhet);
}
if(i==1)
{
area=new ArrayAdapter<>(getApplicationContext(),android.R.layout.simple_spinner_item,sunamgonj);
}
if(i==2)
{
area=new ArrayAdapter<>(getApplicationContext(),android.R.layout.simple_spinner_item,moulovibazar);
}
if(i==3)
{
area=new ArrayAdapter<>(getApplicationContext(),android.R.layout.simple_spinner_item,habiganj);
}
destspinner2.setAdapter(area);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
pickdistrict=pickupspinner1.getSelectedItem().toString();
pickarea=String.valueOf(pickupspinner2.getSelectedItem());
destdistrict=destspinner1.getSelectedItem().toString();
destarea=destspinner2.getSelectedItem().toString();
selectbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent submissionintent=new Intent(SqlitemainActivity.this,FinalRequestActivity.class);
submissionintent.putExtra("pickd",pickdistrict);
submissionintent.putExtra("picka",pickarea);
submissionintent.putExtra("desd",destdistrict);
submissionintent.putExtra("desa",destarea);
submissionintent.putExtra("vtype",vehicletype);
startActivity(submissionintent);
}
});
}
}
Activity Class 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"
tools:context=".SqlitemainActivity"
android:orientation="vertical"
android:background="#000000"
>
<TextView
android:layout_width="230dp"
android:layout_height="wrap_content"
android:text="Select Your District:"
android:layout_marginStart="0dp"
android:layout_marginLeft="0dp"
android:layout_marginTop="50dp"
android:textStyle="italic"
android:textColor="#F44336"
android:textSize="15sp"
/>
<TextView
android:layout_width="171dp"
android:layout_height="wrap_content"
android:text="Area:"
android:layout_marginStart="0dp"
android:layout_marginLeft="0dp"
android:layout_marginTop="120dp"
android:textStyle="italic"
android:textColor="#F44336"
android:textSize="15sp"
/>
<TextView
android:id="#+id/pickuplocationtext"
android:layout_width="355dp"
android:layout_height="wrap_content"
android:layout_marginVertical="20dp"
android:text="Select your Pickup Location"
android:textColor="#color/yellow"
android:textSize="20sp"
android:textStyle="bold" />
<Spinner
android:id="#+id/pickupspinner1"
android:layout_width="253dp"
android:layout_height="37dp"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_marginStart="0dp"
android:layout_marginLeft="0dp"
android:layout_marginTop="70dp"
android:background="#FF8100" />
<Spinner
android:id="#+id/pickupspinner2"
android:layout_width="203dp"
android:layout_height="30dp"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_marginStart="0dp"
android:layout_marginLeft="0dp"
android:layout_marginTop="150dp"
android:background="#FF8100" />
<Button
android:id="#+id/selectbutton"
android:layout_width="214dp"
android:layout_height="63dp"
android:layout_marginLeft="90dp"
android:layout_marginTop="600dp"
android:background="#drawable/selectart"
android:text="" />
<TextView
android:id="#+id/destlocationtext"
android:layout_width="355dp"
android:layout_height="wrap_content"
android:layout_marginVertical="230dp"
android:text="Select your Destination Location"
android:textColor="#color/yellow"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:layout_width="230dp"
android:layout_height="wrap_content"
android:text="Select Your District:"
android:layout_marginStart="0dp"
android:layout_marginLeft="0dp"
android:layout_marginTop="260dp"
android:textStyle="italic"
android:textColor="#F44336"
android:textSize="15sp"
/>
<TextView
android:layout_width="171dp"
android:layout_height="wrap_content"
android:text="Area:"
android:layout_marginStart="0dp"
android:layout_marginLeft="0dp"
android:layout_marginTop="320dp"
android:textStyle="italic"
android:textColor="#F44336"
android:textSize="15sp"
/>
<Spinner
android:id="#+id/destinationspinner1"
android:layout_width="251dp"
android:layout_height="37dp"
android:layout_marginStart="0dp"
android:background="#FF8100"
android:layout_marginLeft="0dp"
android:layout_marginTop="280dp" />
<Spinner
android:id="#+id/destinationspinner2"
android:layout_width="199dp"
android:layout_height="31dp"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_marginStart="0dp"
android:layout_marginLeft="0dp"
android:layout_marginTop="350dp"
android:background="#FF8100" />
</RelativeLayout>
Here are the errors I'm getting
Process: com.example.bohon_final__001, PID: 1417
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.bohon_final__001/com.example.bohon_final__001.SqlitemainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2952)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3087)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1817)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6746)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
at com.example.bohon_final__001.SqlitemainActivity.onCreate(SqlitemainActivity.java:181)
at android.app.Activity.performCreate(Activity.java:7144)
at android.app.Activity.performCreate(Activity.java:7135)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1272)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2932)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3087)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1817)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6746)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
You got NullPointerException or NPE, this is the most common exception you'll face that you must be aware of, from here you find fruitful answers and explanation about it
In your particular case, your NPE exception is due to calling toString() method on a null object, and this is not allowed to access fields and methods of an object that is is not instantiated.
Process: com.example.bohon_final__001, PID: 1417
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.bohon_final__001/com.example.bohon_final__001.SqlitemainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
Looking into your code, you call toString() for the selected item of the spinner before an item is selected, and this is the cause of the NPE
pickdistrict=pickupspinner1.getSelectedItem().toString();
pickarea=String.valueOf(pickupspinner2.getSelectedItem());
destdistrict=destspinner1.getSelectedItem().toString();
destarea=destspinner2.getSelectedItem().toString();
so you can solve this either by:
Setting a default item before calling toString(), and this can be done by
pickupspinner1.setSelection(my_default_item); // replace my_default_item with one of your spinner items
// Then you can call toString() afterwards
destdistrict = String.valueOf(pickupspinner2.getSelectedItem());
or by calling toString() whenever the user selects a spinner item so are are certain that there is an item is selected; to do so implement the onItemSelected() callback of setOnItemSelectedListener of your spinner
pickupspinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selection = (String) parent.getItemAtPosition(position);
destdistrict = String.valueOf(selection);
}
}
Yeah i fixed the error. The only problem was assigning the values of the string should be inside the onCLick Button listener method instead of inside the Oncreate method.
selectbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pickdistrict=pickupspinner1.getSelectedItem().toString();
pickarea=String.valueOf(pickupspinner2.getSelectedItem());
destdistrict=destspinner1.getSelectedItem().toString();
destarea=destspinner2.getSelectedItem().toString();
Intent submissionintent=new Intent(SqlitemainActivity.this,FinalRequestActivity.class);
submissionintent.putExtra("pickd",pickdistrict);
submissionintent.putExtra("picka",pickarea);
submissionintent.putExtra("desd",destdistrict);
submissionintent.putExtra("desa",destarea);
submissionintent.putExtra("vtype",vehicletype);
startActivity(submissionintent);
}
});
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);
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
$ error in androidmonitor
02-02 14:22:48.870 3269-3269/com.example.applincatio.t E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.applincatio.t, PID: 3269
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.applincatio.t/com.example.applincatio.t.moddle}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.webkit.WebView.setWebChromeClient(android.webkit.WebChromeClient)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
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:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.webkit.WebView.setWebChromeClient(android.webkit.WebChromeClient)' on a null object reference
at com.example.applincatio.t.moddle.onCreate(moddle.java:20)
at android.app.Activity.performCreate(Activity.java:6664)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
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:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
$main activity.java
package com.example.applincatio.t;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import static com.example.applincatio.t.R.*;
import static com.example.applincatio.t.R.id.moddle1;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
ImageView moddle;
ImageButton outlook;
ImageButton contactus;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(layout.activity_main);
moddle = (ImageView) findViewById(moddle1);
ImageView moddle = (ImageView) findViewById(moddle1);
moddle.setOnClickListener(this);
}
public void onClick(View view) {
switch (view.getId()) {
case moddle1:
Intent imprintIntent = new Intent(MainActivity.this, moddle.class);
imprintIntent.putExtra("webivew", moddle1);
this.startActivity(imprintIntent);
break;
case id.outlook:
Intent contactIntent = new Intent(MainActivity.this, moddle.class);
// contactIntent.putExtra("webivewContact", outlook);
this.startActivity(contactIntent);
break;
case id.contactus:
Intent aboutIntent = new Intent(MainActivity.this, moddle.class);
//aboutIntent.putExtra("webivewAbout", contactus);
this.startActivity(aboutIntent);
break;
}
}
}
$moddle.java
package com.example.applincatio.t;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
public class moddle extends AppCompatActivity {
String url;
WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.web_link);
webView.clearCache(true);
webView.clearHistory();
webView.getSettings().setJavaScriptEnabled(true);
Intent intent = this.getIntent();
if (intent != null) {
Bundle data = getIntent().getExtras();
if (data.containsKey("webivew")) { //i have changed this param to match the intent passed
url = data.getString("webivew");
}
if (data.containsKey("webivewContact")) {
url = data.getString("webivewContact");
}
if (data.containsKey("webivewAbout")) {
url = data.getString("webivewAbout");
}
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView wView, int progress) {
// webViewActivity.setTitle("Loading...");
// webViewActivity.requestWindowFeature(progress * 100);
if(progress == 100) {
// webViewActivity.setTitle(R.string.app_name);
}
}
});
webView.loadUrl(url);
}
}
}
$activitymain.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:id="#+id/activity_main"
android:layout_width="match_parent"
android:background="#drawable/p"
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="com.example.applincatio.t.MainActivity"
android:weightSum="1">
<GridLayout
android:layout_width="match_parent"
android:rowCount="4"
android:columnCount="2"
android:layout_height="530dp"
android:alignmentMode="alignMargins"
android:columnOrderPreserved="false"
android:id="#+id/gridview"
android:padding="14dp">
<LinearLayout
android:layout_gravity="center_horizontal|center_vertical"
android:layout_margin="16dp"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:id="#+id/moddle1"
android:src="#drawable/moddle"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="MODDLE"
android:textColor="#fff"
android:textStyle="bold"
android:textAppearance="#style/TextAppearance.AppCompat.Headline" />
</LinearLayout>
<LinearLayout
android:layout_gravity="center_horizontal|center_vertical"
android:layout_margin="16dp"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageButton
android:layout_width="96dp"
android:layout_height="139dp"
android:id="#+id/outlook"
android:layout_gravity="center"
android:src="#drawable/ou"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="OUTLOOK"
android:gravity="bottom"
android:textAlignment="center"
android:textColor="#ffffff"
android:textStyle="bold"
android:textAppearance="#style/TextAppearance.AppCompat.Headline" />
</LinearLayout>
<LinearLayout
android:layout_gravity="center_horizontal|center_vertical"
android:layout_margin="16dp"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageButton
android:layout_width="122dp"
android:layout_height="141dp"
android:layout_gravity="center"
android:id="#+id/contactus"
android:src="#drawable/cont"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CONTACT US"
android:textSize="20dp"
android:textColor="#ffff"
android:textStyle="bold"
android:textAppearance="#style/TextAppearance.AppCompat.Headline" />
</LinearLayout>
<LinearLayout
android:layout_gravity="center_horizontal|center_vertical"
android:layout_margin="16dp"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageButton
android:layout_width="123dp"
android:layout_height="128dp"
android:onClick="onClick"
android:layout_gravity="center"
android:src="#drawable/vi"
android:id="#+id/visitus" />
<TextView
android:layout_width="wrap_content"
android:layout_height="48dp"
android:text="VISIT US"
android:gravity="bottom"
android:textAlignment="center"
android:textColor="#ffffff"
android:textStyle="bold"
android:textAppearance="#style/TextAppearance.AppCompat.Headline" />
</LinearLayout>
</GridLayout>
</LinearLayout>
when i run the app. it is running but when i click on any imagebutton the app keeps stopping. i cant understand the mistake i did .in image you can see my layout its running but imagebuttons are not working
please any one help me
thanks in advance
Try the below one,
package com.example.applincatio.t;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
public class moddle extends AppCompatActivity {
String url;
WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.web_link);
webView.clearCache(true);
webView.clearHistory();
webView.getSettings().setJavaScriptEnabled(true);
Intent intent = this.getIntent();
if (intent != null) {
Bundle data = getIntent().getExtras();
if (data.containsKey("webview")) {
url = data.getString("webview");
}
if (data.containsKey("webivewContact")) {
url = data.getString("webivewContact");
}
if (data.containsKey("webivewAbout")) {
url = data.getString("webivewAbout");
}
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView wView, int progress) {
// webViewActivity.setTitle("Loading...");
// webViewActivity.requestWindowFeature(progress * 100);
if(progress == 100) {
// webViewActivity.setTitle(R.string.app_name);
}
}
});
url = "https://moodle.kluniversity.in/login/index.php";
webView.loadUrl(url);
}
}
}
Thanks!
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