App Crash: FATAL EXCEPTION: main - android-studio

App Crash on button click. Here is the log.
Dealing specifically with trying to store a user into Parse.com as my backend. I have a java class called RegisterActivity with corresponding xml file, leading me to think it could be a null pointer exception, but I tested, and that doesnt seem to be the problem. Here are the 3 classes in which I believe are involved with the problem.
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.parse.ParseException;
import com.parse.ParseUser;
import com.parse.SignUpCallback;
public class RegisterActivity extends Activity {
protected EditText mUsername;
protected EditText mUserEmail;
protected EditText mUserPassword;
protected Button mRegisterButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
//initialize
mUsername = (EditText)findViewById(R.id.usernameRegisterEditText);
mUserEmail= (EditText)findViewById(R.id.emailRegisterEditText);
mUserPassword= (EditText)findViewById(R.id.passwordRegisterEditText);
mRegisterButton = (Button)findViewById(registerButton);
//listen to register button click
mRegisterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//get the username,password, and email, then convert to string
String username = mUsername.getText().toString().trim();
String email = mUserEmail.getText().toString().trim();
String password = mUserPassword.getText().toString().trim();
//store user and parse
ParseUser user = new ParseUser();
user.setUsername(username);
user.setPassword(email);
user.setEmail(password);
user.signUpInBackground(new SignUpCallback() {
#Override
public void done(ParseException e) {
if(e == null){
//user signed up successfully
Toast.makeText(RegisterActivity.this, "Welcome!", Toast.LENGTH_LONG).show();
//take user to homepage
}else{
//error signing up user
}
}
});
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_register, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Here is the corresponding activity_register.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.parse.inclassmode.RegisterActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:hint="username"
android:ems="10"
android:id="#+id/usernameRegisterEditText"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="142dp" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:hint="email"
android:ems="10"
android:id="#+id/emailRegisterEditText"
android:layout_below="#+id/usernameRegisterEditText"
android:layout_centerHorizontal="true" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:hint="password"
android:ems="10"
android:id="#+id/passwordRegisterEditText"
android:layout_below="#+id/emailRegisterEditText"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="sign up"
android:id="#+id/registerButton"
android:layout_marginTop="42dp"
android:layout_below="#+id/passwordRegisterEditText"
android:layout_alignParentStart="true" />
</RelativeLayout>
MainActivity.java class which includes my keys for Parse.com
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import com.parse.Parse;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Enable Local Datastore, ID's hidden
Parse.initialize(this, "id", "id");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
and finally my android manifest, which launches the register activity then takes the user to the home screen.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.parse.inclassmode" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".RegisterActivity"
android:label="#string/title_activity_register" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity"
android:label="InClassMode" >
</activity>
</application>
</manifest>

Figured it out!
For those of you who may come across this problem, create a new class that is not an activity, from there, initialize the Parse.

Related

Android Studio Recycler View have gaps between the rows. Help me fix

I followed this tutorial on youtube for my school project. The app is able to display selected images from gallery but the recycler view have gaps in every row. What do I code to fix this app? help. enter image description here
here's my activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:scrollbarStyle="insideInset"
android:scrollbars="vertical"
tools:context=".MainActivity">
<Button
android:id="#+id/pick"
android:layout_width="53dp"
android:layout_height="64dp"
android:layout_margin="12dp"
android:layout_weight="0"
android:backgroundTint="#FF5722"
android:text="+"
android:textSize="24sp"
app:cornerRadius="64dp" />
<TextView
android:id="#+id/totalPhotos"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0"
android:gravity="center"
android:textColor="#FFFFFF" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView_Gallery_Images"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_weight="1"
</LinearLayout>
RecyclerAdapter.java
package com.example.mygram;
import android.media.Image;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private ArrayList<Uri> uriArrayList;
public RecyclerAdapter(ArrayList<Uri> uriArrayList) {
this.uriArrayList = uriArrayList;
}
#NonNull
#Override
public RecyclerAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.custom_single_image,parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerAdapter.ViewHolder holder, int position) {
holder.imageView.setImageURI(uriArrayList.get(position));
}
#Override
public int getItemCount() {
return uriArrayList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView imageView;
public ViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.image);
}
}
}
Custom single images.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<ImageView
android:id="#+id/image"
android:layout_width="match_parent"
android:layout_height="0dp"
android:scaleType="centerCrop"
app:layout_constraintDimensionRatio="1"
tools:ignore="MissingConstraints" />
</androidx.constraintlayout.widget.ConstraintLayout>
And here's the MainActivity.java
package com.example.mygram;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
TextView textView;
Button pick;
ArrayList <Uri> uri = new ArrayList<>();
RecyclerAdapter adapter ;
private static final int Read_Permission = 101;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.totalPhotos);
recyclerView = findViewById(R.id.recyclerView_Gallery_Images);
pick = findViewById(R.id.pick);
adapter = new RecyclerAdapter(uri);
recyclerView.setLayoutManager(new GridLayoutManager(MainActivity.this,3));
recyclerView.setAdapter(adapter);
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, Read_Permission);
}
pick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2){
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
}
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), 1);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1 && resultCode == Activity.RESULT_OK){
if(data.getClipData() !=null) {
int x = data.getClipData().getItemCount();
for (int i = 0; i < x; i++) {
uri.add(data.getClipData().getItemAt(i).getUri());
}
adapter.notifyDataSetChanged();
textView.setText("Photos ("+uri.size()+")");
}else if (data.getData()!=null){
String imageURL=data.getData().getPath();
uri.add(Uri.parse(imageURL));
}
}
}
}
The concept of the app is instagram feed tester. I want to be able to display images like the grid in instagram but the gap is appearing preventing it to happen. help me please thankyou
In your Custom single images.xml replace the height of the parent layout to wrap_content. Replace your code with the following
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<ImageView
android:id="#+id/image"
android:layout_width="match_parent"
android:layout_height="0dp"
android:scaleType="centerCrop"
app:layout_constraintDimensionRatio="1"
tools:ignore="MissingConstraints" />
</androidx.constraintlayout.widget.ConstraintLayout>
Everything is right : Just need to Change this to this: (images.xml)
android:layout_height="match_parent"
to
android:layout_height="wrap_content"
in your model xml file

Display ImageButton on last slide of viewpager

I'm trying to have a button appear only on the last page of a ViewPager. I have the working button but it is displayed on all the pages instead of only the last page. I want to have it visible only on the last page. Here is my code.
activity_welcome2.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
tools:context=".Welcome_Activity"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.viewpager.widget.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!--- for dots -->
<View
android:id="#+id/view1"
android:layout_width="match_parent"
android:layout_height="1dp"
android:alpha=".5"
android:layout_above="#+id/dotsLayout"
android:background="#color/white"
android:layout_marginBottom="15dp" />
<LinearLayout
android:id="#+id/dotsLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
android:orientation="horizontal"
android:gravity="center"
android:layout_marginBottom="55sp" />
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageButton
android:id="#+id/next3"
android:layout_width="99dp"
android:layout_height="45dp"
android:background="#android:color/transparent"
android:scaleType="fitCenter"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.822"
app:srcCompat="#drawable/next" />
</androidx.constraintlayout.widget.ConstraintLayout>
</RelativeLayout>
Welcome_Activity.java
package com.group7.salitongue;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.viewpager.widget.ViewPager;
public class Welcome_Activity extends AppCompatActivity {
private ViewPager mPager;
private int[] layouts = { R.layout.activity_main, R.layout.activity_splashscreen2, R.layout.activity_welcome };
private MpagerAdapter mpagerAdapter;
private LinearLayout Dots_Layout;
private ImageView[] dots;
private ImageButton nextBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome2);
mPager = (ViewPager) findViewById(R.id.viewPager);
mpagerAdapter = new MpagerAdapter(layouts, this);
mPager.setAdapter(mpagerAdapter);
Dots_Layout = (LinearLayout) findViewById(R.id.dotsLayout);
createDots(0);
mPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
#Override
public void onPageSelected(int position) {
createDots(position);
}
#Override
public void onPageScrollStateChanged(int state) {}
});
// transition button to Signup page
nextBtn = (ImageButton) findViewById(R.id.next3);
nextBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Welcome_Activity.this,MainActivity.class);
startActivity(intent);
}
});
}
private void createDots(int current_position) {
if(Dots_Layout != null)
Dots_Layout.removeAllViews();
dots = new ImageView[layouts.length];
for (int i = 0; i < layouts.length; i++) {
dots[i] = new ImageView(this);
if (i == current_position) {
dots[i].setImageDrawable(ContextCompat.getDrawable(this, R.drawable.active_dots));
}
else {
dots[i].setImageDrawable(ContextCompat.getDrawable(this, R.drawable.default_dots));
}
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT
);
params.setMargins(4, 0, 4, 0);
Dots_Layout.addView(dots[i],params);
}
}
}
How can I display the button only when the user has reached the last page of swiping?
Just listen in the onPageSelected method of your OnPageChangeListener when the last page is reached and set the button to visible. In all other cases, just hide it.
#Override
public void onPageSelected(int position) {
createDots(position);
// only show the button when the last page is reached
if (position == mPagerAdapter.getCount() - 1)
nextBtn.setVisibility(View.VISIBLE);
else
nextBtn.setVisibility(View.GONE);
}

Android studio dialogFragment screen dims but doesn't show

I am making an app in android studio using java. I have made a dialogfragment for the setting option int the overflow menu. It was working just fine before but now when I click settings, the screen dims and nothing happens. I can click on the phone screen and the screen will undim and the app will continue working like normal and it throws no error in log cat. I set a log cat message after in inflater runs and it seems to be executing correctly. I hav no idea why it was working before but now it is not. Here is my code:
dialogFragment class:
package com.dicegame1;
import android.app.Dialog;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.Switch;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.DialogFragment;
public class SettingsMenu extends DialogFragment {
Switch doubles;
Switch triples;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View dialogView = inflater.inflate(R.layout.settings_menu,null);
doubles = dialogView.findViewById(R.id.switchDoublesBonus);
triples = dialogView.findViewById(R.id.switchTriplesBonus);
Button save = dialogView.findViewById(R.id.btnSave);
Button cancel = dialogView.findViewById(R.id.btnCancel);
Log.d("load", "dialog load");
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dismiss();
Log.d("dis", "dismiss");
}
});
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MainActivity callingActivity = (MainActivity) getActivity();
Dice player = callingActivity.sendPlayer();
player.setDoubles(doubles.isChecked());
player.setTriples(triples.isChecked());
Log.d("s", "save");
dismiss();
}
});
return builder.create();
}
}
here is calling methods in main activity:
#Override
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.overflow_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
int id = item.getItemId();
if (id == R.id.settings) {
SettingsMenu d = new SettingsMenu();
Log.d("1", "Dialog created");
d.show(getSupportFragmentManager(),"");
Log.d("2", "Show called");
return true;
}
return super.onOptionsItemSelected(item);
}
here is xml for settings menu:
<?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">
<Switch
android:id="#+id/switchDoublesBonus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minHeight="48dp"
android:text="Doubles"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.205"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.213"
/>
<Switch
android:id="#+id/switchTriplesBonus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="226dp"
android:minHeight="48dp"
android:text="Triples"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.201"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0"
/>
<Button
android:id="#+id/btnSave"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.124"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.876" />
<Button
android:id="#+id/btnCancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cancel"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.78"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.876" />
</androidx.constraintlayout.widget.ConstraintLayout>
I want to reiterate that things were working correctly before and I have reverted all changes made and its still not working. Any ideas??

My app is unble to start another activity after showing splash screen and it is showing this error

My app is unble to start another Activity after showing splash screen.
This is the error I get when running my app:
Exception:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.ref, PID: 7683
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ref/com.example.ref.LoginActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.appcompat.app.ActionBar.setTitle(java.lang.CharSequence)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.appcompat.app.ActionBar.setTitle(java.lang.CharSequence)' on a null object reference
at com.example.ref.LoginActivity.onCreate(LoginActivity.java:46)
at android.app.Activity.performCreate(Activity.java:8000)
at android.app.Activity.performCreate(Activity.java:7984)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:223) 
at android.app.ActivityThread.main(ActivityThread.java:7656) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947) 
I/Process: Sending signal. PID: 7683 SIG: 9
Disconnected from the target VM, address: 'localhost:49932', transport: 'socket'
SpalshScreen:
package com.example.ref;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.os.Handler;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class SpalshScreen extends AppCompatActivity {
FirebaseUser currentUser;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spalsh_screen2);
mAuth = FirebaseAuth.getInstance();
if (mAuth != null) {
currentUser = mAuth.getCurrentUser(); }
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
FirebaseUser user = mAuth.getCurrentUser();
if (user == null) {
Intent intent = new Intent(SpalshScreen.this, LoginActivity.class);
startActivity(intent);
finish();
} else {
Intent mainIntent = new Intent(SpalshScreen.this, DashboardActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
}
}
}, 1000);
}
}
LoginActivity:
package com.example.ref;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.InputType;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.HashMap;
import java.util.Objects;
public class LoginActivity extends AppCompatActivity {
private EditText email, password, name;
private Button mlogin;
private TextView newdnewaccount, reocverpass;
FirebaseUser currentUser;
private ProgressDialog loadingBar;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
ActionBar actionBar = getSupportActionBar();
actionBar.setTitle("Create Account");
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
// initialising the layout items
email = findViewById(R.id.login_email);
password = findViewById(R.id.login_password);
newdnewaccount = findViewById(R.id.needs_new_account);
reocverpass = findViewById(R.id.forgetp);
mAuth = FirebaseAuth.getInstance();
mlogin = findViewById(R.id.login_button);
loadingBar = new ProgressDialog(this);
mAuth = FirebaseAuth.getInstance();
// checking if user is null or not
if (mAuth != null) {
currentUser = mAuth.getCurrentUser();
}
mlogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String emaill = email.getText().toString().trim();
String pass = password.getText().toString().trim();
// if format of email doesn't matches return null
if (!Patterns.EMAIL_ADDRESS.matcher(emaill).matches()) {
email.setError("Invalid Email");
email.setFocusable(true);
} else {
loginUser(emaill, pass);
}
}
});
// If new account then move to Registration Activity
newdnewaccount.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, RegistrationActivity.class));
}
});
// Recover Your Password using email
reocverpass.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showRecoverPasswordDialog();
}
});
}
private void showRecoverPasswordDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Recover Password");
LinearLayout linearLayout = new LinearLayout(this);
final EditText emailet = new EditText(this);//write your registered email
emailet.setText("Email");
emailet.setMinEms(16);
emailet.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
linearLayout.addView(emailet);
linearLayout.setPadding(10, 10, 10, 10);
builder.setView(linearLayout);
builder.setPositiveButton("Recover", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String emaill = emailet.getText().toString().trim();
beginRecovery(emaill);//send a mail on the mail to recover password
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create().show();
}
private void beginRecovery(String emaill) {
loadingBar.setMessage("Sending Email....");
loadingBar.setCanceledOnTouchOutside(false);
loadingBar.show();
// send reset password email
mAuth.sendPasswordResetEmail(emaill).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
loadingBar.dismiss();
if (task.isSuccessful()) {
Toast.makeText(LoginActivity.this, "Done sent", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(LoginActivity.this, "Error Occured", Toast.LENGTH_LONG).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
loadingBar.dismiss();
Toast.makeText(LoginActivity.this, "Error Failed", Toast.LENGTH_LONG).show();
}
});
}
private void loginUser(String emaill, String pass) {
loadingBar.setMessage("Logging In....");
loadingBar.show();
// sign in with email and password after authenticating
mAuth.signInWithEmailAndPassword(emaill, pass).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
loadingBar.dismiss();
FirebaseUser user = mAuth.getCurrentUser();
if (task.getResult().getAdditionalUserInfo().isNewUser()) {
String email = user.getEmail();
String uid = user.getUid();
HashMap<Object, String> hashMap = new HashMap<>();
hashMap.put("email", email);
hashMap.put("uid", uid);
hashMap.put("name", "");
hashMap.put("onlineStatus", "online");
hashMap.put("typingTo", "noOne");
hashMap.put("phone", "");
hashMap.put("image", "");
hashMap.put("cover", "");
FirebaseDatabase database = FirebaseDatabase.getInstance();
// store the value in Database in "Users" Node
DatabaseReference reference = database.getReference("Users");
// storing the value in Firebase
reference.child(uid).setValue(hashMap);
}
Toast.makeText(LoginActivity.this, "Registered User " + user.getEmail(), Toast.LENGTH_LONG).show();
Intent mainIntent = new Intent(LoginActivity.this, DashboardActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
} else {
loadingBar.dismiss();
Toast.makeText(LoginActivity.this, "Login Failed", Toast.LENGTH_LONG).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
loadingBar.dismiss();
Toast.makeText(LoginActivity.this, "Error Occured", Toast.LENGTH_LONG).show();
}
});
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return super.onSupportNavigateUp();
}
}
<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Theme.Ref" parent="Theme.MaterialComponents.DayNight.NoActionBar">
<!-- Primary brand color. -->
<item name="colorPrimary">#color/purple_500</item>
<item name="colorPrimaryVariant">#color/purple_700</item>
<item name="colorOnPrimary">#color/white</item>
<!-- Secondary brand color. -->
<item name="colorSecondary">#color/teal_200</item>
<item name="colorSecondaryVariant">#color/teal_700</item>
<item name="colorOnSecondary">#color/black</item>
<!-- Status bar color. -->
<item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
<!-- Customize your theme here. -->
</style>
</resources>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".LoginActivity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/welcom"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="120dp"
android:layout_marginTop="50dp"
android:text="Welcome!"
android:textColor="#color/colorBlack"
android:textSize="30sp"
android:textStyle="italic|bold" />
<TextView
android:id="#+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/welcom"
android:layout_marginStart="35dp"
android:layout_marginTop="120dp"
android:text="Email"
android:textColor="#color/colorBlack" />
<EditText
android:id="#+id/login_email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/email"
android:layout_alignParentStart="true"
android:layout_marginLeft="30dp"
android:layout_marginTop="5dp"
android:layout_marginRight="30dp"
android:background="#drawable/edit"
android:drawableStart="#drawable/ic_email"
android:hint="Email..."
android:inputType="textEmailAddress"
android:padding="8dp" />
<TextView
android:id="#+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/login_email"
android:layout_marginStart="32dp"
android:layout_marginTop="20dp"
android:text="Password"
android:textColor="#color/colorBlack" />
<EditText
android:id="#+id/login_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/password"
android:layout_alignParentStart="true"
android:layout_marginLeft="30dp"
android:layout_marginTop="5dp"
android:layout_marginRight="30dp"
android:background="#drawable/edit"
android:drawableStart="#drawable/password"
android:hint="Password..."
android:inputType="textPassword"
android:padding="8dp" />
<TextView
android:id="#+id/forgetp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/login_password"
android:layout_marginStart="210dp"
android:layout_marginTop="15dp"
android:layout_marginEnd="23dp"
android:text="#string/forget_password"
android:textAlignment="center"
android:textColor="#color/colorPrimaryDark"
android:textSize="17sp"
android:textStyle="bold" />
<Button
android:id="#+id/login_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/forgetp"
android:layout_marginLeft="30dp"
android:layout_marginTop="15dp"
android:layout_marginRight="30dp"
android:background="#drawable/buttonss"
android:padding="4dp"
android:text="Login"
android:textAllCaps="false"
android:textColor="#android:color/background_light"
android:textSize="24sp" />
<TextView
android:id="#+id/needs_new_account"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/login_button"
android:layout_centerHorizontal="true"
android:layout_marginStart="15dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="23dp"
android:text="#string/need_new_account_sign_up_here"
android:textAlignment="center"
android:textColor="#color/colorPrimary"
android:textSize="17sp"
android:textStyle="bold" />
</RelativeLayout>
</ScrollView>
</LinearLayout>
See getting Null pointer exception while setting the title to action bar. Probably you missed something in styles.xml. Could you write it? There may be a problem in
<style name="AppTheme.NoActionBar">
<item name="android:windowActionBar">false</item>
Also, please, add a layout of LoginActivity. There should be Toolbar.
When the compiler start onCreate() in your second activity he can't find the reference to the object that you are trying to setTitle(), so basically your Toolbar or ActionBar doesn't have a reference to the Object in the View(xml).
Ex:
Toolbar toolbar = findViewById(R.id.name_of_the_object);
in this way toolbar gets the reference to the object in the view (activity.xml);
I think this line is wrong ActionBar actionBar = getSupportActionBar();
It should be ActionBar actionBar = activity.getSupportActionBar();

App Crashes whenever I click an Icon on Navigation bar

Just got many problems sorted out on my bottom navigation bar, but now the app crashes whenever I click on any of the 3 navigation bar Icons.
Error
2020-07-23 15:41:26.397 25876-25876/com.example.sociate11 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.sociate11, PID: 25876
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference
at androidx.fragment.app.FragmentTransaction.doAddOp(FragmentTransaction.java:245)
at androidx.fragment.app.BackStackRecord.doAddOp(BackStackRecord.java:180)
at androidx.fragment.app.FragmentTransaction.replace(FragmentTransaction.java:343)
at androidx.fragment.app.FragmentTransaction.replace(FragmentTransaction.java:293)
at com.example.sociate11.activityHome$2.onNavigationItemSelected(activityHome.java:67)
at com.google.android.material.bottomnavigation.BottomNavigationView$1.onMenuItemSelected(BottomNavigationView.java:243)
at androidx.appcompat.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:840)
at androidx.appcompat.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:158)
at androidx.appcompat.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:991)
at com.google.android.material.bottomnavigation.BottomNavigationMenuView$1.onClick(BottomNavigationMenuView.java:124)
at android.view.View.performClick(View.java:7357)
at android.view.View.performClickInternal(View.java:7334)
at android.view.View.access$3600(View.java:808)
at android.view.View$PerformClick.run(View.java:28200)
at android.os.Handler.handleCallback(Handler.java:907)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7478)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:549)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:941)
activityHome.java
package com.example.sociate11;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.firebase.auth.FirebaseAuth;
public class activityHome extends AppCompatActivity {
private FirebaseAuth firebaseAuth;
private Button logout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
firebaseAuth = FirebaseAuth.getInstance();
logout = (Button)findViewById(R.id.btnLogOut);
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
firebaseAuth.signOut();
finish();
startActivity(new Intent(activityHome.this, MainActivity.class));
}
});
BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation_bar);
bottomNav.setOnNavigationItemSelectedListener(navListener);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new HomeFragment()).commit();
}
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.home_fragment:
selectedFragment = new HomeFragment();
break;
case R.id.events_fragment:
selectedFragment = new EventFragment();
break;
case R.id.fragment_myconversation:
selectedFragment = new ConversationFragment();
break;
}
assert selectedFragment != null;
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
selectedFragment).commit();
return true;
}
};
}
ConversationsFragment.java (all 3 fragments are currently identical)
package com.example.sociate11;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class ConversationFragment extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_myconversations,container,false);
}
}
bottom_navigation.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/menu_home"
android:title="Home"
android:icon="#drawable/ic_home"
app:showAsAction="always"/>
<item
android:id="#+id/menu_myEvents"
android:title="My Events"
android:icon="#drawable/ic_event"
app:showAsAction="always"/>
<item
android:id="#+id/menu_myConversations"
android:title="My Conversations"
android:icon="#drawable/ic_conversations"
app:showAsAction="always"/>
</menu>
activity_home.xml
<?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=".activityHome"
android:background="#color/colorPrimary">
<Button
android:id="#+id/btnLogOut"
android:layout_width="115dp"
android:layout_height="75dp"
android:text="log out"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/bottom_navigation_bar" />
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottom_navigation_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?android:attr/windowBackground"
app:itemTextColor="#color/colorPrimaryDark"
app:itemIconTint="#color/colorPrimaryDark"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/btnLogOut"
app:layout_constraintVertical_bias="1.0"
app:menu="#menu/bottom_navigation" />
</androidx.constraintlayout.widget.ConstraintLayout>
Thank you for the help as always, and please let me know if I didn't provide enough info!

Resources