Getting NullPointerException at NavigationView - java

I'm trying to make a Drawer Menu but i'm having NullPointer, but i think everything is corect.
I'll post all my code here:
package wagner.com.meuartesanato.home;
import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import wagner.com.meuartesanato.R;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showHome(null);
TextView textMenu = (TextView) findViewById(R.id.text_menu);
TextView textHome = (TextView) findViewById(R.id.text_home);
TextView textSimulation = (TextView) findViewById(R.id.text_simulation);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
loadDrawer();
}
public void showMenu(View v){
//drawer.openDrawer(GravityCompat.END);
}
public void showHome(View v){
//loadFragment(Home1Fragment.class);
}
public void showSimulation(View v){
Toast.makeText(this,"Mostrar simulação",Toast.LENGTH_SHORT).show();
}
private void loadDrawer(){
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View view = navigationView.getHeaderView(0);
Button about = (Button)view.findViewById(R.id.button_about);
Button howToUse = (Button)view.findViewById(R.id.button_how_to_use);
Button addAccount = (Button)view.findViewById(R.id.button_add_account);
Button changeRegister = (Button)view.findViewById(R.id.button_change_register);
Button changePassword = (Button)view.findViewById(R.id.button_change_password);
Button help = (Button)view.findViewById(R.id.button_help);
Button exit = (Button)view.findViewById(R.id.button_exit);
about.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Mostra tela sobre o app
//loadFragment(SobreFragment.class);
drawer.closeDrawer(GravityCompat.END);
}
});
howToUse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this,"Mostrar como usar",Toast.LENGTH_SHORT).show();
drawer.closeDrawer(GravityCompat.END);
}
});
addAccount.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this,"Mostrar algo",Toast.LENGTH_SHORT).show();
drawer.closeDrawer(GravityCompat.END);
}
});
changeRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this,"Alterar cadastro",Toast.LENGTH_SHORT).show();
drawer.closeDrawer(GravityCompat.END);
}
});
changePassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this,"Alterar cadastro",Toast.LENGTH_SHORT).show();
drawer.closeDrawer(GravityCompat.END);
}
});
help.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this,"Help",Toast.LENGTH_SHORT).show();
drawer.closeDrawer(GravityCompat.END);
}
});
exit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//fecha a activity, voltando pra tela de login
finish();
}
});
}
private void loadFragment(Class fragmentClass){
try {
Fragment fragment = (Fragment) fragmentClass.newInstance();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragment_holder, fragment).commit();
}catch (Exception e) {
e.printStackTrace();
}
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
drawer.closeDrawer(GravityCompat.END);
return false;
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.END)) {
drawer.closeDrawer(GravityCompat.END);
} else {
drawer.openDrawer(GravityCompat.END);
}
}
}
And my xml files:
activity_home.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout 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:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="end"
app:headerLayout="#layout/nav_header_main"
android:fitsSystemWindows="true"
android:background="#color/colorWhite"/>
</android.support.v4.widget.DrawerLayout>
activity_main.xml
<?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:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="10dp"
android:background="#drawable/degrade"
tools:context="wagner.com.meuartesanato.home.MainActivity">
<LinearLayout
android:baselineAligned="false"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/top_bar">
<LinearLayout
android:onClick="showMenu"
android:layout_width="0dp"
android:layout_weight="3"
android:gravity="center_horizontal"
android:orientation="vertical"
android:layout_gravity="center_vertical"
android:layout_height="wrap_content">
<ImageView
android:layout_width="60dp"
android:layout_height="60dp"
android:src="#mipmap/menu"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/text_menu"
android:layout_marginTop="5dp"
android:textSize="12sp"
android:textColor="#FFF"
android:text="Menu"/>
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3"
android:onClick="showHome"
android:gravity="center_horizontal"
android:orientation="vertical"
android:layout_gravity="center_vertical">
<ImageView
android:layout_width="60dp"
android:layout_height="60dp"
android:src="#mipmap/home"/>
<TextView
android:id="#+id/text_home"
android:layout_marginTop="5dp"
android:textSize="12sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FFF"
android:text="Home"
/>
</LinearLayout>
<LinearLayout
android:onClick="showSimulation"
android:layout_width="0dp"
android:layout_weight="3"
android:gravity="center_horizontal"
android:orientation="vertical"
android:layout_gravity="center_vertical"
android:layout_height="wrap_content">
<ImageView
android:layout_width="60dp"
android:layout_height="60dp"
android:src="#mipmap/simulacao"
/>
<TextView
android:id="#+id/text_simulation"
android:layout_marginTop="5dp"
android:layout_width="wrap_content"
android:textSize="12sp"
android:layout_height="wrap_content"
android:textColor="#FFF"
android:text="Simulação"
/>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_below="#id/top_bar">
<View
android:layout_width="match_parent"
android:layout_height="10dp"
android:background="#drawable/shadow"/>
<FrameLayout
android:id="#+id/fragment_holder"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFF"
android:layout_marginBottom="#dimen/activity_vertical_margin">
</FrameLayout>
</LinearLayout>
</RelativeLayout>
nav_header_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:background="#FFF"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal">
<ImageView
android:id="#+id/drawer_avatar"
android:layout_marginTop="20dp"
android:layout_width="115dp"
android:layout_height="115dp" />
<TextView
android:id="#+id/full_name"
android:layout_width="180dp"
android:gravity="center"
android:textColor="#color/colorDarkGray"
android:layout_height="wrap_content"
android:textSize="20sp"
android:layout_marginBottom="20dp"
android:layout_marginTop="10dp"
/>
<Button
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#color/colorLightGray"
android:text="Sobre o App"
android:id="#+id/button_about"
android:textColor="#color/colorPurple"
android:textSize="#dimen/normal_text"
android:textAllCaps="false"
/>
<Button
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#color/colorWhite"
android:text="Como usar o App"
android:id="#+id/button_how_to_use"
android:textColor="#color/colorPurple"
android:textSize="#dimen/normal_text"
android:textAllCaps="false"
/>
<Button
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#color/colorLightGray"
android:text="Adicionar Conta Bancaria?"
android:id="#+id/button_add_account"
android:textColor="#color/colorPurple"
android:textSize="#dimen/normal_text"
android:textAllCaps="false"
/>
<Button
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#color/colorWhite"
android:text="Alterar Cadastro?"
android:id="#+id/button_change_register"
android:textColor="#color/colorPurple"
android:textSize="#dimen/normal_text"
android:textAllCaps="false"
/>
<Button
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#color/colorLightGray"
android:text="Alterar Senha?"
android:id="#+id/button_change_password"
android:textColor="#color/colorPurple"
android:textSize="#dimen/normal_text"
android:textAllCaps="false"
/>
<Button
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#color/colorWhite"
android:text="Ajuda"
android:id="#+id/button_help"
android:textColor="#color/colorPurple"
android:textSize="#dimen/normal_text"
android:textAllCaps="false"
/>
<Button
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#color/colorLightGray"
android:text="Sair"
android:id="#+id/button_exit"
android:textColor="#color/colorPurple"
android:textSize="#dimen/normal_text"
android:textAllCaps="false"
/>
<TextView
android:layout_marginTop="50dp"
android:layout_marginBottom="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Copyright"
android:textColor="#color/colorGray"
/>
</LinearLayout>
The error log is:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: wagner.com.meuartesanato, PID: 9112
java.lang.RuntimeException: Unable to start activity ComponentInfo{wagner.com.meuartesanato/wagner.com.meuartesanato.home.MainActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.support.design.widget.NavigationView.setNavigationItemSelectedListener(android.support.design.widget.NavigationView$OnNavigationItemSelectedListener)'
on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.support.design.widget.NavigationView.setNavigationItemSelectedListener(android.support.design.widget.NavigationView$OnNavigationItemSelectedListener)'
on a null object reference
at wagner.com.meuartesanato.home.MainActivity.loadDrawer(MainActivity.java:59)
at wagner.com.meuartesanato.home.MainActivity.onCreate(MainActivity.java:41)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
I really don't know why i'm getting null pointer exception.
Thanks, for the answers!

The stack trace clearly says what is missing. You could have actually found out the programming error by carefully reviewing your code. Anyways modify the following line in your onCreate method. You were inflating the wrong layout
What it is now - setContentView(R.layout.activity_main);
What you should change it to - setContentView(R.layout.activity_home);

Related

Why I can't run the two activities together? the two activities and the image shows that I reached MainActivity directly without clicking homebutton

knowing that there is no errors, only MainActivity shows without homebutton................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................
MainActivity.java
package com.example.AppCalculator;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
EditText etfirstvalue,etsecondvalue;
Button btnadd,btnsubs,btnmultiply,btndivide;
Double num1,num2;
TextView tvresult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etfirstvalue=findViewById(R.id.etfirstvalue);
etsecondvalue=findViewById(R.id.etsecondvalue);
btnadd=findViewById(R.id.btnadd);
btndivide=findViewById(R.id.btndivision);
btnmultiply=findViewById(R.id.btnmultiply);
btnsubs=findViewById(R.id.btnsubs);
tvresult=findViewById(R.id.tvresult);
Clicklistener();
}
public void Clicklistener(){
btnadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
num1=Double.parseDouble(etfirstvalue.getText().toString());
num2=Double.parseDouble(etsecondvalue.getText().toString());
Double result=num1+num2;
tvresult.setText(String.valueOf(result));
}
});
btnsubs.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
num1=Double.parseDouble(etfirstvalue.getText().toString());
num2=Double.parseDouble(etsecondvalue.getText().toString());
Double result=num1-num2;
tvresult.setText(String.valueOf(result));
}
});
btnmultiply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
num1=Double.parseDouble(etfirstvalue.getText().toString());
num2=Double.parseDouble(etsecondvalue.getText().toString());
Double result=num1*num2;
tvresult.setText(String.valueOf(result));
}
});
btndivide.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
num1=Double.parseDouble(etfirstvalue.getText().toString());
num2=Double.parseDouble(etsecondvalue.getText().toString());
Double result=num1/num2;
tvresult.setText(String.valueOf(result));
}
});
}
}
MainActivity.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="#FFFFFF"
android:backgroundTint="#FFFFFF"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:gravity="center"
android:text="Simple Calculator"
android:textSize="25sp" />
<EditText
android:id="#+id/etfirstvalue"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:hint="Enter First Value"
android:inputType="number" />
<EditText
android:id="#+id/etsecondvalue"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:hint="Enter Second Value"
android:inputType="number" />
<TextView
android:id="#+id/tvresult"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:gravity="center"
android:text="Result"
android:textColor="#color/purple_500"
android:textSize="20sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_marginHorizontal="10dp"
android:orientation="horizontal"
android:weightSum="2">
<Button
android:id="#+id/btnadd"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginHorizontal="10dp"
android:layout_weight="1"
android:backgroundTint="#color/purple_500"
android:text="ADD" />
<Button
android:id="#+id/btnsubs"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginHorizontal="10dp"
android:layout_weight="1"
android:backgroundTint="#color/purple_500"
android:text="Subs" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_marginHorizontal="10dp"
android:orientation="horizontal"
android:weightSum="2">
<Button
android:id="#+id/btnmultiply"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginHorizontal="10dp"
android:layout_weight="1"
android:backgroundTint="#color/purple_500"
android:text="Multiply" />
<Button
android:id="#+id/btndivision"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginHorizontal="10dp"
android:layout_weight="1"
android:backgroundTint="#color/purple_500"
android:text="Divide" />
</LinearLayout>
</LinearLayout>
homebutton.java
package com.example.AppCalculator;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class homebutton extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.homebutton);
Button btncalc=findViewById(R.id.btncalc);
btncalc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(homebutton.this, MainActivity.class);
startActivity(intent);
}
});
}
}
homebutton.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"
tools:context=".homebutton"
tools:ignore="ExtraText">
<Button
android:id="#+id/btncalc"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginHorizontal="10dp"
android:layout_weight="1"
android:backgroundTint="#color/purple_500"
android:text="Calculator" />
</LinearLayout>
You need to clarify your question more. However I believe you meant homebutton should start first and after you click calculate it should take you to the second one.
If that's the case, then you need to define your start activity from the AndroidManifest because currently your app is starting on MainActivity.java

androidx.recyclerview.widget.RecyclerView cannot be cast to android.widget.LinearLayout

When I click Update Faculty (MaterialCardView) in the activity_main.xml the activity activity_update_faculty.xml suppose to display but my app crashes and closes, I tried to find the problem in the logcat and it says "androidx.recyclerview.widget.RecyclerView cannot be cast to android.widget.LinearLayout" I'm struggling to find the problem since I'm still new. Can someone help me, please
Here's is the activity_main.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:gravity="center"
android:orientation="horizontal">
<com.google.android.material.card.MaterialCardView
android:id="#+id/addNotice"
android:layout_width="130dp"
android:layout_height="150dp"
android:layout_margin="10dp"
app:cardElevation="5dp">
<LinearLayout
android:layout_width="135dp"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<ImageView
android:layout_width="64dp"
android:layout_height="64dp"
android:background="#drawable/circle_green"
android:padding="15dp"
android:src="#drawable/ic_notice" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginTop="10dp"
android:background="#color/lightGray" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:padding="5dp"
android:text="Upload Notice"
android:textColor="#color/textColor"
android:textStyle="bold" />
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
<com.google.android.material.card.MaterialCardView
android:id="#+id/addGalleryImage"
android:layout_width="130dp"
android:layout_height="150dp"
android:layout_margin="10dp"
app:cardElevation="5dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<ImageView
android:layout_width="64dp"
android:layout_height="64dp"
android:background="#drawable/circle_purple"
android:padding="15dp"
android:src="#drawable/ic_gallery"/>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginTop="10dp"
android:background="#color/lightGray"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:padding="5dp"
android:text="Upload Image"
android:textColor="#color/textColor"
android:textStyle="bold"/>
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:gravity="center"
android:orientation="horizontal">
<com.google.android.material.card.MaterialCardView
android:id="#+id/addEbook"
android:layout_width="130dp"
android:layout_height="150dp"
android:layout_margin="10dp"
app:cardElevation="5dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<ImageView
android:layout_width="64dp"
android:layout_height="64dp"
android:background="#drawable/circle_pink"
android:padding="15dp"
android:src="#drawable/ic_upload"/>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginTop="10dp"
android:background="#color/lightGray"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:padding="5dp"
android:text="Upload Ebook"
android:textColor="#color/textColor"
android:textStyle="bold"/>
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
<com.google.android.material.card.MaterialCardView
android:id="#+id/faculty"
android:layout_width="130dp"
android:layout_height="150dp"
android:layout_margin="10dp"
app:cardElevation="5dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<ImageView
android:layout_width="64dp"
android:layout_height="64dp"
android:background="#drawable/circle_yellow"
android:padding="15dp"
android:src="#drawable/ic_group"/>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginTop="10dp"
android:background="#color/lightGray"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:padding="5dp"
android:text="Update Faculty"
android:textColor="#color/textColor"
android:textStyle="bold"/>
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:gravity="center"
android:orientation="horizontal">
<com.google.android.material.card.MaterialCardView
android:id="#+id/deleteNotice"
android:layout_width="130dp"
android:layout_height="150dp"
android:layout_margin="10dp"
app:cardElevation="5dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<ImageView
android:layout_width="64dp"
android:layout_height="64dp"
android:background="#drawable/cicle_red"
android:padding="15dp"
android:src="#drawable/ic_delete"/>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginTop="10dp"
android:background="#color/lightGray"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:padding="5dp"
android:text="Delete Notice"
android:textColor="#color/textColor"
android:textStyle="bold"/>
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
</LinearLayout>
</LinearLayout>
Here is the MainActivity.java :
package com.example.adminuniversityapp;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import com.example.adminuniversityapp.facculty.UpdateFaculty;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
CardView uploadNptice, addGalleryImage, addEbook, faculty;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uploadNptice = findViewById(R.id.addNotice);
addGalleryImage = findViewById(R.id.addGalleryImage);
addEbook = findViewById(R.id.addEbook);
faculty = findViewById(R.id.faculty);
uploadNptice.setOnClickListener(this);
addGalleryImage.setOnClickListener(this);
addEbook.setOnClickListener(this);
faculty.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent intent;
switch (v.getId()){
case R.id.addNotice:
intent = new Intent( MainActivity.this,UploadNotice.class);
startActivity(intent);
break;
case R.id.addGalleryImage:
intent = new Intent( MainActivity.this,UploadImage.class);
startActivity(intent);
break;
case R.id.addEbook:
intent = new Intent( MainActivity.this,UploadPdfActivity.class);
startActivity(intent);
break;
case R.id.faculty:
intent = new Intent( MainActivity.this, UpdateFaculty.class);
startActivity(intent);
break;
}
}
}
activity_update_faculty.xml :
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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=".facculty.UpdateFaculty">
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/fab"
style="#style/Widget.Design.FloatingActionButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|right"
android:layout_margin="16dp"
android:src="#drawable/ic_add"
app:elevation="3dp"
app:fabSize="normal"/>
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:gravity="center"
android:text="Computer Science"
android:textColor="#color/textColor"
android:textSize="22sp"
android:textStyle="bold"/>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginVertical="8dp"
android:background="#c1c1c1"/>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/csDepartment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:nestedScrollingEnabled="false"
android:visibility="gone"/>
<LinearLayout
android:id="#+id/csNoData"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<include layout="#layout/no_data_found"/>
</LinearLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:gravity="center"
android:text="Mechanical Engineering"
android:textColor="#color/textColor"
android:textSize="22sp"
android:textStyle="bold"/>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginVertical="8dp"
android:background="#c1c1c1"/>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/mechanicalDepartment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:nestedScrollingEnabled="false"
android:visibility="gone"/>
<LinearLayout
android:id="#+id/mechNoData"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<include layout="#layout/no_data_found"/>
</LinearLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:gravity="center"
android:text="Physics Department"
android:textColor="#color/textColor"
android:textSize="22sp"
android:textStyle="bold"/>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginVertical="8dp"
android:background="#c1c1c1"/>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/physicsDepatment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:nestedScrollingEnabled="false"
android:visibility="gone"/>
<LinearLayout
android:id="#+id/physicsNoData"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<include layout="#layout/no_data_found"/>
</LinearLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:gravity="center"
android:text="Chemistry Department"
android:textColor="#color/textColor"
android:textSize="22sp"
android:textStyle="bold"/>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginVertical="8dp"
android:background="#c1c1c1"/>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/chemistryDepatment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:nestedScrollingEnabled="false"
android:visibility="gone"/>
<LinearLayout
android:id="#+id/chemistryNoData"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<include layout="#layout/no_data_found"/>
</LinearLayout>
</LinearLayout>
</androidx.core.widget.NestedScrollView>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
**UpdateFaculty.java:
**
package com.example.adminuniversityapp.facculty;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.example.adminuniversityapp.R; // i had to import this from the other package in order for R.layout works
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class UpdateFaculty extends AppCompatActivity {
FloatingActionButton fab;
private RecyclerView csDepartment, mechanicalDepartment, physicalDepartment, chemistryDepartment;
private LinearLayout csNoData, mechNoData, physicsNoData, chemistryNoData;
private List<TeacherData> list, list2, list3, list4;
private TeacherAdapter adapter;
private DatabaseReference reference, dbRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_faculty);
csDepartment = findViewById(R.id.csDepartment);
mechanicalDepartment = findViewById(R.id.mechanicalDepartment);
physicalDepartment = findViewById(R.id.physicsDepatment);
chemistryDepartment = findViewById(R.id.chemistryDepatment);
csNoData = findViewById(R.id.csDepartment);
mechNoData = findViewById(R.id.mechNoData);
physicsNoData = findViewById(R.id.physicsNoData);
chemistryNoData = findViewById(R.id.chemistryNoData);
reference = FirebaseDatabase.getInstance().getReference().child("teacher");
csDepartment();
mechanicalDepartment();
physicalDepartment();
chemistryDepartment();
fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(UpdateFaculty.this, addTeacher.class));
}
});
}
private void csDepartment() {
dbRef = reference.child("Computer Science");
dbRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
list = new ArrayList<>();
if(!dataSnapshot.exists()){
csNoData.setVisibility(View.VISIBLE);
csDepartment.setVisibility(View.GONE);
} else {
csNoData.setVisibility(View.GONE);
csDepartment.setVisibility(View.VISIBLE);
for (DataSnapshot snapshot: dataSnapshot.getChildren()){
TeacherData data = snapshot.getValue(TeacherData.class);
list.add(data);
}
csDepartment.setHasFixedSize(true);
csDepartment.setLayoutManager(new LinearLayoutManager(UpdateFaculty.this));
adapter = new TeacherAdapter(list, UpdateFaculty.this);
csDepartment.setAdapter(adapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(UpdateFaculty.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void mechanicalDepartment() {
dbRef = reference.child("Mechanical");
dbRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
list2 = new ArrayList<>();
if(!dataSnapshot.exists()){
mechNoData.setVisibility(View.VISIBLE);
mechanicalDepartment.setVisibility(View.GONE);
} else {
mechNoData.setVisibility(View.GONE);
mechanicalDepartment.setVisibility(View.VISIBLE);
for (DataSnapshot snapshot: dataSnapshot.getChildren()){
TeacherData data = snapshot.getValue(TeacherData.class);
list2.add(data);
}
mechanicalDepartment.setHasFixedSize(true);
mechanicalDepartment.setLayoutManager(new LinearLayoutManager(UpdateFaculty.this));
adapter = new TeacherAdapter(list2, UpdateFaculty.this);
mechanicalDepartment.setAdapter(adapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(UpdateFaculty.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void physicalDepartment() {
dbRef = reference.child("Physics");
dbRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
list3 = new ArrayList<>();
if(!dataSnapshot.exists()){
physicsNoData.setVisibility(View.VISIBLE);
physicalDepartment.setVisibility(View.GONE);
} else {
physicsNoData.setVisibility(View.GONE);
physicalDepartment.setVisibility(View.VISIBLE);
for (DataSnapshot snapshot: dataSnapshot.getChildren()){
TeacherData data = snapshot.getValue(TeacherData.class);
list3.add(data);
}
physicalDepartment.setHasFixedSize(true);
physicalDepartment.setLayoutManager(new LinearLayoutManager(UpdateFaculty.this));
adapter = new TeacherAdapter(list3, UpdateFaculty.this);
physicalDepartment.setAdapter(adapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(UpdateFaculty.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void chemistryDepartment() {
dbRef = reference.child("Chemistry");
dbRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
list4 = new ArrayList<>();
if(!dataSnapshot.exists()){
chemistryNoData.setVisibility(View.VISIBLE);
chemistryDepartment.setVisibility(View.GONE);
} else {
chemistryNoData.setVisibility(View.GONE);
chemistryDepartment.setVisibility(View.VISIBLE);
for (DataSnapshot snapshot: dataSnapshot.getChildren()){
TeacherData data = snapshot.getValue(TeacherData.class);
list4.add(data);
}
chemistryDepartment.setHasFixedSize(true);
chemistryDepartment.setLayoutManager(new LinearLayoutManager(UpdateFaculty.this));
adapter = new TeacherAdapter(list4, UpdateFaculty.this);
chemistryDepartment.setAdapter(adapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(UpdateFaculty.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
Here is what it shows on the logcat right after I click the Update Faculty MaterialCardView :
2022-03-22 14:09:03.319 24645-24645/com.example.adminuniversityapp I/Timeline: Timeline: Activity_launch_request time:36107995
2022-03-22 14:09:03.344 24645-24702/com.example.adminuniversityapp V/FA: Recording user engagement, ms: 49869
2022-03-22 14:09:03.367 24645-24702/com.example.adminuniversityapp V/FA: Connecting to remote service
2022-03-22 14:09:03.369 24645-24671/com.example.adminuniversityapp V/FA: onActivityCreated
2022-03-22 14:09:03.373 24645-24702/com.example.adminuniversityapp V/FA: Connection attempt already in progress
2022-03-22 14:09:03.373 24645-24702/com.example.adminuniversityapp V/FA: Activity paused, time: 61111997
2022-03-22 14:09:03.375 24645-24645/com.example.adminuniversityapp D/DecorView[]: getWindowModeFromSystem windowmode is 1
2022-03-22 14:09:03.409 24645-24645/com.example.adminuniversityapp E/libc: Access denied finding property "ro.vendor.pref_scale_resolution"
2022-03-22 14:09:03.409 24645-24645/com.example.adminuniversityapp I/FloatingActionButton: Setting a custom background is not supported.
2022-03-22 14:09:03.411 24645-24645/com.example.adminuniversityapp E/libc: Access denied finding property "ro.vendor.pref_scale_resolution"
2022-03-22 14:09:03.468 24645-24645/com.example.adminuniversityapp E/libc: Access denied finding property "ro.vendor.pref_scale_resolution"
2022-03-22 14:09:03.509 24645-24645/com.example.adminuniversityapp D/AndroidRuntime: Shutting down VM
2022-03-22 14:09:03.513 24645-24645/com.example.adminuniversityapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.adminuniversityapp, PID: 24645
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.adminuniversityapp/com.example.adminuniversityapp.facculty.UpdateFaculty}: java.lang.ClassCastException: androidx.recyclerview.widget.RecyclerView cannot be cast to android.widget.LinearLayout
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3580)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3752)
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:2191)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:236)
at android.app.ActivityThread.main(ActivityThread.java:8049)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:620)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1011)
Caused by: java.lang.ClassCastException: androidx.recyclerview.widget.RecyclerView cannot be cast to android.widget.LinearLayout
at com.example.adminuniversityapp.facculty.UpdateFaculty.onCreate(UpdateFaculty.java:46)
csNoData = findViewById(R.id.csDepartment);
This is where the exception occurs. The reason is that the view with id csDepartment is a RecyclerView not a LinearLayout. Because of that, itcannot be cast to aLinearLayout`.
To solve it, replace that line of code with this:
csNoData = findViewById(R.id.csNoData);

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

Android ImageButton does not display image

I am new to java and I am developing a simple mediaplayer: I have problems with two image buttons: when i run the app the relative images are not displayed. This is my code:
JAVA:
package lukes.mediaplayer;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.app.Activity;
public class alpha extends Activity implements View.OnClickListener {
SeekBar seekBar_alpha;
ImageButton btPlay_alpha;
ImageButton btStop_alpha;
MediaPlayer mp;
Handler seekHandler = new Handler();
ImageView display;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alpha);
display = (ImageView) findViewById(R.id.imagetop);
display.setOnClickListener(this);
getInit();
seekUpdation();
}
public void getInit() {
seekBar_alpha = (SeekBar) findViewById(R.id.seekBar_alpha);
btPlay_alpha = (ImageButton) findViewById(R.id.btPlay_alpha);
btStop_alpha = (ImageButton) findViewById(R.id.btStop_alpha);
btPlay_alpha.setOnClickListener(this);
btStop_alpha.setOnClickListener(this);
mp = MediaPlayer.create(this, R.raw.alpha_audio);
seekBar_alpha.setMax(mp.getDuration());
}
Runnable run = new Runnable() {
#Override
public void run() {
seekUpdation();
}
};
public void seekUpdation() {
seekBar_alpha.setProgress(mp.getCurrentPosition());
seekHandler.postDelayed(run, 1000);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.imagetop:
Intent intent = new Intent (alpha.this, alpha_img.class);
startActivity(intent);
case R.id.btPlay_alpha:
mp.start();
break;
case R.id.btStop_alpha:
mp.pause();
}
}
#Override
protected void onPause(){
super.onPause();
if (mp!=null && mp.isPlaying()){
mp.pause();
}
}
}
The "btPlay_alpha" and "btStop_alpha" image buttons does not display their image. Can you help me to fix that? Thank you!
Hey guys, I add the XML code:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
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:fitsSystemWindows="true"
tools:context=".alpha">
<android.support.design.widget.AppBarLayout
android:id="#+id/main.appbar"
android:layout_width="match_parent"
android:layout_height="350dp"
android:fitsSystemWindows="true"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/main.collapsing"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:expandedTitleMarginEnd="64dp"
app:expandedTitleMarginStart="48dp"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<android.support.v7.widget.Toolbar
android:id="#+id/main.toolbar"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_collapseMode="pin"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<ImageButton
android:id="#+id/imagetop"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/black"
android:fitsSystemWindows="true"
android:scaleType="centerCrop"
android:src="#drawable/alpha"
app:layout_collapseMode="parallax" />
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
app:cardElevation="5dp"
app:cardUseCompatPadding="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/textView3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-condensed"
android:lineSpacingExtra="8dp"
android:padding="16dp"
android:text="#string/alpha_title"
android:textColor="#color/colorPrimary"
android:textSize="24sp"
android:textStyle="bold" />
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:paddingLeft="16dp"
android:paddingRight="16dp">
<ImageButton
android:id="#+id/btStop_alpha"
android:layout_width="60dp"
android:layout_height="55dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:backgroundTint="#color/lightRed"
android:elevation="6dp"
android:padding="16dp"
app:srcCompat="#android:drawable/ic_media_pause" />
<ImageButton
android:id="#+id/btPlay_alpha"
android:layout_width="60dp"
android:layout_height="55dp"
android:layout_alignParentTop="true"
android:layout_gravity="center"
android:layout_toEndOf="#+id/btStop_alpha"
android:layout_toRightOf="#+id/btStop_alpha"
android:backgroundTint="#color/lightRed"
android:elevation="6dp"
app:srcCompat="#android:drawable/ic_media_play" />
<SeekBar
android:id="#+id/seekBar_alpha"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toEndOf="#+id/btPlay_alpha"
android:layout_toRightOf="#+id/btPlay_alpha"
android:max="100" />
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="serif"
android:lineSpacingExtra="8dp"
android:padding="16dp"
android:text="#string/alpha_text"
android:textSize="18sp" />
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
</android.support.design.widget.CoordinatorLayout>
Thank you for your support!
I see youre extending Activity Instead of AppCompatActivity. In your xml, you are setting attribute srcCompat; make sure As of Android Support Library 23.3.0, support vector drawables can only be loaded via app:srcCompat .
you need to add vectorDrawables.useSupportLibrary = true to your build.gradle file
// Gradle Plugin 2.0+
android {
defaultConfig {
vectorDrawables.useSupportLibrary = true
}
}

button BACK to a collapsingToolbar - Android

It happens that from my main activity I call an activity in that activity that I call tale with collapsingToolbar, well everything works fine only that I can not give BACK because the collapsinToolbar does not generate a button back.
Java code of the main activity
package com.herprogramacion.alquileres;
import android.database.Cursor;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import com.herprogramacion.alquileres.provider.Contrato.Alquileres;
public class ActividadListaAlquileres extends AppCompatActivity implements AdaptadorAlquileres.OnItemClickListener, LoaderManager.LoaderCallbacks<Cursor> {
private RecyclerView listaUI;
private LinearLayoutManager linearLayoutManager;
private AdaptadorAlquileres adaptador;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.actividad_lista_alquileres);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Filtro...", Snackbar.LENGTH_LONG)
.setAction("Acción", null).show();
}
});
// Preparar lista
listaUI = (RecyclerView) findViewById(R.id.lista);
listaUI.setHasFixedSize(true);
linearLayoutManager = new LinearLayoutManager(this);
listaUI.setLayoutManager(linearLayoutManager);
adaptador = new AdaptadorAlquileres(this, this);
listaUI.setAdapter(adaptador);
// Iniciar loader
getSupportLoaderManager().restartLoader(1, null, this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_actividad_lista_alquileres, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(AdaptadorAlquileres.ViewHolder holder, String idAlquiler) {
// Snackbar.make(findViewById(android.R.id.content), ":id = " + idAlquiler,
// Snackbar.LENGTH_LONG).show();
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
return new CursorLoader(this, Alquileres.URI_CONTENIDO, null, null, null, null);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
if (adaptador != null) {
adaptador.swapCursor(data);
}
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
}
}
Java code of the activity where I generate the collapsingToolbar
package com.herprogramacion.alquileres;
import android.content.Intent;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
public class biografia2 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_biografia2);
CollapsingToolbarLayout collapsingToolbar =
(CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
collapsingToolbar.setTitle("Titulo ");
}
}
Xml code of my main activity
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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:fitsSystemWindows="true"
tools:context="com.herprogramacion.alquileres.ActividadListaAlquileres">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/contenido_actividad_lista_alquileres" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:src="#drawable/icono_filtro" />
</android.support.design.widget.CoordinatorLayout>
Xml code of the activity where I generate the collapsingToolbar
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="#dimen/detail_backdrop_height"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:fitsSystemWindows="true">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_scrollFlags="scroll|exitUntilCollapsed"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:expandedTitleMarginStart="48dp"
app:expandedTitleMarginEnd="64dp" >
<ImageView
android:id="#+id/backdrop"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:fitsSystemWindows="true"
app:layout_collapseMode="parallax"
android:src="#drawable/jack"
android:alpha="0.5"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="170dp"
android:layout_gravity="center">
</RelativeLayout>
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:layout_collapseMode="pin" />
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingTop="24dp">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="#dimen/card_margin">
<LinearLayout
style="#style/Widget.CardContent"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Info"
android:textAppearance="#style/TextAppearance.AppCompat.Title" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/lorem_ipsum" />
</LinearLayout>
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/card_margin"
android:layout_marginLeft="#dimen/card_margin"
android:layout_marginRight="#dimen/card_margin">
<LinearLayout
style="#style/Widget.CardContent"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Friends"
android:textAppearance="#style/TextAppearance.AppCompat.Title" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/lorem_ipsum" />
</LinearLayout>
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/card_margin"
android:layout_marginLeft="#dimen/card_margin"
android:layout_marginRight="#dimen/card_margin">
<LinearLayout
style="#style/Widget.CardContent"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Related"
android:textAppearance="#style/TextAppearance.AppCompat.Title" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/lorem_ipsum" />
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
<android.support.design.widget.FloatingActionButton
android:layout_height="wrap_content"
android:layout_width="wrap_content"
app:layout_anchor="#id/appbar"
app:layout_anchorGravity="bottom|right|end"
android:src="#drawable/ic_discuss"
android:layout_margin="#dimen/fab_margin"
android:clickable="true"/>
</android.support.design.widget.CoordinatorLayout>
You can add back navigation icon in the xml for Toolbar component using app:navigationIcon attribute.
<android.support.v7.widget.Toolbar
android:id="#+id/materialup.toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?attr/actionBarSize"
app:layout_scrollFlags="scroll"
app:navigationIcon="?homeAsUpIndicator" />
You should be able to show the default back button using setDisplayHomeAsUpEnabled:
final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);

Categories