Recycler View Null Pointer Exception [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 1 year ago.
**I am new to android studio and java
I'm trying to bind a button to an activity that contains a recycler view and the adapter that comes with it. The problem is when I click on the button the activity crashes. I know the button is not the problem because I have a different activity that uses a button and goes to the activity.
The problem is in either the activity for the recycler view which is named EdwardActivity or the adapter and I can't seem to figure it out.
Error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.edu.pfrfitness, PID: 10520
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.edu.pfrfitness/com.edu.pfrfitness.EdwardActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setLayoutManager(androidx.recyclerview.widget.RecyclerView$LayoutManager)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setLayoutManager(androidx.recyclerview.widget.RecyclerView$LayoutManager)' on a null object reference
at com.edu.pfrfitness.EdwardActivity.onCreate(EdwardActivity.java:31)
at android.app.Activity.performCreate(Activity.java:8000)
at android.app.Activity.performCreate(Activity.java:7984)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:223) 
at android.app.ActivityThread.main(ActivityThread.java:7656) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947) 
I/Process: Sending signal. PID: 10520 SIG: 9
Activity for recycler(named Edward Activity):
package com.edu.pfrfitness;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
public class EdwardActivity extends AppCompatActivity {
RecyclerView recyclerView;
String s1[], s2[];
int images [] = {R.drawable.black, R.drawable.black, R.drawable.black, R.drawable.black, R.drawable.black, R.drawable.black};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_row);
recyclerView = findViewById(R.id.recyclerView);
s1 = getResources() .getStringArray(R.array.Navigation_List);
s2 = getResources() .getStringArray(R.array.description);
MyAdapter myAdapter = new MyAdapter(this, s1, s2, images);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(myAdapter);
//call recycler
}
public void Recycler(){
}
}
Adapter:
package com.edu.pfrfitness;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
String data1[], data2[];
int images[];
Context context;
public MyAdapter(Context ct, String s1[], String s2[], int img[]) {
context = ct;
data1 = s1;
data2 = s2;
images = img;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.my_row, parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.edwardText1.setText(data1[position]);
holder.edwardText2.setText(data2[position]);
holder.edwardImageView.setImageResource(images[position]);
}
#Override
public int getItemCount() {
return images.length;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView edwardText1, edwardText2;
ImageView edwardImageView;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
edwardText1 = itemView.findViewById(R.id.edwardText1);
edwardText2 = itemView.findViewById(R.id.edwardText2);
edwardImageView = itemView.findViewById(R.id.edwardImageView);
}
}
}
My row so like how each row will look:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:ignore="MissingConstraints">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/edwardImageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:srcCompat="#tools:sample/avatars" />
<TextView
android:id="#+id/edwardText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginTop="10dp"
android:text="Navigation_List"
android:textSize="24sp"
android:textStyle="bold"
app:layout_constraintStart_toEndOf="#+id/edwardImageView"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/edwardText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="description"
android:textSize="16sp"
app:layout_constraintStart_toStartOf="#+id/edwardText1"
app:layout_constraintTop_toBottomOf="#+id/edwardText1" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
</androidx.constraintlayout.widget.ConstraintLayout>

Error explanation:
According to the error you are trying to call setLayoutManager function on a null object. So, your variable "recyclerView" is obviously null.
Reason:
The reason is that in your activity you do this:
setContentView(R.layout.my_row);
and you use the file "my_row.xml" to create your Activity layout. But, in this layout there is no view with id recyclerView. So, when you do this:
recyclerView = findViewById(R.id.recyclerView);
then variable recyclerView is set to null.
Solution:
I guess that by mistake you used file "my_row.xml" as the Activity's layout, since this layout was obviously created fot the adapter's items. You should instead use another layout for the Activity's layout by passing it in your setContent in Activity's onCreate.

Related

FATAL EXCEPTION: main in Android studio

Hey Everyone this is my first android app I'm new in Android development. When I try to run this app on my device suddenly it crashes.
And my app crash when I try to log in
This is the main code of JAVA
package com.example.javanots;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.firebase.ui.firestore.FirestoreRecyclerAdapter;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirestoreRegistrar;
import com.google.firebase.firestore.Query;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
import java.text.BreakIterator;
public class NotesActivity extends AppCompatActivity {
FloatingActionButton mcreatenotefab;
private FirebaseAuth firebaseAuth;
RecyclerView mrecyclerview;
StaggeredGridLayoutManager staggeredGridLayoutManager;
FirebaseUser firebaseUser;
FirebaseFirestore firebaseFirestore;
FirestoreRecyclerAdapter<firebasemodel,NoteViewHolder> noteAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notes);
mcreatenotefab=findViewById(R.id.createnotefab);
firebaseAuth=FirebaseAuth.getInstance();
//Get Data From Particular User Not from All user
firebaseUser=FirebaseAuth.getInstance().getCurrentUser();
firebaseFirestore=FirebaseFirestore.getInstance();
getSupportActionBar().setTitle("All Notes");
mcreatenotefab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(NotesActivity.this,Createnote.class));
}
});
//For Get All notes of User
Query query = firebaseFirestore.collection("notes").document(firebaseUser.getUid()).collection("mynotes").orderBy("title",Query.Direction.ASCENDING);
FirestoreRecyclerOptions<firebasemodel> allusernotes = new FirestoreRecyclerOptions.Builder<firebasemodel>().setQuery(query,firebasemodel.class).build();
noteAdapter = new FirestoreRecyclerAdapter<firebasemodel, NoteViewHolder>(allusernotes) {
#Override
protected void onBindViewHolder(#NonNull NoteViewHolder noteViewHolder, int position, #NonNull firebasemodel firebasemodel) {
noteViewHolder.notetitle.setText(firebasemodel.getTitle());
noteViewHolder.notecontent.setText(firebasemodel.getContent());
}
#NonNull
#Override
public NoteViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.notes_layout,parent,false);
return new NoteViewHolder(view);
}
};
setContentView(R.layout.notes_layout);
mrecyclerview.findViewById(R.id.recyclerview);
mrecyclerview.setHasFixedSize(true);
staggeredGridLayoutManager=new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL);
mrecyclerview.setLayoutManager(staggeredGridLayoutManager);
mrecyclerview.setAdapter(noteAdapter);
}
public class NoteViewHolder extends RecyclerView.ViewHolder
{
private TextView notetitle;
private TextView notecontent;
LinearLayout mnote;
public NoteViewHolder(#NonNull View itemView) {
super(itemView);
notetitle=itemView.findViewById(R.id.notetitel);
notecontent=itemView.findViewById(R.id.notecontent);
mnote=itemView.findViewById(R.id.note);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId())
{
case R.id.logout: firebaseAuth.signOut();
finish();
startActivity(new Intent(NotesActivity.this,MainActivity.class));
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onStart() {
super.onStart();
noteAdapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
noteAdapter.startListening();
if(noteAdapter!=null)
{
noteAdapter.startListening();
}
}
}
This is my XML codes
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".NotesActivity">
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/createnotefab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"
android:layout_gravity="bottom|end"
android:layout_marginRight="30dp"
android:layout_marginBottom="30dp"
android:background="#A1F4FB"
android:src="#drawable/ic_baseline_add_24"
app:maxImageSize="40dp">
</com.google.android.material.floatingactionbutton.FloatingActionButton>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:scrollbars="vertical">
</androidx.recyclerview.widget.RecyclerView>
</RelativeLayout>
I'm getting a List of Error I don't know how to solve it
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.javanots, PID: 24241
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.javanots/com.example.javanots.NotesActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View androidx.recyclerview.widget.RecyclerView.findViewById(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3835)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:4011)
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:2325)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:246)
at android.app.ActivityThread.main(ActivityThread.java:8633)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View androidx.recyclerview.widget.RecyclerView.findViewById(int)' on a null object reference
at com.example.javanots.NotesActivity.onCreate(NotesActivity.java:86)
at android.app.Activity.performCreate(Activity.java:8207)
at android.app.Activity.performCreate(Activity.java:8191)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3808)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:4011) 
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:2325) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:246) 
at android.app.ActivityThread.main(ActivityThread.java:8633) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:602) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1130)
Please Explain My problem's solution.
You are trying to call "findViewById" on mrecyclerview, that's not initialized yet (it's value is null).
It seems you are trying to do the right (bind the recyclerview), but the wrong way.
Give it a try by changing
mrecyclerview.findViewById(R.id.recyclerview);
to
mrecyclerview = (RecyclerView) findViewById(R.id.recyclerview);
After that, you'll be able to call methods on recyclerview, like .setAdapter(), ...
You had declared an object by the name mrecyclerview right? In line 86 of your code, instead of mrecyclerview.findViewById(R.id.recyclerview), try mrecyclerview = findViewById(R.id.recyclerview). Your error lines show that the problem was caused by a NullPointerException - Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View androidx.recyclerview.widget.RecyclerView.findViewById(int)' on a null object reference

Can't set text to TextView in Android Studio

I had this problem with every TextView. I tried a lot of things but i just can't manage to make it work. If you have any suggestion, please help.
I'm begginer in android but I think this is simple problem, but i just can't fix it.
Thanks in advance.
Code for fragment Home
package com.example.mmreviews;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class HomeFragment extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
LayoutInflater lf = getActivity().getLayoutInflater();
View view = lf.inflate(R.layout.fragment_home, container, false);
view.findViewById(R.id.btn_edit).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getFragmentManager().beginTransaction().replace(R.id.fragment_container, new EditFragment()).commit();
}
});
view.findViewById(R.id.btn_logout).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), LogIn.class);
startActivity(intent);
}
});
TextView textViewUsernameInfo = view.findViewById(R.id.username);
textViewUsernameInfo.setText("Some text");
return view;
}
}
Xml for text i want to set. Maybe i should try some other text view?
<TextView
android:id="#+id/username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toEndOf="#id/text1"
android:layout_toRightOf="#id/text1"
android:textColor="#4B83E5"
android:textSize="16sp">
</TextView>
exception that I get
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.mmreviews, PID: 6184
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.mmreviews/com.example.mmreviews.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2957)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6944)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.example.mmreviews.HomeFragment.onCreateView(HomeFragment.java:38)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2600)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:881)
at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1238)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1303)
at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:439)
at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManagerImpl.java:2079)
at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1869)
at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1824)
at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManagerImpl.java:1727)
at androidx.fragment.app.FragmentManagerImpl.dispatchStateChange(FragmentManagerImpl.java:2663)
at androidx.fragment.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManagerImpl.java:2613)
at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:246)
at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:542)
at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:210)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1340)
at android.app.Activity.performStart(Activity.java:7200)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2920)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032) 
at android.app.ActivityThread.-wrap11(Unknown Source:0) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696) 
at android.os.Handler.dispatchMessage(Handler.java:105) 
at android.os.Looper.loop(Looper.java:164) 
at android.app.ActivityThread.main(ActivityThread.java:6944) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374) 
Try this:
TextView textViewUsernameInfo = (TextView)view.findViewById(R.id.username);
textViewUsernameInfo.setText("Some text");
For some reason, you have two inflaters
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
//LayoutInflater inflater also inflater, but you decalre another inflater
LayoutInflater lf = getActivity().getLayoutInflater();
//and i assume you try to get lf LayoutInflater from Activity not from Fragment
View view = lf.inflate(R.layout.fragment_home, container, false);
...
}
Try to remove
LayoutInflater lf = getActivity().getLayoutInflater();
and change your view to
assert inflater != null;//not required but try to add
View view = inflater.inflate(R.layout.fragment_home, container, false);
According to docs: onCreateView(LayoutInflater, ViewGroup, Bundle) creates and returns the view hierarchy associated with the fragment and LayoutInflater object can be used to inflate any views in the fragment.
Docs about fragment
UPD: I won't able to recreate your error.
I created simple XML for the main activity and for fragment separately
main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.fragment.app.FragmentContainerView
android:id="#+id/fragmentContainerView"
android:name="com.example.test.MainFragment"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
main_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainFragment">
<TextView
android:id="#+id/username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#4B83E5"
android:textSize="16sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
</TextView>
<Button
android:id="#+id/btn_edit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<Button
android:id="#+id/btn_logout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Created Fragment class and left MainActivity with default
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.main_activity);
}
}
Fragment class
public class MainFragment extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.main_fragment, container, false);
Button button1 = view.findViewById(R.id.btn_edit);
button1.setOnClickListener(v -> Toast.makeText (requireContext (),"short1",Toast.LENGTH_SHORT).show ());
Button button2 = view.findViewById(R.id.btn_logout);
button2.setOnClickListener(v -> Toast.makeText (requireContext (),"short2",Toast.LENGTH_SHORT).show ());
TextView textViewUsernameInfo = view.findViewById(R.id.username);
textViewUsernameInfo.setText("Some text");
return view;
}}
It is working fine without throwing NullPointerException for me.
You can try ViewBinding from Android Devs or ButterKnife third-party library from JakeWharton (it is deprecated as for 2021 and wouldn't have further updates, because ViewBinding does the same - still you can use it.)

Error: Binary XML file line #9 in com.example.myfragment:layout/activity_main: Error inflating class fragment

I have been trying to put a recycler view inside a fragment and displaying the fragment in the main activity in Android Studio. It kept giving me and error inflating class fragment error. I don't know if it's the XML or the fragment code that contains the problems.
Error Code
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myfragment, PID: 11025
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myfragment/com.example.myfragment.MainActivity}: android.view.InflateException: Binary XML file line #9 in com.example.myfragment:layout/activity_main: Binary XML file line #9 in com.example.myfragment:layout/activity_main: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3270)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
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:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
Caused by: android.view.InflateException: Binary XML file line #9 in com.example.myfragment:layout/activity_main: Binary XML file line #9 in com.example.myfragment:layout/activity_main: Error inflating class fragment
Caused by: android.view.InflateException: Binary XML file line #9 in com.example.myfragment:layout/activity_main: Error inflating class fragment
Caused by: java.lang.IllegalArgumentException: Binary XML file line #9: Must specify unique android:id, android:tag, or have a parent with an id for com.example.myfragment.AddExerciseFragment
at androidx.fragment.app.FragmentManagerImpl.onCreateView(FragmentManagerImpl.java:3177)
at androidx.fragment.app.FragmentController.onCreateView(FragmentController.java:134)
at androidx.fragment.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:357)
at androidx.fragment.app.FragmentActivity.onCreateView(FragmentActivity.java:336)
at android.view.LayoutInflater.tryCreateView(LayoutInflater.java:1069)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:997)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:961)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:1123)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1084)
at android.view.LayoutInflater.inflate(LayoutInflater.java:682)
at android.view.LayoutInflater.inflate(LayoutInflater.java:534)
at android.view.LayoutInflater.inflate(LayoutInflater.java:481)
at com.android.internal.policy.PhoneWindow.setContentView(PhoneWindow.java:438)
at android.app.Activity.setContentView(Activity.java:3324)
at com.example.myfragment.MainActivity.onCreate(MainActivity.java:18)
at android.app.Activity.performCreate(Activity.java:7802)
at android.app.Activity.performCreate(Activity.java:7791)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3245)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
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:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
Here is my activity main
package com.example.myfragment;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
activity_main
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<fragment
android:name="com.example.myfragment.AddExerciseFragment"
tools:layout="#layout/add_exercise_fragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:ignore="MissingConstraints"/>
</androidx.constraintlayout.widget.ConstraintLayout>
Fragment Code
package com.example.myfragment;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class AddExerciseFragment extends Fragment{
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
MainActivity activity;
View view;
public AddExerciseFragment(MainActivity activity) {
this.activity = activity;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.add_exercise_fragment,container,false);
mRecyclerView = view.findViewById(R.id.recyclerView);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mAdapter = new ExampleAdapter(activity);
mRecyclerView.setAdapter(mAdapter);
return view;
}
}
Fragment XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/darker_gray"
android:padding="4dp"
android:scrollbars="vertical" />
</RelativeLayout>
Example Item
package com.example.myfragment;
import android.widget.Spinner;
public class ExampleItem {
private String mWorkoutName;
private String workoutNum;
private String munit;
private Spinner mUnitSpinner;
public ExampleItem(String workoutName, String num, String unit) {
mWorkoutName = workoutName;
workoutNum = num;
munit = unit;
}
public Spinner getmUnitSpinner() {
return mUnitSpinner;
}
public void setSpinner (Spinner _mUnitSpinner) {
mUnitSpinner = _mUnitSpinner;
}
public String getmWorkoutName() {
return mWorkoutName;
}
public String getWorkoutNum() {
return workoutNum;
}
public String getMunit() {
return munit;
}
public void setmWorkoutName(String mWorkoutName) {
this.mWorkoutName = mWorkoutName;
}
public void setWorkoutNum(String workoutNum) {
this.workoutNum = workoutNum;
}
public void setMunit(String munit) {
this.munit = munit;
}
}
Example Item XML
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
android:id="#+id/addworkoutcardView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/structurespinner"
android:padding="5dp"
app:cardCornerRadius="4dp"
app:layout_constraintTop_toBottomOf="#+id/structurespinner"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<EditText
android:id="#+id/number"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_toRightOf="#+id/workoutname"/>
<EditText
android:id="#+id/workoutname"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_marginEnd="19dp"
android:ems="10"
android:layout_marginRight="19dp" />
<Spinner
android:id="#+id/unitspinner"
android:layout_width="120dp"
android:layout_height="50dp"
android:layout_marginStart="7dp"
android:layout_toRightOf="#+id/number"
android:entries="#array/workoutUnit"
android:layout_toEndOf="#+id/number"
android:layout_marginLeft="7dp" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
Recycler View Adapter
package com.example.myfragment;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class ExampleAdapter extends RecyclerView.Adapter<ExampleAdapter.ExampleViewHolder> {
private Activity activity;
private AddExerciseController controller;
public ExampleAdapter(MainActivity activity) {
this.activity = activity;
this.controller = AddExerciseController.getController();
}
public static class ExampleViewHolder extends RecyclerView.ViewHolder {
public EditText workoutName;
public EditText workoutNum;
public Spinner workoutUnit;
public ExampleViewHolder(View itemView) {
super(itemView);
workoutName = itemView.findViewById(R.id.workoutname);
workoutNum = itemView.findViewById(R.id.number);
workoutUnit = itemView.findViewById(R.id.unitspinner);
workoutUnit.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapter, View v,
int position, long id) {
// On selecting a spinner item
String sStep = adapter.getItemAtPosition(position).toString();
workoutUnit.setSelection(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
#Override
public ExampleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.example_item, parent, false);
ExampleViewHolder evh = new ExampleViewHolder(v);
return evh;
}
#Override
public void onBindViewHolder(ExampleViewHolder holder, int position) {
ExampleItem currentItem = controller.getListExercise().get(position);
holder.workoutName.setText(currentItem.getmWorkoutName());
holder.workoutNum.setText(currentItem.getWorkoutNum());
currentItem.setSpinner(holder.workoutUnit);
// store the spinner in the DetailItem object
currentItem.setSpinner(holder.workoutUnit);
// store DetailItem object in the array
controller.getListExercise().set(position, currentItem);
}
#Override
public int getItemCount() {
return controller.getListExercise().size();
}
Exercise Controller
package com.example.myfragment;
import java.util.ArrayList;
import java.util.List;
public class AddExerciseController {
private List<ExampleItem> exampleList;
private static AddExerciseController controller;
public AddExerciseController(){
initMovieList();
}
private List<ExampleItem> initMovieList(){
if (this.exampleList == null) {
this.exampleList = new ArrayList<ExampleItem>();
exampleList.add(new ExampleItem("workout1","60", "seconds"));
exampleList.add(new ExampleItem("workout2","50","seconds"));
exampleList.add(new ExampleItem("workout3","5","seconds"));
}
return this.exampleList;
}
public List<ExampleItem> getListExercise() {
return exampleList;
}
public static AddExerciseController getController(){
if(controller == null){
controller = new AddExerciseController();
}
return controller;
}
}
The error message says:
Caused by: java.lang.IllegalArgumentException: Binary XML file line #9:
Must specify unique android:id, android:tag, or have a parent with an id
for com.example.myfragment.AddExerciseFragment
And if we look at your activity XML:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<fragment
android:name="com.example.myfragment.AddExerciseFragment"
tools:layout="#layout/add_exercise_fragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:ignore="MissingConstraints"/>
</androidx.constraintlayout.widget.ConstraintLayout>
You'll note that your <fragment> tag does not have an android:id, android:tag, nor does your parent layout have an android:id. That's why you're getting the exception.
Therefore you can fix this by adding an android:id to your <fragment> tag (you also don't want to be using a ConstraintLayout with wrap_content sizes with a fragment - you want just a simple FrameLayout):
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<fragment
android:id="#+id/add_exercise_fragment"
android:name="com.example.myfragment.AddExerciseFragment"
tools:layout="#layout/add_exercise_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout>
It should be noted that Fragments must always have an empty constructor, so this code snippet is going to cause you to crash immediately afterwards:
public AddExerciseFragment(MainActivity activity) {
this.activity = activity;
}
You should replace that constructor with a constructor with no parameters:
public AddExerciseFragment() {
}
You'll want to use getActivity() to retrieve the Activity, casting it to your MainActivity as needed.
I have got the same error but it was because of different issue.I would like to add this answer here.
The same error is caused when you fail to mention a serializable data class in kotlin android room database.
data class ..(...):Serializable(check whether your data class is Serializaable)

I'm having problems with running the code on my device [duplicate]

This question already has answers here:
Explanation of ClassCastException in Java
(12 answers)
Closed 4 years ago.
Here is my problem. Below is my class (Events.java) below it is the error. I continue to run my code on my phone but continue to get that error. I don't know what exactly the problem is and I don't know how to fix it. I tried everything I looked up but kept getting errors. Please help I'm a noob obviously.
package com.androidapp.restart;
import android.app.Fragment;
import android.app.LoaderManager;
import android.app.ProgressDialog;
import android.content.ContentUris;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import com.getbase.floatingactionbutton.FloatingActionButton;
/**
* Created by aa215995 on 3/2/2018.
*/
public class Events extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
private FloatingActionButton mAddEventButton;
private Toolbar mToolbar;
EventCursorAdapter mCursorAdapter;
EventDbHelper eventDbHelper = new EventDbHelper(getActivity());
ListView eventListView;
ProgressDialog prgDialog;
private static final int VEHICLE_LOADER = 0;
#Nullable
#Override
public ListView onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
eventListView = (ListView) inflater.inflate(R.layout.nav_events, container, false);
mToolbar = (Toolbar) getView().findViewById(R.id.toolbar);
((AppCompatActivity)getActivity()).setSupportActionBar(mToolbar);
mToolbar.setTitle("Events");
eventListView = (ListView) getView().findViewById(R.id.list);
View emptyView = getView().findViewById(R.id.empty_view);
eventListView.setEmptyView(emptyView);
mCursorAdapter = new EventCursorAdapter(getActivity(), null);
eventListView.setAdapter(mCursorAdapter);
eventListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
Intent intent = new Intent(view.getContext(), AddEvent.class);
Uri currentVehicleUri = ContentUris.withAppendedId(EventContract.EventEntry.CONTENT_URI, id);
// Set the URI on the data field of the intent
intent.setData(currentVehicleUri);
startActivity(intent);
}
});
mAddEventButton = (FloatingActionButton) getView().findViewById(R.id.fab);
mAddEventButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), AddEvent.class);
startActivity(intent);
}
});
getLoaderManager().initLoader(VEHICLE_LOADER, null, this);
return eventListView;
}
#Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
String[] projection = {
EventContract.EventEntry._ID,
EventContract.EventEntry.KEY_TITLE,
EventContract.EventEntry.KEY_DATE,
EventContract.EventEntry.KEY_TIME,
EventContract.EventEntry.KEY_REPEAT,
EventContract.EventEntry.KEY_REPEAT_NO,
EventContract.EventEntry.KEY_REPEAT_TYPE,
EventContract.EventEntry.KEY_ACTIVE
};
return new CursorLoader(getActivity(), // Parent activity context
EventContract.EventEntry.CONTENT_URI, // Provider content URI to query
projection, // Columns to include in the resulting Cursor
null, // No selection clause
null, // No selection arguments
null); // Default sort order
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
mCursorAdapter.swapCursor(cursor);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
mCursorAdapter.swapCursor(null);
}
}
This is the error
05-24 14:02:00.885 15627-15627/com.androidapp.restart E/AndroidRuntime:
FATAL EXCEPTION: main
Process: com.androidapp.restart, PID: 15627
java.lang.ClassCastException: android.widget.LinearLayout cannot be cast
to android.widget.ListView
at com.androidapp.restart.Events.onCreateView(Events.java:47)
at com.androidapp.restart.Events.onCreateView(Events.java:31)
at android.app.Fragment.performCreateView(Fragment.java:2508)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1279)
at android.app.FragmentManagerImpl.addAddedFragments(FragmentManager.java:2407)
at android.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2186)
at android.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2142)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2043)
at android.app.FragmentManagerImpl$1.run(FragmentManager.java:719)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
This is the xml file (events.xml)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.androidapp.restart.Events">
<ListView
android:id="#+id/list"
android:layout_below="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<RelativeLayout
android:id="#+id/empty_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true">
<TextView
android:id="#+id/no_event_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:padding="16dp"
android:gravity="center"
android:text="#string/no_cardetails"/>
</RelativeLayout>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_margin="16dp"
android:src="#drawable/ic_add_black_24dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintRight_toRightOf="parent" />
EDITED
Now I have change the xml to a Relative Layout, same issues, but here is another issue I found:
at android.app.Fragment.performCreateView(Fragment.java:2508)
Here is the section of the Fragment.java:
if (mFragmentManager != null) {
writer.print(prefix); writer.print("mFragmentManager=");
writer.println(mFragmentManager);
}
This is an issue:
eventListView = (ListView) inflater.inflate(R.layout.nav_events, container, false);
You try to inflate listview but inflater returns you a LinearLayout a parent of all views. You need inflate the LinearLayout instead of listview and this is causes to cast exception.
You are trying to cast a layout on a listview
add this #id into your LinearLayout and inflate it in your Activity
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#id/layout";
tools:context="com.delaroystudiuos.alarmreminder.MainActivity">
and then call it like this
LinearLayout ll = (LinearLayout) inflater.inflate(R.layout.layout, container, false);;
If you are trying to access your existing ListView item in the XML:
<ListView
android:id="#+id/list"
android:layout_below="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
You will need to instead use:
View view = inflater.inflate(R.layout.nav_events, container, false);
eventListView = view.findViewById(R.id.list);

How to fix a bug where my Android app keeps crashing on start, does not open? (see description for more details)

This is the full logcat info:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method 'void
android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a
null object reference
at cmput301.subbook.MainActivity.onCreate(MainActivity.java:49)
at android.app.Activity.performCreate(Activity.java:6999)
at android.app.Activity.performCreate(Activity.java:6990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856) 
at android.app.ActivityThread.-wrap11(Unknown Source:0) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:164) 
at android.app.ActivityThread.main(ActivityThread.java:6494) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
These are the relevant files:
activity_main.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="cmput301.subbook.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Exit App"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ListView
android:id="#+id/listView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/mainText"
android:background="#e6a1a1"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="0dp" />
<!-- <Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="144dp"
android:layout_marginTop="504dp"
android:text="Add New Subscription"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0" /> -->
</android.support.constraint.ConstraintLayout>
MainActivity.java
package cmput301.subbook;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import java.util.ArrayList;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.view.View;
import android.widget.ArrayAdapter;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private TextView text;
private List<String> subListVal;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.mainText);
ArrayList<String> subListVal = new ArrayList<String>();
// subListVal = new ArrayList<String>();
subListVal.add("Netflix");
subListVal.add("Github");
subListVal.add("Spotify");
subListVal.add("Gym");
/* ArrayAdapter<String> adapter;
adapter = new ArrayAdapter <String>(this, R.layout.list_rows, R.id.listText, subListVal);
ListView listView = (ListView) findViewById(android.R.id.list);
listView.setAdapter(adapter); */
CustomAdapter adapter = new CustomAdapter(subListVal, this);
//handle listview and assign adapter
ListView lView = (ListView)findViewById(android.R.id.list);
lView.setAdapter(adapter);
/* Button add_btn = new Button(this);
add_btn.setText("Add New");
lView.addFooterView(add_btn); */
}
}
list_rows.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/listText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:textSize="20sp"
android:textColor="#ffe600" />
<Button
android:id="#+id/delete_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="5dp"
android:text="Delete" />
<Button
android:id="#+id/edit_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="#id/delete_btn"
android:layout_centerVertical="true"
android:layout_marginRight="10dp"
android:text="Edit" />
</LinearLayout>
CustomerAdapter.java
package cmput301.subbook;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by thesh on 2/3/2018.
*/
public class CustomAdapter extends BaseAdapter implements ListAdapter {
private ArrayList<String> list= new ArrayList<String>();
private Context context;
public CustomAdapter(ArrayList<String> list, Context context) {
this.list = list;
this.context = context;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int pos) {
return list.get(pos);
}
#Override
public long getItemId(int pos) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.list_rows, null);
}
//Handle TextView and display string from your list
TextView listItemText = (TextView)view.findViewById(R.id.listText);
listItemText.setText(list.get(position));
//Handle buttons and add onClickListeners
Button deleteBtn = (Button)view.findViewById(R.id.delete_btn);
Button editBtn = (Button)view.findViewById(R.id.edit_btn);
deleteBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
list.remove(position); //or some other task
notifyDataSetChanged();
}
});
editBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
notifyDataSetChanged();
}
});
return view;
}
}
Literally my app was working, and suddenly I got this bug, without changing much. The last change I made was trying to add a button at the footer_view of the list. I tried googling the logchat error to no avail.
Would appreciate the help. Thanks.
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference at cmput301.subbook.MainActivity.onCreate(MainActivity.java:49)
This is telling you that line 49 in MainActivity has your problem, in a setAdapter() call, where you are calling it on something that is null.
That would appear to be this line:
lView.setAdapter(adapter);
That means lView is null.
You attempt to assign a value to lView in the preceding line:
ListView lView = (ListView)findViewById(android.R.id.list);
If lView is null, then findViewById(android.R.id.list) is returning null. This means that Android cannot find a widget in your layout that has an android:id value of #android:id/list.
That is because your ListView has a different ID value:
<ListView
android:id="#+id/listView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/mainText"
android:background="#e6a1a1"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="0dp" />
These need to line up. So, either:
Change android:id in the <ListView> to #android:id/list, or
Change your findViewById() call to look for R.id.listView
change this ListView lView = (ListView)findViewById(android.R.id.list);
to ListView lView = (ListView)findViewById(R.id.listView);
Change -
ListView lView = (ListView)findViewById(android.R.id.list);
with -
ListView lView = (ListView)findViewById(R.id.listview);

Categories

Resources