Getting nullpointer exception in Imageview of a layout file [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
Hello my problem is that i am getting a null pointer exception in my program i am getting a exception in a imageview of a layout file i am trying to make a firebase app so i use try-catch blocks for handling firebase error so i decided to make a beautiful dialog box but when i test it first time it runs but now it throws a null pointer exception so please help me here is my code and activities
:- my register activity
public class registerActivity extends Activity {
Dialog error_dialog_box_register;
TextView dialog_title_register, dialog_message_register;
ImageView dialog_main_image, dialog_cancel_image;
Button ok_button, login_button;
private Button RegisterButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
RegisterButton = findViewById(R.id.register_in_button);
RegisterButtonListener();
}
private void RegisterButtonListener() {
RegisterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CreateNewAccount();
}
});
}
private void CreateNewAccount() {
mAuth.createUserWithEmailAndPassword(Email, Password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Register_Progress_bar.setVisibility(View.GONE);
SendUserToDate_of_birthActivity();
} else {
try {
Register_Progress_bar.setVisibility(View.GONE);
throw Objects.requireNonNull(task.getException());
} catch (FirebaseAuthUserCollisionException f) {
ShowErrorPopup();
Toast.makeText(registerActivity.this, "User already exists", Toast.LENGTH_SHORT).show();
} catch (FirebaseNetworkException e) {
Toast.makeText(registerActivity.this, "Error network error", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
}
#SuppressLint("SetTextI18n")
private void ShowErrorPopup() {
error_dialog_box_register.setContentView(R.layout.custom_popup_p);
dialog_cancel_image = (ImageView) findViewById(R.id.Cancel_dialog_box_register);
ok_button = (Button) findViewById(R.id.dialog_ok_button_register);
login_button = (Button) findViewById(R.id.dialog_login_button_register);
dialog_title_register = (TextView) findViewById(R.id.Dialog_title_register);
dialog_message_register = (TextView) findViewById(R.id.dialog_message_register);
dialog_cancel_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
error_dialog_box_register.dismiss();
}
});
login_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SendUserToLoginActivity();
}
});
dialog_title_register.setText("Error");
dialog_message_register.setText("Email already exists please login or try again");
error_dialog_box_register.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
error_dialog_box_register.show();
}
}
Here is my xml file:-
<?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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:gravity="center"
android:orientation="vertical">
<ImageView
android:id="#+id/Cancel_dialog_box_register"
android:layout_width="46dp"
android:layout_height="38dp"
android:layout_alignParentEnd="true"
android:layout_marginTop="7dp"
android:layout_marginEnd="7dp"
android:elevation="5dp"
android:src="#drawable/ic_close_black_24dp"
/>
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
app:cardBackgroundColor="#color/ColorRed"
app:cardCornerRadius="15dp"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:layout_marginBottom="25dp"
android:orientation="vertical">
<TextView
android:id="#+id/Dialog_title_register"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:text=""
android:textAlignment="center"
android:textColor="#000000"
android:textSize="25sp"
android:textStyle="bold" />
<ImageView
android:id="#+id/dialog_main_image_register"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginBottom="10dp"
android:src="#drawable/ic_error_black_24dp" />
<TextView
android:id="#+id/dialog_message_register"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginBottom="20dp"
android:text=""
android:textAlignment="center"
android:textColor="#000000"
android:textSize="18sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/dialog_login_button_register"
android:layout_width="180dp"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:layout_marginStart="20dp"
android:layout_marginTop="20dp"
android:background="#drawable/login_b_custom"
android:text="#string/login"
android:textColor="#color/colorPrimaryDark"
android:textSize="15sp" />
<Button
android:id="#+id/dialog_ok_button_register"
android:layout_width="180dp"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:layout_marginStart="15dp"
android:layout_marginTop="20dp"
android:background="#drawable/login_b_custom"
android:text="Ok"
android:textColor="#color/colorPrimaryDark"
android:textSize="15sp"
/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
</RelativeLayout>
And i am getting error like these
2019-08-03 15:52:13.840 5711-5711/? E/Zygote: isWhitelistProcess - Process is Whitelisted
2019-08-03 15:52:13.841 5711-5711/? E/Zygote: accessInfo : 1
2019-08-03 15:52:43.642 5711-5711/com.geetmp3.themusicapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.geetmp3.themusicapp, PID: 5711
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.geetmp3.themusicapp.AccountCreation.registerActivity.ShowErrorPopup(registerActivity.java:193)
at com.geetmp3.themusicapp.AccountCreation.registerActivity.access$300(registerActivity.java:34)
at com.geetmp3.themusicapp.AccountCreation.registerActivity$2.onComplete(registerActivity.java:146)
at com.google.android.gms.tasks.zzj.run(Unknown Source:4)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7076)
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:965)
Please reply me why i am getting null pointer exception and please help me

In your OnCreate function you assign your RegisterButton as:
RegisterButton = findViewById(R.id.register_in_button);
but in your layout you have two buttons with the IDs of:
android:id="#+id/dialog_login_button_register"
and
android:id="#+id/dialog_ok_button_register"
So your findViewById call returns with null because no button with the ID of register_in_button exists. Then you get an exception when you attempt to invoke the null object's method.

Please create variables reference by dialog because all ImageVeiw or textview are inside the dialog
error_dialog_box_register= new Dialog(this);
error_dialog_box_register.requestWindowFeature(Window.FEATURE_NO_TITLE);
error_dialog_box_register.setContentView(R.layout.custom_popup_p);
error_dialog_box_register.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
error_dialog_box_register.setCancelable(false);
dialog_cancel_image = error_dialog_box_register.findViewById(R.id.Cancel_dialog_box_register);

Related

java.lang.NullPointerException in Firebase Realtime Database fetching activity

I have beenn struggling to find out why I am getting the error: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
Below is the full description of the error:
2021-03-15 14:15:49.906 24447-24447/com.goldencrestit.quicky2 D/AndroidRuntime: Shutting down VM
2021-03-15 14:15:49.907 24447-24447/com.goldencrestit.quicky2 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.goldencrestit.quicky2, PID: 24447
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
at com.goldencrestit.quicky2.ViewProfileActivity$1.onDataChange(ViewProfileActivity.java:64)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(ValueEventRegistration.java:75)
at com.google.firebase.database.core.view.DataEvent.fire(DataEvent.java:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(EventRaiser.java:55)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:264)
at android.app.ActivityThread.main(ActivityThread.java:7581)
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:980)
This error pops up when I click on the "View your Profile" button in order to load the profile page.
Below is the expected result. It is support to fetch data from my firebase realtime database to fill the dummy texts:
Check below my codes:
activity_company_portal.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:background="#color/bg_color"
android:orientation="vertical"
tools:context=".CompanyPortal">
<include
layout="#layout/toolbar"
android:id="#+id/toolbar_home" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="right"
android:padding="20dp"
android:orientation="horizontal">
<ImageButton
android:id="#+id/logout_btn"
android:layout_width="50dp"
android:layout_height="50dp"
android:background="#drawable/ic_baseline_power_settings_new_24" />
</LinearLayout>
<ImageView
android:id="#+id/imageView3"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center"
android:layout_marginTop="10dp"
app:srcCompat="#drawable/logo" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="20dp">
<Button
android:id="#+id/view_job"
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="#drawable/button_bg"
android:layout_marginTop="20dp"
android:textColor="#color/text_color_secondary"
android:textSize="16sp"
android:letterSpacing=".2"
android:text="#string/view_all_jobs" />
<Button
android:id="#+id/add_job"
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="#drawable/button_bg"
android:layout_marginTop="50dp"
android:textColor="#color/text_color_secondary"
android:layout_below="#id/view_job"
android:textSize="16sp"
android:letterSpacing=".2"
android:text="#string/add_a_new_job" />
<Button
android:id="#+id/edit_profile"
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="#drawable/button_bg"
android:layout_marginTop="50dp"
android:textColor="#color/text_color_secondary"
android:layout_below="#id/add_job"
android:textSize="16sp"
android:letterSpacing=".2"
android:text="#string/edit_your_profile" />
<Button
android:id="#+id/view_profile"
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="#drawable/button_bg"
android:layout_marginTop="50dp"
android:textColor="#color/text_color_secondary"
android:layout_below="#id/edit_profile"
android:textSize="16sp"
android:letterSpacing=".2"
android:text="#string/view_your_profile" />
</RelativeLayout>
</LinearLayout>
CompanyPortalActivity.java
public class CompanyPortalActivity extends AppCompatActivity {
private FirebaseAuth mAuth;
private FirebaseUser mCurrentUser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_company_portal);
Toolbar toolbar = findViewById(R.id.toolbar_home);
setSupportActionBar(toolbar);
Objects.requireNonNull(getSupportActionBar()).setTitle("Quicky Job Portal");
Button viewJobs = findViewById(R.id.view_job);
Button postJobs = findViewById(R.id.add_job);
Button edit_profile = findViewById(R.id.edit_profile);
Button view_profile = findViewById(R.id.view_profile);
viewJobs.setOnClickListener(v -> startActivity(new Intent(getApplicationContext(), IndividualPostActivity.class)));
postJobs.setOnClickListener(v -> startActivity(new Intent(getApplicationContext(), PostJobsActivity.class)));
edit_profile.setOnClickListener(v -> startActivity(new Intent(getApplicationContext(), EditProfileActivity.class)));
view_profile.setOnClickListener(v -> startActivity(new Intent(getApplicationContext(), ViewProfileActivity.class)));
mAuth = FirebaseAuth.getInstance();
mCurrentUser = mAuth.getCurrentUser();
ImageButton mLogoutBtn = findViewById(R.id.logout_btn);
mLogoutBtn.setOnClickListener(v -> {
mAuth.signOut();
sendUserToLogin();
});
}
#Override
protected void onStart() {
super.onStart();
if(mCurrentUser == null){
sendUserToLogin();
}
}
private void sendUserToLogin() {
Intent loginIntent = new Intent(getApplicationContext(), CompanyLoginActivity.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(loginIntent);
finish();
}
}
activity_view_profile.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/bg_color"
tools:context=".ViewProfileActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<include
layout="#layout/toolbar"
android:id="#+id/toolbar"/>
<ImageView
android:id="#+id/imageView7"
android:layout_width="match_parent"
android:layout_height="50dp"
app:srcCompat="#drawable/logo" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#color/text_color_primary"
android:layout_marginTop="10dp"
android:layout_marginEnd="40dp"
android:layout_marginStart="40dp"
android:text="Company Name" />
<TextView
android:id="#+id/company_name"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginTop="5dp"
android:layout_marginEnd="40dp"
android:layout_marginBottom="20dp"
android:textAlignment="center"
android:layout_marginStart="40dp"
android:textColor="#color/text_color_secondary"
android:text="Golden Crest Tech"
android:background="#drawable/text_display" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#color/text_color_primary"
android:layout_marginEnd="40dp"
android:layout_marginStart="40dp"
android:text="Business Type" />
<TextView
android:id="#+id/business_type"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginTop="5dp"
android:layout_marginEnd="40dp"
android:layout_marginBottom="20dp"
android:textAlignment="center"
android:layout_marginStart="40dp"
android:textColor="#color/text_color_secondary"
android:text="Technology"
android:background="#drawable/text_display" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#color/text_color_primary"
android:layout_marginEnd="40dp"
android:layout_marginStart="40dp"
android:text="Phone Number" />
<TextView
android:id="#+id/phone_number"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginTop="5dp"
android:layout_marginEnd="40dp"
android:layout_marginBottom="20dp"
android:textAlignment="center"
android:layout_marginStart="40dp"
android:textColor="#color/text_color_secondary"
android:text="08020345678"
android:background="#drawable/text_display" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#color/text_color_primary"
android:layout_marginEnd="40dp"
android:layout_marginStart="40dp"
android:text="Company Address" />
<TextView
android:id="#+id/address"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginTop="5dp"
android:layout_marginEnd="40dp"
android:layout_marginBottom="20dp"
android:textAlignment="center"
android:layout_marginStart="40dp"
android:textColor="#color/text_color_secondary"
android:text="Surulere, Lagos"
android:background="#drawable/text_display" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#color/text_color_primary"
android:layout_marginEnd="40dp"
android:layout_marginStart="40dp"
android:layout_marginBottom="5dp"
android:text="Company Detail" />
<EditText
android:id="#+id/editTextTextMultiLine"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="40dp"
android:layout_marginEnd="40dp"
android:background="#drawable/text_display_2"
android:clickable="false"
android:editable="false"
android:ems="10"
android:enabled="false"
android:fontFamily="#font/open_sans"
android:gravity="start|top"
android:inputType="textMultiLine"
android:text="#string/company_detail_dummy"
android:textColor="#color/text_color_secondary"
android:textSize="14sp" />
<Button
android:id="#+id/edit_profile"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/button_bg"
android:layout_marginLeft="40dp"
android:layout_marginRight="40dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="20dp"
android:textColor="#color/text_color_secondary"
android:textAllCaps="false"
android:textSize="16sp"
android:text="Edit Profile" />
</LinearLayout>
</ScrollView>
ViewProfileActivity.java
public class ViewProfileActivity extends AppCompatActivity {
private DatabaseReference myRef;
TextView company_name_txt, business_type_txt, phone_number_txt, company_address_txt;
EditText company_detail_txt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_profile);
company_name_txt = findViewById(R.id.company_name);
business_type_txt = findViewById(R.id.business_type);
phone_number_txt = findViewById(R.id.phone_number);
company_address_txt = findViewById(R.id.address);
company_detail_txt = findViewById(R.id.company_detail);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Objects.requireNonNull(getSupportActionBar()).setTitle("Company Profile");
Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
Objects.requireNonNull(getSupportActionBar()).setDisplayShowHomeEnabled(true);
myRef = FirebaseDatabase.getInstance().getReference().child("Company Profile");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()){
String companyName = snapshot.child("company_name").getValue().toString();
String phoneNumber = snapshot.child("phone_number").getValue().toString();
String companyAddress= snapshot.child("address").getValue().toString();
String businessType = snapshot.child("business_type").getValue().toString();
company_name_txt.setText(companyName);
business_type_txt.setText(businessType);
company_address_txt.setText(companyAddress);
phone_number_txt.setText(phoneNumber);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {}
});
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (item.getItemId()==android.R.id.home){
finish();
}
return super.onOptionsItemSelected(item);
}
}
Below is what I am trying to display on the Job Detail Layout:
The error seems to come from this piece of code:
myRef = FirebaseDatabase.getInstance().getReference().child("Company Profile");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()){
String companyName = snapshot.child("company_name").getValue().toString();
String phoneNumber = snapshot.child("phone_number").getValue().toString();
String companyAddress= snapshot.child("address").getValue().toString();
String businessType = snapshot.child("business_type").getValue().toString();
company_name_txt.setText(companyName);
business_type_txt.setText(businessType);
company_address_txt.setText(companyAddress);
phone_number_txt.setText(phoneNumber);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {}
});
The above code is loading all data from /Company Profile and then trying to read the company_name property from it. But if we look at the data you shared, there is no /Company Profile/company_name property, so that explains why getValue() returns null and the toString() then leads to the exception you get.
It seems your JSON tree consists of: /Company Profile/$uid/$pushid. How to property load the data from this structure depends on how much information you already know in your code, so let's look at the options:
If you know both the UID and the push ID of the information you want to load, you can do load just that with:
myRef = FirebaseDatabase.getInstance().getReference().child("Company Profile");
String uid = "6babpG...MxLg33"; // must be the exact, complete value
String pushid = "-MVmyqx...3rwsAO"; // must be the exact, complete value
myRef.child(uid).child(pushid().addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()){
String companyName = snapshot.child("company_name").getValue().toString();
...
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
throw error.toException(); // never ignore errors
}
});
If you know the UID, but not the push ID, of the information you want to load, you can load all push IDs and loop over them with:
myRef = FirebaseDatabase.getInstance().getReference().child("Company Profile");
String uid = "6babpG...MxLg33"; // must be the exact, complete value
myRef.child(uid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
String companyName = snapshot.child("company_name").getValue().toString();
...
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
throw error.toException(); // never ignore errors
}
});
So here we loop over dataSnapshot.getChildren() to get across the unknown push IDs from the database. This means we can have multiple child nodes, so you may want to consider using a list view/recycler view for displaying the data.
The final case is if you know neither the UID nor the push ID of the data you want to display. In that case you need two nested loops to navigate over the data, one for the UIDs in the JSON, and one for the push IDs. So:
myRef = FirebaseDatabase.getInstance().getReference().child("Company Profile");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
for (DataSnapshot snapshot: userSnapshot.getChildren()) {
String companyName = snapshot.child("company_name").getValue().toString();
...
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
throw error.toException(); // never ignore errors
}
});
You'll note that the solution is quite similar to the previous one, but now with a second loop. Here too, you'll have to consider what is the best UI element to display the structure, as now you're navigating/parsing an entire tree-like structure from the database.

I can't get data from Edittext [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 3 years ago.
I have some issues creating a login activity.
Even though I put the right username (123456) and password (123456789).
I made sure to put the getText() method inside onLogin but I always get the message "login failed" and so I assume I don't get any data from EditText, and so I can't see what's wrong.
this login java class:
public class LoginActivity extends AppCompatActivity {
private EditText UsernameEt;
private EditText PasswordEt;
AlertDialog alertDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
UsernameEt=findViewById(R.id.username);
PasswordEt=findViewById(R.id.password);
alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Login Status");
}
public void onLogin(View view) {
String username = UsernameEt.getText().toString();
String password = PasswordEt.getText().toString();
String type = "login";
//BackgroundWorker backgroundWorker = new BackgroundWorker(this);
//backgroundWorker.execute(type, username, password);
if(username=="123456" && password=="123456789"){
alertDialog.setMessage("Login success");
alertDialog.show();
} else {
alertDialog.setMessage("Login failed");
alertDialog.show();
}
}
}
and this is the login xml:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="#drawable/bg"
android:fitsSystemWindows="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:orientation="vertical">
<EditText
android:id="#+id/username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:backgroundTint="#FFFFFF"
android:drawableLeft="#drawable/ic_person_black_24dp"
android:ems="10"
android:hint="IPN"
android:inputType="textPersonName"
android:textColor="#FFFFFF"
android:textColorHint="#FFFFFF" />
<EditText
android:id="#+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:backgroundTint="#FFFFFF"
android:drawableLeft="#drawable/ic_lock_black_24dp"
android:ems="10"
android:hint="Password"
android:inputType="textPassword"
android:textColor="#FFFFFF"
android:textColorHint="#FFFFFF" />
<Button
android:id="#+id/buttonLogin"
style="#style/DefaultButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|center"
android:layout_marginTop="16dp"
android:layout_marginEnd="0dp"
android:layout_marginRight="0dp"
android:background="#drawable/gradiant"
android:onClick="onLogin"
android:text="#string/login"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</LinearLayout>
</ScrollView>
if(username.equals("123456") && password.equals("123456789"){
// login true
}
try this
username.getText().toString().contentEquals("123456") && password.getText().toString().contentEquals("123456789")

android java Null point exeption at view.setonclicklistener at the secend init why they do not match

I have this problem and it shows me following error
please help me:
I get a NullPointerException in init2(). Apperently sms is null.
I don't understand the problem
Process: com.example.android.projectdestage, PID: 11049
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.android.projectdestage/com.example.android.projectdestage.MainActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.view.View.setOnClickListener(android.view.View$OnClickListener)'
on a null object reference
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2984)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3045)
at android.app.ActivityThread.-wrap14(ActivityThread.java)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1642)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6776)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1518)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.view.View.setOnClickListener(android.view.View$OnClickListener)'
on a null object reference
at
com.example.android.projectdestage.MainActivity.init2(MainActivity.java:60)
at
com.example.android.projectdestage.MainActivity.onCreate(MainActivity.java:38)
at android.app.Activity.performCreate(Activity.java:6956)
at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2927)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3045) 
at android.app.ActivityThread.-wrap14(ActivityThread.java) 
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1642) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6776) 
at java.lang.reflect.Method.invoke(Native Method) 
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1518) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)
****this is my main activity****
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
public class MainActivity extends AppCompatActivity
{
private Button sms;
private Button btnMap;
private static final String TAG = "MainActivity";
private static final int ERROR_DIALOG_REQUEST = 9001;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_main);
if(isServicesOK()){
init();
init2();
}
}
private void init(){
Button btnMap = (Button) findViewById(R.id.btnMap);
btnMap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, MapActivity.class);
startActivity(intent);
}
});
}
private void init2()
{
Button sms = (Button) findViewById(R.id.sms);
sms.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent message = new Intent(MainActivity.this, MainActivity2.class);
startActivity(message);
}
});
}
public boolean isServicesOK()
{
Log.d(TAG, "isServicesOK: checking google services version");
int available = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(MainActivity.this);
if(available == ConnectionResult.SUCCESS)
{
// koulchi mli7 map request
Log.d(TAG, "isServicesOK: Google Play Services is working");
return true;
}
else if(GoogleApiAvailability.getInstance().isUserResolvableError(available))
{
//test d erreur
Log.d(TAG, "isServicesOK: an error occured but we can fix it");
Dialog dialog = GoogleApiAvailability.getInstance().getErrorDialog(MainActivity.this, available, ERROR_DIALOG_REQUEST);
dialog.show();
}else
{
Toast.makeText(this, "You can't make map requests", Toast.LENGTH_SHORT).show();
}
return false;
}
}
`**this is my mainactivity xml**`
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.android.projectdestage.MainActivity">
<Button
android:id="#+id/btnMap"
android:layout_width="87dp"
android:layout_height="45dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="244dp"
android:text="#string/map"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.43"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/smsbtn"
android:layout_width="wrap_content"
android:layout_height="43dp"
android:layout_marginBottom="136dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="#string/enter_your_message"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.43"
app:layout_constraintStart_toStartOf="parent" />
</android.support.constraint.ConstraintLayout>
**and the main2activity 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:gravity="center"
android:orientation="vertical"
tools:context="com.example.android.projectdestage.MainActivity2">
<TextView
android:id="#+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/enter_your_message"
android:textSize="30sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="519dp"
android:orientation="vertical">
<TextView
android:id="#+id/editText2"
android:layout_width="385dp"
android:layout_height="410dp"
android:layout_marginTop="50dp"
android:layout_weight="1"
android:text="#string/textview" />
<Button
android:id="#+id/btnSendSMSendSms"
android:layout_width="wrap_content"
android:layout_height="250dp"
android:layout_marginLeft="150dp"
android:layout_marginStart="150dp"
android:layout_marginVertical="110dp"
android:layout_weight="1"
android:text="#string/sendsms"
tools:targetApi="o" />
</LinearLayout>
</LinearLayout>
and the the mapactivity xml
i think the main problem is here
<?xml version="1.0" encoding="utf-8"?>
<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">
<fragment 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:id="#+id/map"
tools:context=".MapsActivity"
android:name="com.google.android.gms.maps.SupportMapFragment" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginTop="10dp"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp"
android:elevation="10dp"
android:background="#drawable/white_border"
android:id="#+id/relLayout1" tools:targetApi="lollipop">
<ImageView
android:layout_width="15dp"
android:layout_height="15dp"
android:id="#+id/ic_magnify"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:src="#drawable/ic_magnify" android:contentDescription="#string/todoo" android:layout_marginStart="10dp" />
<AutoCompleteTextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_toRightOf="#+id/ic_magnify"
android:layout_centerVertical="true"
android:textSize="15sp"
android:textColor="#000"
android:id="#+id/input_search"
android:background="#null"
android:hint="#string/enter_address_city_or_zip_code"
android:imeOptions="actionSearch" android:layout_toEndOf="#+id/ic_magnify" />
</RelativeLayout>
<ImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_below="#id/relLayout1"
android:layout_alignParentRight="true"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:scaleType="centerCrop"
android:id="#+id/ic_gps"
android:src="#drawable/ic_gps" android:contentDescription="#string/todo" android:layout_alignParentEnd="true" android:layout_marginEnd="10dp" />
<ImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:id="#+id/place_picker"
android:layout_marginLeft="10dp"
android:layout_marginTop="15dp"
android:scaleType="centerCrop"
android:layout_below="#+id/relLayout1"
android:src="#drawable/ic_map" android:contentDescription="#string/todoml" android:layout_marginStart="10dp" />
<ImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_below="#+id/place_picker"
android:layout_marginLeft="10dp"
android:layout_marginTop="15dp"
android:scaleType="centerCrop"
android:id="#+id/place_info"
android:src="#drawable/ic_info" android:layout_marginStart="10dp" android:contentDescription="#string/todoop" />
</RelativeLayout>
thank you
thank you
thank you
thank you
thank you
thank you
thank you
thank you
thank you
thank you
thank you
thank you
thank you
thank you
thank you
thank you
thank you
thank you
thank you
thank you
Button sms = (Button) findViewById(R.id.sms); returns null
This means he can not find R.id.sms in your activity_main.xml layout.
Maybe a typo or copy paste error? Check if this button's ID in this file really is sms.
Also if you have multiple layouts for different screen sizes, etc. Check all of them.
You have smsBtn as an id for sms Button in your activity_main.xml, whereas you've passed sms as id. So id with sms is not found and so button is null and throws null pointer exception.
There is better approach that can accomplish this using Butterknife library:
public class MainActivity extends AppCompatActivity
{
#BindView(R.id.smsBtn)
private Button sms;
#BindView(R.id.btnMap)
private Button btnMap;
private static final String TAG = "MainActivity";
private static final int ERROR_DIALOG_REQUEST = 9001;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_main);
ButterKnife.bind(this);
}
#OnClick({R.id.btnMap, R.id.smsBtn})
public void onClick(View view) {
switch (view.getId()) {
case R.id.btnMap:
//Your functionality
break;
case R.id.smsBtn:
//Your functionality
break;
}
}
}
//Dependency for ButterKnife library
implementation 'com.jakewharton:butterknife:8.8.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
//Butterknife link
https://github.com/JakeWharton/butterknife

java.lang.StringIndexOutOfBoundsException: error in Android

while I was testing my app using the virtual emulator (don't have a valid device where I can test), I found out a bug. That's the java.lang.StringIndexOutOfBoundsException: length=0; index=2 error, and it pops out when I click on an EditText and try to write in it. The EditText is set to appear when another button is clicked. Here is the XML:
<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.luca.cecco.activity.allergie"
android:padding="20dp"
android:orientation="vertical"
android:background="#drawable/possible4_bg">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hai allergie?"
android:fontFamily="sans-serif"
android:textAllCaps="true"
style="#style/BOLD"
android:textAlignment="center"
android:layout_gravity="center"
android:layout_marginTop="200dp"
android:background="#drawable/round_shape_btn"
android:textColor="#color/blank"
android:padding="10dp"
android:textSize="40sp"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="105dp">
<Button
android:id="#+id/btn_allergia_si"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_marginLeft="120dp"
android:layout_marginRight="10dp"
android:background="#drawable/round_shape_clicked_btn"
android:fontFamily="sans-serif"
android:text="Sì"
android:textAllCaps="true"
style="#style/BOLD"
android:gravity="center"
android:textColor="#color/blank"
android:textSize="30sp" />
<Button android:id="#+id/btn_allergia_no"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="No"
style="#style/BOLD"
android:gravity="center"
android:background="#drawable/round_shape_clicked_btn"
android:fontFamily="sans-serif"
android:textAllCaps="true"
android:textColor="#color/blank"
android:textSize="30sp"
android:layout_marginLeft="110dp"/>
</LinearLayout>
<EditText android:id="#+id/allergia_si"
android:layout_width="285dp"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:layout_marginLeft="150dp"
android:hint="Inserisci qui le tue allergie"
android:textAlignment="center"
android:textSize="20sp"
android:textColorHint="#color/blank"
android:background="#drawable/round_shape_clicked_btn"
android:textAllCaps="true"
android:padding="5dp"/>
<Button android:id="#+id/btn_avanti3"
android:layout_marginTop="100dp"
android:layout_marginRight="30dp"
android:layout_width="110dp"
android:textColor="#color/blank"
android:layout_height="85dp"
android:text="Avanti"
android:gravity="center"
android:textAlignment="center"
android:textSize="20sp"
android:layout_gravity="end"
style="#style/AlertDialog.AppCompat"
android:background="#color/blue_button"
android:textStyle="bold"
android:textAllCaps="true"
android:fontFamily="sans-serif"
/>
</LinearLayout>
</RelativeLayout>
And here it is the Java class:
private Button btn_si;
private Button btn_no;
private EditText et_allergia;
private Button btn_avanti;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_allergie);
btn_si = (Button) findViewById(R.id.btn_allergia_si);
btn_no = (Button) findViewById(R.id.btn_allergia_no);
et_allergia = (EditText) findViewById(R.id.allergia_si);
btn_avanti = (Button) findViewById(R.id.btn_avanti3);
et_allergia.setVisibility(View.INVISIBLE);
btn_no.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
btn_no.setBackground(getResources().getDrawable(R.drawable.round_shape_clicked_btn)); //cambia il colore di base
}
});
btn_si.setOnClickListener(new View.OnClickListener() { //cambia il colore di base e rende visibile l'edit text
#Override
public void onClick(View view)
{
btn_si.setBackground(getResources().getDrawable(R.drawable.round_shape_clicked_btn)); //cambia il colore di base
et_allergia.setVisibility(View.VISIBLE);
}
});
btn_avanti.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
Intent intent = new Intent(allergie.this, Preferenze.class);
startActivity(intent);
}
});
}
You are getting error Because, You have set property 'textAllCaps' in EditText. This property is mostly used for TextView.
Remove This Property and try again.

Why am I unable to get a Dialog when clicking the image?

I want the user to choose that whether they'd like to take picture or choose one from gallery.
I set up an OnClickListener on my Image but when I'm clicking the image, nothing is happening.
Here is my SettingUpUserProfile.java file's code:
public class SettingUpUserProfile extends AppCompatActivity {
public static final int TAKE_PHOTO_REQUEST = 0;
protected ImageView userProfilePicture;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setting_up_user_profile);
userProfilePicture = (ImageView) findViewById(R.id.userProfilePicture);
userProfilePicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(SettingUpUserProfile.this);
builder.setTitle(null);
builder.setItems(R.array.pickImage_options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int position) {
switch (position) {
case 0:
Intent intentCaptureFromCamera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intentCaptureFromCamera, TAKE_PHOTO_REQUEST);
break;
case 1:
// Choose from gallery.
}
}
});
}
});
}
}
and here is my activity_setting_up_user_profile.xml file's code:
<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:background="#color/light_purple"
tools:context="com.abc.xyz.SettingUpUserProfile">
<TextView
android:id="#+id/settingUpUserProfileText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:text="#string/settingUpUserProfileText1"
android:textColor="#color/white"
android:textStyle="bold"
android:textSize="30sp"
android:gravity="center_horizontal|center_vertical"/>
<ImageView
android:id="#+id/userProfilePicture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/settingUpUserProfileText1"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_marginTop="100dp"
android:clickable="true"
android:src="#drawable/ic_face_white_48dp" />
<TextView
android:id="#+id/settingUpUserProfileText2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/userProfilePicture"
android:layout_marginTop="5dp"
android:text="#string/settingUpUserProfileText2"
android:textColor="#color/white"
android:textSize="15sp"
android:gravity="center_horizontal|center_vertical"/>
<EditText
android:id="#+id/userName"
android:background="#drawable/phone_number_edit_text_design"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/settingUpUserProfileText2"
android:layout_marginTop="80dp"
android:layout_marginLeft="10dp"
android:layout_marginStart="10dp"
android:layout_marginRight="10dp"
android:layout_marginEnd="10dp"
android:gravity="center_horizontal|center_vertical"
android:hint="#string/hint_userName"
android:textColor="#color/white"
android:textColorHint="#E0E0E0"
android:textCursorDrawable="#null"
android:inputType="textPersonName"/>
<Button
android:id="#+id/buttonAllSet"
android:background="#color/white"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/userName"
android:layout_marginTop="20dp"
android:text="#string/button_allSet"
android:textStyle="bold"
android:textColor="#color/light_purple"
android:layout_marginEnd="120dp"
android:layout_marginStart="120dp"
android:gravity="center_horizontal|center_vertical"/>
</RelativeLayout>
I'm really unable to figure out what is wrong here.
Kindly, let me know.
I'm new to StackOverflow so please cooperate.
Thanks in advance.
Add Below lines to your onClick() method
AlertDialog alertDialog = builder.create();
alertDialog.show();

Categories