This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am implementing the captcha code in my form but I am getting a null pointer exception the method getImage().
I have two captcha codes in the project one is working fine but the other one is showing the following error. I don't know why it is not taking the captcha as a parameter.
I am providing the logcat and the mainactivity.java below.
Logcat
FATAL EXCEPTION: main
Process: com.mws.tms_application, PID: 6983
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mws.tms_application/com.mws.tms_application.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.Bitmap com.mws.tms_application.TextCaptcha.getImage()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6540)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.Bitmap com.mws.tms_application.TextCaptcha.getImage()' on a null object reference
at com.mws.tms_application.MainActivity.onCreate(MainActivity.java:41)
at android.app.Activity.performCreate(Activity.java:6980)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6540)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
main activity.java
package com.mws.tms_application;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView Registerlink;
Button Submit_btn ,Reset_btn,Link_btn;
EditText Username,Usermob,UserAddress,Usermailid,Userpass,Usercapt;
ActionBar actionBar;
ImageView imageView1;
TextCaptcha textCaptcha1;
//#2eb82e
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = getIntent();
Registerlink = (TextView) findViewById(R.id.loginlink);
Submit_btn=(Button)findViewById(R.id.Submit_btn);
Reset_btn=(Button)findViewById(R.id.Main_Reset_btn);
Username=(EditText)findViewById(R.id.username_edtext);
Usermob=(EditText)findViewById(R.id.usermob_no_edtext);
UserAddress=(EditText)findViewById(R.id.userAddresss_edtext);
Usermailid=(EditText)findViewById(R.id.usermailid_edtext);
Userpass=(EditText)findViewById(R.id.userpass_edtext);
Usercapt=(EditText)findViewById(R.id.usercapt_edtext);
Link_btn=(Button)findViewById(R.id.Link_btn);
imageView1=(ImageView)findViewById(R.id.register_capt_imageview);
imageView1.setImageBitmap(textCaptcha1.getImage());
actionBar=getSupportActionBar();
actionBar.show();
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#2eb82e")));
MainLogic();
}
private void MainLogic()
{ Link_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(MainActivity.this,Home_Navigation_Activity.class);
startActivity(i);
}
});
Submit_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isValidData();
}
});
Reset_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
claredata();
}
});
Registerlink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(MainActivity.this,Login_Activity.class);
startActivity(i);
}
});
}
/* Userid,Username,usermob,userAddress,usermailid,userpass,usercapt;*/
public boolean isValidData()
{
String id,name,mobile,address,email,password,captch;
name=Username.getText().toString();
mobile=Usermob.getText().toString();
address=UserAddress.getText().toString();
email=Usermailid.getText().toString();
password=Userpass.getText().toString();
/*captch=Usercapt.getText().toString();*/
if (!name.equals("")&&!mobile.equals("")&&mobile.length()>=10&&mobile.length()<=13&&!address.equals("")&&!email.equals("")&&!password.equals(""))
{
if (validEmail((email)))
{
return true;
}
else
{
AlertDialog.Builder alt=new AlertDialog.Builder(MainActivity.this);
alt.setMessage("Invalid Email_Id");
alt.setCancelable(true);
alt.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alertDialog=alt.create();
alertDialog.show();
return false;
}
}
else
{
AlertDialog.Builder alt=new AlertDialog.Builder(MainActivity.this);
alt.setMessage("Please fill all details");
alt.setCancelable(true);
alt.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alertDialog=alt.create();
alertDialog.show();
}
return false;
}
public boolean claredata()
{
Username.setText("");
Usermob.setText("");
UserAddress.setText("");
Usermailid.setText("");
Userpass.setText("");
/*captch=Usercapt.getText().toString();*/
return false;
}
private boolean validEmail(String email) {
final String emailPattern = "[a-zA-Z0-9._-]+#[a-z]+\\.+[a-z]+";
if (email.trim().matches(emailPattern))
{
return true;
}
return false;
}
}
It is coming from
imageView1.setImageBitmap(textCaptcha1.getImage());
you are using textCaptcha1 but you have not initialized it anywhere
Related
Hi Please help me to resolve this issue I m getting this error
message. The app crashes I have tried almost every solution suggested
on Google
I am creating a Notes application for Android and the logic of the app when it starts is to check if there is a user created and logged in or not. if there is a user created then start MainActivity
if there is no user created login with Anonymous account
package com.russrezepov.mynotes;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.russrezepov.mynotes.auth.Login;
public class Splash extends AppCompatActivity {
private FirebaseAuth fAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
fAuth = FirebaseAuth.getInstance();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
if (fAuth.getCurrentUser() != null) {
startActivity(new Intent(getApplicationContext(), MainActivity.class));
finish();
} else {
//create a new Anonymous account if a User is not logged in or does not have an account
fAuth.signInAnonymously().addOnSuccessListener(new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
Toast.makeText(Splash.this, "Logged in with Temp Account", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(),MainActivity.class));
finish();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Splash.this, "Error" + e.getMessage(), Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(), Login.class));
finish();
}
});
}
}
}, 1000);
}
}
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.russrezepov.mynotes, PID: 5158
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.russrezepov.mynotes/com.russrezepov.mynotes.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean com.google.firebase.auth.FirebaseUser.isAnonymous()' 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 'boolean com.google.firebase.auth.FirebaseUser.isAnonymous()' on a null object reference
at com.russrezepov.mynotes.MainActivity.onCreate(MainActivity.java:97)
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: 5158 SIG: 9
Disconnected from the target VM, address: 'localhost:54989', transport: 'socket'
The Error message shows that if (user.isAnonymous()) is where the code below is stops
package com.russrezepov.mynotes;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.cardview.widget.CardView;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.firestore.FirestoreRecyclerAdapter;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.navigation.NavigationView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.Query;
import com.russrezepov.mynotes.auth.Login;
import com.russrezepov.mynotes.auth.Register;
import com.russrezepov.mynotes.model.Note;
import com.russrezepov.mynotes.note.AddNote;
import com.russrezepov.mynotes.note.EditNote;
import com.russrezepov.mynotes.note.TheNoteDetails;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
DrawerLayout drawerLayout;
ActionBarDrawerToggle toggle;
NavigationView nav_view;
RecyclerView noteList;
FloatingActionButton fab;
FirebaseUser user;
FirebaseAuth fAuth;
private FirebaseFirestore fStore;
//private Adapter adapter;
//private NoteAdapter noteAdapter;
final static String TAG = "Firebase Not Reading";
final static String TAGF = "Firebase CONNECTED";
FirestoreRecyclerAdapter<Note,NoteViewHolder> noteAdapter;
//>>>ON CREATE <<<
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Log.i(TAGF,"onCreate");
drawerLayout = findViewById(R.id.drawer);
nav_view = findViewById(R.id.nav_view);
nav_view.setNavigationItemSelectedListener(this);
toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open, R.string.close);
drawerLayout.addDrawerListener(toggle);
toggle.setDrawerIndicatorEnabled(true);
toggle.syncState();
noteList = findViewById(R.id.noteList);
fab = findViewById(R.id.addNoteFloat);
View headerView = nav_view.getHeaderView(0);
TextView userDisplayName = headerView.findViewById(R.id.userDisplayName);
TextView userDisplayEmail = headerView.findViewById(R.id.userDisplayEmail);
if (user.isAnonymous()) {
userDisplayName.setText("Temporary Account");
userDisplayEmail.setVisibility(View.GONE);
} else {
userDisplayEmail.setText(user.getEmail());
userDisplayName.setText(user.getDisplayName());
}
setUpRecyclerView();
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(view.getContext(), AddNote.class));
overridePendingTransition(R.anim.slide_up,R.anim.slide_down);
finish();
}
});
}
private void setUpRecyclerView() {
fStore = FirebaseFirestore.getInstance();
fAuth = FirebaseAuth.getInstance();
user = fAuth.getCurrentUser();
//query notes=>UID=>MyNotes=>user all notes
Query query = fStore.collection("notes").document(user.getUid()).collection("myNotes").orderBy("title",Query.Direction.DESCENDING);
//executing the query
FirestoreRecyclerOptions<Note> allNotes;
allNotes = new FirestoreRecyclerOptions.Builder<Note>()
.setQuery(query, Note.class)
.build();
// fStore.collection("notes")
// .get()
// .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
// #Override
// public void onComplete(#NonNull Task<QuerySnapshot> task) {
// if (task.isSuccessful()) {
// Log.i(TAGF,"Firebase Connected Successfully");
// for (QueryDocumentSnapshot document : Objects.requireNonNull(task.getResult())) {
// //titles.add(document.getString("title"));
// //content.add(document.getString("content"));
// Log.i(TAGF,document.getString("title"));
// Log.i(TAGF,document.getString("content"));
// Log.i(TAGF,"Firebase Connected Successfully");
// }
// } else {
// Log.w(TAG,"Error getting documents.", task.getException());
// }
// }
// });
noteAdapter = new FirestoreRecyclerAdapter<Note, NoteViewHolder> (allNotes) {
#RequiresApi(api = Build.VERSION_CODES.M)
protected void onBindViewHolder(#NonNull NoteViewHolder noteViewHolder, final int i, #NonNull final Note note) {
//Binding data from MainActivity, when Adapter object is created, to this View that we have here
noteViewHolder.noteTitle.setText(note.getTitle());
noteViewHolder.noteContent.setText(note.getContent());
final int colorCodes = getRandomColor();
noteViewHolder.mCardView.setBackgroundColor(noteViewHolder.view.getResources().getColor(colorCodes,null));
//getting each doc id to be able to update them in EditNote using i as a position in collections
final String docId = noteAdapter.getSnapshots().getSnapshot(i).getId();
noteViewHolder.view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//getting current context where we are starting the Activity and passing them to another activity
Intent i = new Intent(v.getContext(), TheNoteDetails.class);
//When someone clicks on the first item in the RecyclerView it is going to get the position as Zero -> Position
//passing the title and description to the NoteDetails
i.putExtra("title", note.getTitle());
i.putExtra("content", note.getContent());
i.putExtra("color", colorCodes);
i.putExtra("noteId",docId);
v.getContext().startActivity(i); //Not passing anything yet. Just getting current context and passing current context
}
});
//Adding menu Edit & Delete functionality for each Note in Main Activity
ImageView menuIcon = noteViewHolder.view.findViewById(R.id.menuIcon);
menuIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
final String docId = noteAdapter.getSnapshots().getSnapshot(i).getId();
PopupMenu popupMenu = new PopupMenu(v.getContext(),v);
popupMenu.setGravity(Gravity.END);
popupMenu.getMenu().add("Edit").setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
Intent i = new Intent(v.getContext(), EditNote.class);
i.putExtra("title",note.getTitle());
i.putExtra("content",note.getContent());
i.putExtra("noteId",docId);
startActivity(i);
return false;
}
});
popupMenu.getMenu().add("Delete").setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
DocumentReference docRef = fStore.collection("notes").document(user.getUid()).collection("myNotes").document(docId);
docRef.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(MainActivity.this, "Note Deleted", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, "Error Deleting Note", Toast.LENGTH_SHORT).show();
}
});
return false;
}
});
popupMenu.show();
}
});
}
#NonNull
#Override
public NoteViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.note_view_layout,parent, false);
return new NoteViewHolder(view);
}
};
//Staggered layout expands based on Context Size
noteList.setLayoutManager(new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL));
noteList.setAdapter(noteAdapter);
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
drawerLayout.closeDrawer(GravityCompat.START);
switch (item.getItemId()) {
case R.id.addNote:
startActivity(new Intent(this, AddNote.class));
overridePendingTransition(R.anim.slide_up,R.anim.slide_down);
break;
case R.id.sync:
// sending Anonymous users only to Sync Activity aka Register New Account
if (user.isAnonymous()) {
startActivity(new Intent(this, Login.class));
overridePendingTransition(R.anim.slide_up,R.anim.slide_down);
} else {
Toast.makeText(this, "You Are Already Connected", Toast.LENGTH_SHORT).show();
}
break;
case R.id.logout:
checkUser();
break;
default:
Toast.makeText(this, "Coming Soon!", Toast.LENGTH_SHORT).show();
}
return false;
}
private void checkUser() {
//Check if the user is real or Anonymous
if (user.isAnonymous()) {
displayAlert();
} else {
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(getApplicationContext(), Splash.class));
overridePendingTransition(R.anim.slide_up,R.anim.slide_down);
}
}
private void displayAlert() {
AlertDialog.Builder warnignAlert = new AlertDialog.Builder(this)
.setTitle("Are you sure?")
.setMessage("you are logged in with Temp account. Logging out will delete all unsaved notes")
.setPositiveButton("Sync Note", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(getApplicationContext(), Register.class));
finish();
}
}).setNegativeButton("Logout", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//TODO: delete all the notes created by the anonymous user
// fStore.collection("notes").document(user.getUid()).document()
// fStore.collection("notes").document(user.getUid())
// .delete()
// .addOnSuccessListener(new OnSuccessListener<Void>() {
// #Override
// public void onSuccess(Void aVoid) {
// Log.d(TAG, "Notes successfully deleted!");
// }
// })
// .addOnFailureListener(new OnFailureListener() {
// #Override
// public void onFailure(#NonNull Exception e) {
// Log.w(TAG, "Error deleting Notes", e);
// }
// });
//TODO: delete the anonymous user
user.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
startActivity(new Intent(getApplicationContext(),Splash.class));
overridePendingTransition(R.anim.slide_up,R.anim.slide_down);
}
});
}
});
warnignAlert.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.option_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (item.getItemId() == R.id.settings) {
Toast.makeText(this, "Settings Menu is Clicked!", Toast.LENGTH_SHORT).show();
}
return super.onOptionsItemSelected(item);
}
#Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
#Override
protected void onStart() {
super.onStart();
noteAdapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
noteAdapter.stopListening();
}
public static class NoteViewHolder extends RecyclerView.ViewHolder {
TextView noteTitle, noteContent;
View view;
CardView mCardView;
private NoteViewHolder(#NonNull final View itemView) {
super(itemView);
noteTitle = itemView.findViewById(R.id.titles);
noteContent = itemView.findViewById(R.id.content);
mCardView = itemView.findViewById(R.id.noteCard);
view = itemView; //Handles clicks on Recycle View items. Clicks are redirected to the inside of a Note
}
}
private int getRandomColor() {
List<Integer> colorCode = new ArrayList<>();
colorCode.add(R.color.blue);
colorCode.add(R.color.yellow);
colorCode.add(R.color.skyBlue);
colorCode.add(R.color.lightPurple);
colorCode.add(R.color.lightGreen);
colorCode.add(R.color.greenlight);
colorCode.add(R.color.gray);
colorCode.add(R.color.pink);
colorCode.add(R.color.red);
colorCode.add(R.color.notgreen);
Random randomColor = new Random();
int numberColor = randomColor.nextInt(colorCode.size());
return colorCode.get(numberColor);
}
}
You are initializing the user object after accessing it. You are doing it in setUpRecyclerView but accessing it before.
setUpRecyclerView();
if (user.isAnonymous()) {
userDisplayName.setText("Temporary Account");
userDisplayEmail.setVisibility(View.GONE);
} else {
userDisplayEmail.setText(user.getEmail());
userDisplayName.setText(user.getDisplayName());
}
This will make sure you have user object before using it.
high school teachers here trying to teach how to implement a DialogFragment with listener attach with an interface to the fragment that show it. for some reason the listener is always null and while the dialog show, when I press the ok or Cancel button of the Dialog, the transfert to the implement method dont work, it stop a the line where I call the listener class (always null) in the alertDialog.Builder Here my code, thank
here my Fragment that call the dialogfragment
package net.ccl.monapp.ui;
import android.os.Bundle;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import net.ccl.monapp.R;
public class AnimationFragment extends Fragment implements MonDialogFragment.MonDialogListener {
public AnimationFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_animation,container,false);
Button myButton = root.findViewById(R.id.bt_dialog);
final TextView tvTitre = root.findViewById(R.id.tv_titre);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment myDialog = new MonDialogFragment();
// Show Alert DialogFragment
myDialog.show(getFragmentManager(), "Dialog");
}
});
return root;
}
#Override
public void onDialogPositiveClick(DialogFragment dialog) {
TextView myTitre = getView().findViewById(R.id.tv_titre);
myTitre.setText("Mon nouveau titre");
dialog.dismiss();
}
#Override
public void onDialogNegativeClick(DialogFragment dialog) {
Toast.makeText(getActivity(),"Vous avez canceler l'action du dialog",Toast.LENGTH_SHORT);
}
}
here my DialogFragment
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.DialogFragment;
public class MonDialogFragment extends DialogFragment {
public MonDialogFragment() {
}
public interface MonDialogListener {
void onDialogPositiveClick(DialogFragment dialog);
void onDialogNegativeClick(DialogFragment dialog);
}
// Use this instance of the interface to deliver action events
public MonDialogListener listener;
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
// Instantiate the NoticeDialogListener so we can send events to the host
listener = (MonDialogListener) context;
} catch (ClassCastException e) {
}
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Mon interface dialog");
builder.setMessage("Ceci est un message qui explique que tu peux changer le titre du fragment animation en cliquant sur ok");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
listener.onDialogPositiveClick(MonDialogFragment.this);
}
});
builder .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
listener.onDialogNegativeClick(MonDialogFragment.this);
}
});
return builder.create();
}
}
and here my logcat
Process: net.ccl.monapp, PID: 13691
java.lang.NullPointerException: Attempt to invoke interface method 'void net.ccl.monapp.ui.MonDialogFragment$MonDialogListener.onDialogPositiveClick(androidx.fragment.app.DialogFragment)' on a null object reference
at net.ccl.monapp.ui.MonDialogFragment$1.onClick(MonDialogFragment.java:56)
at androidx.appcompat.app.AlertController$ButtonHandler.handleMessage(AlertController.java:167)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
Your onAttach() isn't actually doing anything since the Context you're attempting to cast is your Activity, not your AnimationFragment.
Instead of reaching up to get your listener, your AnimationFragment should set the listener on the Dialog by overriding onAttachFragment().
First, you need to make sure that your MonDialogFragment is a child fragment of your AnimationFragment by changing your show() to use getChildFragmentManager():
myDialog.show(getChildFragmentManager(), "Dialog");
Then, override onAttachFragment() in your AnimationFragment:
#Override
public void onAttachFragment(Fragment fragment) {
super.onAttachFragment(fragment);
if (fragment instanceof MonDialogFragment) {
((MonDialogFragment) fragment).listener = this;
}
}
You can then remove onAttach() from MonDialogFragment entirely.
i want to change my start activity for actvity MainActivity to TuserActivity. i declared these line in my manifest:
<activity android:name=".TuserActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
But i got NullPointerException while running the application, how can i slove this problem?
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.krushi/com.example.krushi.TuserActivity}:
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:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
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.krushi.TuserActivity.onCreate(TuserActivity.java:44)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
TuserActivity:
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class TuserActivity extends AppCompatActivity {
private EditText tphnumber;
Button btSend;
TextView tEmail;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tuser);
tphnumber = findViewById(R.id.tphone);
btSend = findViewById(R.id.btSend);
btSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mobile = tphnumber.getText().toString().trim();
if(mobile.isEmpty() || mobile.length() < 10){
tphnumber.setError("Enter a valid mobile");
tphnumber.requestFocus();
return;
}
Intent intent = new Intent(TuserActivity.this, VerifyPhoneActivity.class);
intent.putExtra("mobile", mobile);
startActivity(intent);
}
});
tEmail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(TuserActivity.this, MainActivity.class);
startActivity(intent);
}
});
}
}
MainActivity:
import android.content.Intent;
import android.os.Bundle;
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.FirebaseAuth;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
public EditText emailId, passwd;
Button btnSignUp;
TextView signIn,txuser;
FirebaseAuth firebaseAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firebaseAuth = FirebaseAuth.getInstance();
emailId = findViewById(R.id.ETemail);
passwd = findViewById(R.id.ETpassword);
btnSignUp = findViewById(R.id.btnSignUp);
signIn = findViewById(R.id.TVSignIn);
txuser = findViewById(R.id.tuser);
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String emailID = emailId.getText().toString();
String paswd = passwd.getText().toString();
if (emailID.isEmpty()) {
emailId.setError("Enter your E-mail");
emailId.requestFocus();
} else if (paswd.isEmpty()) {
passwd.setError("Enter your password");
passwd.requestFocus();
} else if (emailID.isEmpty() && paswd.isEmpty()) {
Toast.makeText(MainActivity.this, "Fields Empty!", Toast.LENGTH_SHORT).show();
} else if (!(emailID.isEmpty() && paswd.isEmpty())) {
firebaseAuth.createUserWithEmailAndPassword(emailID, paswd).addOnCompleteListener(MainActivity.this, new OnCompleteListener() {
#Override
public void onComplete(Task task) {
if (!task.isSuccessful()) {
Toast.makeText(MainActivity.this.getApplicationContext(),
"SignUp unsuccessful: " + task.getException().getMessage(),
Toast.LENGTH_SHORT).show();
} else {
startActivity(new Intent(MainActivity.this, UserActivity.class));
}
}
});
} else {
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_SHORT).show();
}
}
});
signIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent I = new Intent(MainActivity.this, Activity_Login.class);
startActivity(I);
}
});
txuser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent I = new Intent(MainActivity.this, TuserActivity.class);
startActivity(I);
}
});
}
}
hey you missing the initiate tEmail textview
please add this to the TuserActivity.java before call tEmail.setOnClickListener()
tEmail = findViewById(R.id...);
You have to initialize tEmail before using it.
tEmail = findViewById(R.id.tEmail);
The final initializing block should be like
tphnumber = findViewById(R.id.tphone);
btSend = findViewById(R.id.btSend);
tEmail = findViewById(R.id.tEmail);
In TuserActivity, your code is failing at:
tEmail.setOnClickListener(...)
... because you never instantiated tEmail.
you need to find the view by calling :
tEmail = findViewById(...);
Hope this helps.
this is error m getting.. i have interview.. n i need to show this app.. but getting error.. plz help.. the app was running an hour back fluently.. i was trying to put logout button on main activity to come back on login activity but lost login button function itself...
01-18 11:59:14.938 7321-7321/info.androidhive.materialdesign E/AndroidRuntime: FATAL EXCEPTION: main
Process: info.androidhive.materialdesign, PID: 7321
java.lang.RuntimeException: Unable to start activity ComponentInfo{info.androidhive.materialdesign/info.androidhive.materialdesign.activity.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2373)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2435)
at android.app.ActivityThread.access$900(ActivityThread.java:153)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1324)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5375)
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:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at info.androidhive.materialdesign.activity.MainActivity.onClickButtonListener3(MainActivity.java:51)
at info.androidhive.materialdesign.activity.MainActivity.onCreate(MainActivity.java:45)
at android.app.Activity.performCreate(Activity.java:6865)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2326)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2435)
at android.app.ActivityThread.access$900(ActivityThread.java:153)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1324)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5375)
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:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
this is my Login.java
package info.androidhive.materialdesign.activity;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.content.Intent;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import info.androidhive.materialdesign.R;
import info.androidhive.materialdesign.db.sqlitedb;
public class Login extends Activity {
sqlitedb sqlitehelper;
SQLiteDatabase db;
private static Button btn_login, btn_back;
EditText emailEditText, passwordEditText;
int i;
int flag;
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
btn_login = (Button) findViewById(R.id.login_1);
emailEditText = (EditText)findViewById(R.id.uemail);
passwordEditText = (EditText)findViewById(R.id.upass);
sqlitehelper = new sqlitedb(getApplicationContext());
db = sqlitehelper.getWritableDatabase();
onClickButtonListener1();
onClickButtonListener2();
btn_login.setClickable(true);
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
public void onClickButtonListener1()
{
btn_back = (Button)findViewById(R.id.back_1);
btn_back.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
// Intent i = new Intent("info.androidhive.materialdesign.activity.Home");
// startActivity(i);
finish();
}
}
);
}
public void onClickButtonListener2()
{
btn_login = (Button) findViewById(R.id.login_1);
btn_login.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
onLoginClick(v);
}
}
);
}
public void onLoginClick(View v) {
if (v.getId() == R.id.login_1)
{
String contactEmail = emailEditText.getText().toString();
String contactPassword = passwordEditText.getText().toString();
String password = sqlitehelper.getSingleEntry(contactEmail);
if (contactPassword.equals(password))
{
Intent i = new Intent("info.androidhive.materialdesign.activity.MainActivity");
startActivity(i);
finish();
}
else
{
Toast temp = Toast.makeText(Login.this, "Email and password don't match", Toast.LENGTH_SHORT);
temp.show();
}
}
}
}
You initialize the login button in the onCreate() here:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
btn_login = (Button) findViewById(R.id.login_1);
and then you call the onClickButtonListener2(); in which you initialize the button again in here:
public void onClickButtonListener2()
{
btn_login = (Button) findViewById(R.id.login_1);
So just do this:
call this onClickButtonListener2(); method in onCreate() and modify code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
btn_login = (Button) findViewById(R.id.login_1);
emailEditText = (EditText)findViewById(R.id.uemail);
passwordEditText = (EditText)findViewById(R.id.upass);
sqlitehelper = new sqlitedb(getApplicationContext());
db = sqlitehelper.getWritableDatabase();
btn_login.setClickable(true);
onClickButtonListener1();
onClickButtonListener2();
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
and change the onClickButtonListener2(); to:
public void onClickButtonListener2(){
btn_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String contactEmail = emailEditText.getText().toString();
String contactPassword = passwordEditText.getText().toString();
String password = sqlitehelper.getSingleEntry(contactEmail);
if (contactPassword.equals(password)){
Intent i = new Intent("info.androidhive.materialdesign.activity.MainActivity");
startActivity(i);
YourActivity.this.finish();
}else{
Toast temp = Toast.makeText(Login.this, "Email and password don't match", Toast.LENGTH_SHORT);
temp.show();
}
}
}
);
}
Hope it helps!!!
I updated AppCompat to the newly released revision 22.1.0 and changed my AlertDialog to support.v7.app.AlertDialog. But on a Lollipop device, it throws the following exception on dismissDialog().
java.lang.NullPointerException: attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference
at android.support.v7.internal.app.WindowDecorActionBar.getDecorToolbar(WindowDecorActionBar.java:248)
at android.support.v7.internal.app.WindowDecorActionBar.init(WindowDecorActionBar.java:201)
at android.support.v7.internal.app.WindowDecorActionBar.<init>(WindowDecorActionBar.java:184)
at android.support.v7.app.AppCompatDeleg ateImplV7.cre ateSupportActionBar(AppCompatDelegateImplV7.java:176)
at android.support.v7.app.AppCompatDelegateImplBase.getSupportActionBar(AppCompatDelegateImplBase.java:85)
at android.support.v7.app.AppCompatDelegateImplV7.onStop(AppCompatDeleg ateImplV7.java:221)
at android.support.v7.app.AppCompatDialog.onStop(AppCompatDialog.java:108)
at android.app.Dialog.dismissDialog(Dialog.java:438)
at android.app.Dialog.dismiss(Dialog.java:414)
at android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:157)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5834)
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:1388)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183)
How do I fix it?
(Lower-version devices seems to work well. This just happens in Lollipop)
+
I don't call dismiss() explicitly in my code. The dialog throws the exception when it is dismissed by back-button or positive/negative button.
++ Here is my code that uses v7.app.AlertDialog. Thank you.
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
public class SimpleYesNoFragment extends DialogFragment {
public interface OnConfirmListner {
public void onConfirm();
}
public static SimpleYesNoFragment newInstance(String title, String message) {
SimpleYesNoFragment fragment = new SimpleYesNoFragment();
Bundle args = new Bundle();
args.putString("title", title);
args.putString("message", message);
fragment.setArguments(args);
return fragment;
}
private OnConfirmListner mListener;
public void setOnConfirmListener(OnConfirmListner l) {
mListener = l;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder b= new AlertDialog.Builder(getActivity())
.setPositiveButton(R.string.yes, new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if(mListener != null) {
mListener.onConfirm();
}
}
})
.setNegativeButton(R.string.no, new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
Bundle args = getArguments();
String title = args.getString("title",null);
if(!TextUtils.isEmpty(title)) {
b.setTitle(title);
}
String message = args.getString("message",null);
if(!TextUtils.isEmpty(message)) {
b.setMessage(message);
}
return b.create();
}
}
By chance I've noticed that my project has values-v21/themes.xml and it applies android:Theme.Material.Light.Dialog.Alert to the support.v7.app.AlertDialog. This caused the weird bug.
Using a proper AppCompat Theme, such as Theme.AppCompat.Light.Dialog.Alert, to the support.v7.app.AlertDialog solved the problem. Thanks to everyone for helping me out.