Exception when going to another activity - java

I keep getting a NullPointerException when going to my other activity and the app/emulator just crashes.
The manifest file has both activities.
Here is the MainActivity:
public class MainActivity extends AppCompatActivity {
//Garbage Sorting V1
// GUI variables
private Button whereIsItems;
private Button addItem;
private TextView items;
private TextView listThings;
// Model: Database of items
private static ItemsDB itemsDB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.garbage);
itemsDB = new ItemsDB();
itemsDB.fillItemsDB();
items = findViewById(R.id.items);
items.setText("Where to place them:");
listThings = findViewById(R.id.edit_text);
whereIsItems = findViewById(R.id.where_button);
whereIsItems.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
items.setBackgroundColor(Color.parseColor("#FFFFFF"));
String str = listThings.getText().toString();
listThings.setText(itemsDB.getItemValue(str));
}
});
addItem = findViewById(R.id.add_button1);
assert addItem != null;
addItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, GarbageActivity.class);
startActivity(intent);
}
});
}
The other activity GarbageActivity (the one i'm trying to go to):
public class GarbageActivity extends AppCompatActivity {
private static ItemsDB itemsDB;
private EditText whatText;
private EditText whereText;
private Button addItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.garbage_activity);
itemsDB = ItemsDB.get(GarbageActivity.this);
addItem = findViewById(R.id.add_button2);
addItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
whatText = findViewById(R.id.what_text);
whereText = findViewById(R.id.where_text);
String str1 = whatText.getText().toString();
String str2 = whereText.getText().toString();
itemsDB.addItem(str1, str2);
whatText.setText("");
whereText.setText("");
}
});
}
Here is ItemsDB since debugger says there is an error here:
public class ItemsDB {
private Map<String, Item> ItemsDB;
private static ItemsDB sItemsDB;
public ItemsDB() {
ItemsDB = new HashMap<>();
}
private ItemsDB(Context context) {
fillItemsDB();
}
public static ItemsDB get(Context context) {
if (sItemsDB == null) sItemsDB = new ItemsDB(context);
return sItemsDB;
}
public void addItem(String what, String where) {
Item it = new Item(what, where);
ItemsDB.put(it.getWhat(), it);
}
public String getItemValue(String itemName) {
Item item = ItemsDB.get(itemName);
if (item == null) {
return itemName + " not found";
} else {
return itemName + " should be placed in " + ItemsDB.get(itemName).getWhere();
}
}
public void fillItemsDB() {
addItem("Milk Carton", "Cardboard");
addItem("Carrots", "Food");
addItem("T-shirt", "Not found");
addItem("Bread", "Food");
addItem("Butter", "Food");
}
garbage.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 for heading -->
<TextView
android:id="#+id/items"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<!-- Text field to enter item -->
<EditText
android:id="#+id/edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text"
android:layout_marginBottom="5dp"/>
<Button
android:id="#+id/where_button"
android:layout_width="wrap_content"
android:layout_gravity="left"
android:background="#39f208"
android:text="Where"
android:layout_height="80sp"/>
<Button
android:id="#+id/add_button1"
android:layout_width="wrap_content"
android:layout_gravity="left"
android:background="#39f208"
android:text="Add an item"
android:layout_height="80sp"/>
</LinearLayout>
garbage_activity.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">
<TableLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="What Item?"
android:textAppearance="#style/TextAppearance.AppCompat.Large" />
<EditText
android:id="#+id/what_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Where?"
android:textAppearance="#style/TextAppearance.AppCompat.Large" />
<EditText
android:id="#+id/where_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent" />
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="#+id/add_button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add an Item" />
</TableRow>
</TableLayout>
</LinearLayout>
This is my first question on here, so bear with me ;)
EDIT Here is the debugger log:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: dk.itu.sortinggarbageapp, PID: 8926
java.lang.RuntimeException: Unable to start activity ComponentInfo{dk.itu.sortinggarbageapp/dk.itu.sortinggarbageapp.GarbageActivity}: java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.Object java.util.Map.put(java.lang.Object, java.lang.Object)' 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 interface method 'java.lang.Object java.util.Map.put(java.lang.Object, java.lang.Object)' on a null object reference
at dk.itu.sortinggarbageapp.ItemsDB.addItem(ItemsDB.java:27)
at dk.itu.sortinggarbageapp.ItemsDB.fillItemsDB(ItemsDB.java:40)
at dk.itu.sortinggarbageapp.ItemsDB.<init>(ItemsDB.java:17)
at dk.itu.sortinggarbageapp.ItemsDB.get(ItemsDB.java:21)
at dk.itu.sortinggarbageapp.GarbageActivity.onCreate(GarbageActivity.java:24)
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.ja va:592) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947) 
I/Process: Sending signal. PID: 8926 SIG: 9
Disconnected from the target VM, address: 'localhost:63608',transport:
'socket'

The ItemsDB constructor used when the activity is started calls fillItemsDB() which adds items to the ItemsDB field. However, that field is not initialized in this constructor.
You need to either initialize it there, call the other constructor, or initialize where you declare the field.
// initialize at field declaration
Map<String, Item> ItemsDB = new HashMap<>();
// initialize here
private ItemsDB(Context context) {
ItemsDB = new HashMap<>();
fillItemsDB();
}
// call the other constructor
public ItemsDB(Context context) {
this();
fillItemsDB();
}
Either of these things will work.

You could try this on your Garbage class
ItemsDB itemsDB = new ItemsDB();
itemsDB.get(GarbageActivity.this);

Related

Binary XML file line #26: RecyclerView has no LayoutManager androidx.recyclerview.widget.RecyclerView{a9ab2d5 VFED

I Create Recyclerview on android studio use Kotlin programing language, when I run my code I Get Error. This is the Error I'm getting
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.its*******.*******, PID: 18742
java.lang.RuntimeException: Unable to start activity ComponentInfo{******************************}: android.view.InflateException: Binary XML file line #26: RecyclerView has no LayoutManager androidx.recyclerview.widget.RecyclerView{a9ab2d5 VFED..... ......I. 0,0-0,0 #7f080187 app:id/reyclerview_message_list}, adapter:null, layout:null, context:com.its*******.*******.******#36b9430
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3191)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3328)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:113)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:71)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2054)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:233)
at android.app.ActivityThread.main(ActivityThread.java:7225)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:499)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:962)
Caused by: android.view.InflateException: Binary XML file line #26: RecyclerView has no LayoutManager androidx.recyclerview.widget.RecyclerView{a9ab2d5 VFED..... ......I. 0,0-0,0 #7f080187 app:id/reyclerview_message_list}, adapter:null, layout:null, context:com.itsshyam640.cooltalks.userChat#36b9430
Caused by: java.lang.IllegalStateException: RecyclerView has no LayoutManager androidx.recyclerview.widget.RecyclerView{a9ab2d5 VFED..... ......I. 0,0-0,0 #7f080187 app:id/reyclerview_message_list}, adapter:null, layout:null, context:com.its*******.*******.*****#36b9430
at androidx.recyclerview.widget.RecyclerView.generateLayoutParams(RecyclerView.java:4514)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:902)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:861)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:903)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:861)
at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:699)
at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:195)
at com.its*******.*******.*****.onCreate(userChat.java:35)
at android.app.Activity.performCreate(Activity.java:7378)
at android.app.Activity.performCreate(Activity.java:7369)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3171)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3328)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:113)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:71)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2054)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:233)
at android.app.ActivityThread.main(ActivityThread.java:7225)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:499)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:962)
This is my mainfile code I had sent the required code only as per the requirements
public class userChat extends AppCompatActivity {
private RecyclerView recyclerView_message_list;
private ArrayList<userChatModel> userChatModels = new ArrayList<>();
FirebaseDatabase database;
FirebaseAuth auth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_chat);
getSupportActionBar().hide();
database = FirebaseDatabase.getInstance();
auth = FirebaseAuth.getInstance();
String senderId = auth.getUid();
String recievedId = getIntent().getStringExtra("userId");
String userName = getIntent().getStringExtra("userName");
String userProfileImage = getIntent().getStringExtra("userProfileImage");
TextView username = findViewById(R.id.top_username);
username.setText(userName);
Picasso.get().load(userProfileImage).placeholder(R.drawable.user).into((ImageView) findViewById(R.id.user_profile));
findViewById(R.id.back_button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(userChat.this,MainActivity.class);
startActivity(intent);
}
});
recyclerView_message_list = (RecyclerView) findViewById(R.id.recyclerView_message_list);
final userChatAdapter userChatAdapter = new userChatAdapter(userChatModels,this);
recyclerView_message_list.setAdapter(userChatAdapter);
LinearLayoutManager layoutManager = new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false);
recyclerView_message_list.setLayoutManager(layoutManager);
final String senderMessages = senderId + recievedId;
final String recieverMessages = recievedId + senderId;
database.getReference().child("Chats").child(senderMessages).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
userChatModels.clear();
for(DataSnapshot snapshot1 : snapshot.getChildren()){
userChatModel userChatModel = snapshot1.getValue(userChatModel.class);
userChatModels.add(userChatModel);
}
userChatAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
Here is my xml Code
<?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"
android:background="#color/backgroundColor"
tools:context=".userChat">
<androidx.appcompat.widget.Toolbar
android:id="#+id/user_chat_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:elevation="30dp"
android:minHeight="?attr/actionBarSize"
android:theme="?attr/actionBarTheme"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteX="16dp">
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/back_button"
android:layout_width="50dp"
android:layout_height="50dp"
android:background="#drawable/round_gradient"
android:src="#drawable/ic_keyboard_backspace_black_24dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/user_profile"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_margin="5dp"
android:contentDescription="#string/profile_image"
android:src="#drawable/user"
app:layout_constraintBottom_toBottomOf="#id/back_button"
app:layout_constraintStart_toEndOf="#id/back_button"
app:layout_constraintTop_toTopOf="#id/back_button" />
<TextView
android:id="#+id/top_username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:text="#string/username"
android:textColor="#color/textColor"
app:layout_constraintStart_toEndOf="#+id/user_profile"
app:layout_constraintTop_toTopOf="#+id/user_profile" />
<ImageView
android:id="#+id/audioCall"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_margin="5dp"
android:contentDescription="#string/audio_call_image"
app:layout_constraintBottom_toBottomOf="#+id/videoCall"
app:layout_constraintEnd_toStartOf="#+id/videoCall"
app:layout_constraintTop_toTopOf="#+id/videoCall"
app:srcCompat="#android:drawable/stat_sys_phone_call_forward" />
<ImageView
android:id="#+id/videoCall"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_margin="5dp"
android:contentDescription="#string/video_call_image"
android:src="#drawable/camera_pattern"
app:layout_constraintBottom_toBottomOf="#+id/more_actions"
app:layout_constraintEnd_toStartOf="#+id/more_actions"
app:layout_constraintTop_toTopOf="#+id/more_actions" />
<ImageView
android:id="#+id/more_actions"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_margin="5dp"
android:contentDescription="#string/more_action_image"
android:src="#drawable/ic_more_vert_black_24dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.appcompat.widget.Toolbar>
<LinearLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/recyclerView_message_list" />
</LinearLayout>
Here is my userChat Adapter Code
public class userChatAdapter extends RecyclerView.Adapter{
ArrayList<userChatModel> messageModels;
Context context;
int SENDER_VIEW_TYPE = 1;
int RECIEVER_VIEW_TYPE = 2;
public userChatAdapter(ArrayList<userChatModel> messageModels, Context context) {
this.messageModels = messageModels;
this.context = context;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
if(viewType == SENDER_VIEW_TYPE){
View view = LayoutInflater.from(context).inflate(R.layout.message_sent_layout,parent,false);
return new senderViewHolder(view);
}else {
View view = LayoutInflater.from(context).inflate(R.layout.message_recieved_layout,parent,false);
return new recieverViewHolder(view);
}
}
#Override
public int getItemViewType(int position) {
if (messageModels.get(position).getUserId().equals(FirebaseAuth.getInstance().getCurrentUser())){
return SENDER_VIEW_TYPE;
}else {
return RECIEVER_VIEW_TYPE;
}
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
userChatModel messageModel = messageModels.get(position);
if(holder.getClass() == senderViewHolder.class){
((senderViewHolder)holder).senderMessage.setText(messageModel.getUserMessage());
}else {
((recieverViewHolder)holder).recieverMessage.setText(messageModel.getUserMessage());
}
}
#Override
public int getItemCount() {
return messageModels.size();
}
public class recieverViewHolder extends RecyclerView.ViewHolder{
TextView recieverMessage, recieverTime;
public recieverViewHolder(#NonNull View itemView) {
super(itemView);
recieverMessage = itemView.findViewById(R.id.user_recieved_message);
recieverTime = itemView.findViewById(R.id.user_recieved_message_time);
}
}
public class senderViewHolder extends RecyclerView.ViewHolder{
TextView senderMessage, senderTime;
public senderViewHolder(#NonNull View itemView) {
super(itemView);
senderMessage = itemView.findViewById(R.id.user_sent_message);
senderTime = itemView.findViewById(R.id.user_sent_message_time);
}
}
}
I tried many ways but could not resolve the error.... I had applied many stackoverflow solutions.
Thanks in Advance!
Try to add
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/recyclerView_message_list"
+ app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
/>
It determines if your layout is going to be Linear, Grid or Staggered.
You can find more info about the different layoutManagers here:
Android - What is Layout Manager?
And on the docs:
https://developer.android.com/reference/androidx/recyclerview/widget/RecyclerView.LayoutManager
Firstly remove these lines from your java file,
LinearLayoutManager layoutManager = new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false);
recyclerView_message_list.setLayoutManager(layoutManager);
Then add below XML snippet
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/recyclerView_message_list"
+ app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
/>

RecyclerView throws null pointer for setAdapter even though the adapter is defined

I have a null pointer exception but I can't see where I am going wrong. I have been trying to fix this error for 2 days.
Here is the activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
and the Code for the class MainActivity
package com.example.servicestest1;
import android.os.Bundle;
import android.util.Log;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity{
private static final String TAG = "MainActivity";
private ArrayList<String> mDescriptions = new ArrayList<>();
private ArrayList<String> mStartDates = new ArrayList<>();
private ArrayList<String> mEndDates = new ArrayList<>();
private ArrayList<String> mImageUrls = new ArrayList<>();
private ArrayList<String> mTopicList = new ArrayList<>();
RecyclerView recyclerView;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recycler_view);
initRecyclerViewItems();
}
private void initRecyclerViewItems() {
Log.d(TAG, "initRecyclerViewItems: preparing items");
addRecyclerViewItem("https://i.redd.it/3p6500yf3he41.jpg","Hogwarts Express","Working for the soviet union"
,"20/01/1968","20/10/1984");
addRecyclerViewItem("https://i.redd.it/s8bmctrhdxd41.jpg","Some scene about Nature","Some title",
"20/09/1897","20/03/1989");
addRecyclerViewItem("https://i.redd.it/lrbmhm707rd41.jpg","Boating","Boating in a pristine location",
"30/09/1998","31/09/1998");
initRecyclerView();
}
private void addRecyclerViewItem(String imageUrl, String topic, String description, String startDate, String endDate){
Log.w(TAG, "addRecyclerViewItem: called", null);
mImageUrls.add(imageUrl);
mTopicList.add(topic);
mStartDates.add(startDate);
mEndDates.add(endDate);
mDescriptions.add(description);
}
private void initRecyclerView(){
RecyclerViewAdapter adapter = new RecyclerViewAdapter(this,mTopicList,mDescriptions,
mStartDates,mEndDates,mImageUrls);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
}
The recyclerView.setAdapter returns a NullPointer exeception even though I have defined the adapter.
and the code for the RecyclerView adapter
package com.example.servicestest1;
import android.content.Context;
import android.net.Uri;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>{
private static final String TAG = "RecyclerViewAdapter";
private ArrayList<String> mTopicListOfTheEvent;
private ArrayList<String> mDescriptionListOfTheEvent;
private ArrayList<String> mStartDateListOfTheEvent;
private ArrayList<String> mEndDateListOfTheEvent;
private ArrayList<String> mImageListDescribingTheEvent;
private Context mContext;
RecyclerViewAdapter(Context context,
ArrayList<String> topicListOfTheEvent,
ArrayList<String> descriptionListOfTheEvent,
ArrayList<String> startDateListOfTheEvent,
ArrayList<String> endDateListOfTheEvent,
ArrayList<String> imageListDescribingTheEvent){
this.mContext = context;
this.mTopicListOfTheEvent = topicListOfTheEvent;
this.mDescriptionListOfTheEvent = descriptionListOfTheEvent;
this.mStartDateListOfTheEvent = startDateListOfTheEvent;
this.mEndDateListOfTheEvent = endDateListOfTheEvent;
this.mImageListDescribingTheEvent = imageListDescribingTheEvent;
}
#NonNull
#Override
public RecyclerViewAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_recycler_view_layout,parent,true);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerViewAdapter.ViewHolder holder, int position) {
Log.d(TAG, "onBindViewHolder: called");
holder.descriptionOfTheEvent.setText(mDescriptionListOfTheEvent.get(position));
holder.imageDescribingTheEvent.setImageURI(Uri.parse(mImageListDescribingTheEvent.get(position)));
holder.startDateOfTheEvent.setText(mStartDateListOfTheEvent.get(position));
holder.endDateOfTheEvent.setText(mEndDateListOfTheEvent.get(position));
holder.topicListOfTheEvent.setText(mTopicListOfTheEvent.get(position));
holder.parentLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: Clicked on");
Toast.makeText(mContext,"You pressed me",Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return mTopicListOfTheEvent.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
TextView descriptionOfTheEvent;
TextView topicListOfTheEvent;
TextView startDateOfTheEvent;
TextView endDateOfTheEvent;
ImageView imageDescribingTheEvent;
LinearLayout parentLayout;
ViewHolder(#NonNull View itemView) {
super(itemView);
parentLayout = itemView.findViewById(R.id.recycler_view_item);
}
}
}
and the code for the activity_recycler_view_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/recycler_view_item">
<!-- The code for the AppBar -->
<androidx.appcompat.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="44dp"
android:background="#FFFEFE"
android:elevation="5dp"
tools:targetApi="lollipop">
<RelativeLayout
android:id="#+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="44dp"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_marginTop="8dp"
android:src="#drawable/bottom_lotus"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="ContentDescription" />
<ImageView
android:id="#+id/imageView2"
android:layout_width="11dp"
android:layout_height="44dp"
android:layout_marginStart="18dp"
android:layout_marginLeft="18dp"
android:layout_marginTop="17dp"
android:layout_marginBottom="10dp"
android:src="#drawable/arrow"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="ContentDescription" />
<TextView
android:id="#+id/textView"
android:layout_width="66dp"
android:layout_height="44dp"
android:layout_marginStart="49dp"
android:layout_marginLeft="49dp"
android:layout_marginTop="13dp"
android:layout_marginBottom="10dp"
android:lineHeight="21sp"
android:text="Services"
android:textColor="#403E42"
android:textSize="16sp"
app:fontFamily="#font/roboto_condensed_regular"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/profile_picture"
android:layout_width="wrap_content"
android:layout_height="44dp"
android:layout_alignParentRight="true"
android:layout_marginLeft="4dp"
android:layout_marginTop="4dp"
android:layout_marginBottom="4dp"
android:src="#drawable/ic_launcher_background"
android:layout_alignParentEnd="true" />
</RelativeLayout>
</androidx.appcompat.widget.Toolbar>
<RelativeLayout
android:layout_width="348dp"
android:layout_height="296dp"
android:layout_margin="6dp">
<ImageView
android:layout_width="348dp"
android:layout_height="296dp"
android:src="#drawable/images" />
<TextView
android:id="#+id/topic_text_view"
android:layout_width="wrap_content"
android:layout_height="28dp"
android:layout_marginStart="25dp"
android:layout_marginLeft="25dp"
android:layout_marginTop="25dp"
android:alpha="0.41"
android:text="It's His Birthday"
android:textColor="#f93f3f"
android:textSize="21sp"
app:fontFamily="#font/roboto_condensed_bold" />
<!--This LinearLayout is used for drawing the text inside the rectangle -->
<LinearLayout
android:layout_width="242dp"
android:layout_height="51dp"
android:layout_marginLeft="26dp"
android:layout_marginTop="64dp"
android:background="#drawable/rectangle"
android:orientation="vertical"
android:layout_marginStart="26dp">
<TextView
android:layout_width="198dp"
android:layout_height="32dp"
android:gravity="center"
android:lineHeight="16dp"
android:text="This is Sample Text"
android:textColor="#ffffff"
android:textSize="12sp"
app:fontFamily="#font/roboto_bold" />
</LinearLayout>
<TextView
android:layout_width="37dp"
android:layout_height="19dp"
android:layout_marginStart="26dp"
android:layout_marginLeft="26dp"
android:layout_marginTop="142dp"
android:lineHeight="19dp"
android:text="Dates"
android:textColor="#FFFFFF"
android:textSize="14sp"
app:fontFamily="#font/roboto_condensed_bold" />
<LinearLayout
android:layout_width="86dp"
android:layout_height="35dp"
android:layout_marginStart="62dp"
android:layout_marginLeft="62dp"
android:layout_marginTop="142dp"
android:orientation="vertical">
<TextView
android:id="#+id/start_date_of_the_event"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:lineHeight="16dp"
android:text="12 June 2019"
android:textColor="#ffffff"
android:textSize="12sp"
app:fontFamily="#font/roboto" />
<TextView
android:id="#+id/end_date_of_the_event"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:lineHeight="16dp"
android:text="13 June 2019"
android:textColor="#ffffff"
android:textSize="12sp"
app:fontFamily="#font/roboto" />
</LinearLayout>
</RelativeLayout>
<TextView
android:id="#+id/reject_button"
android:layout_width="35dp"
android:layout_height="16dp"
android:layout_marginStart="160dp"
android:layout_marginLeft="160dp"
android:layout_marginTop="15dp"
android:clickable="true"
android:text="REJECT"
android:textColor="#4B0082"
android:textStyle="bold"
tools:ignore="KeyboardInaccessibleWidget" />
<Button
android:id="#+id/accept_button"
android:layout_width="103dp"
android:layout_height="37dp"
android:layout_marginStart="248dp"
android:layout_marginLeft="248dp"
android:background="#4B0082"
android:text="ACCEPT"
android:textColor="#ffffff"
android:textSize="20sp" />
</LinearLayout>
And the here are the errors
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.servicestest1/com.example.servicestest1.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setAdapter(androidx.recyclerview.widget.RecyclerView$Adapter)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setAdapter(androidx.recyclerview.widget.RecyclerView$Adapter)' on a null object reference
at com.example.servicestest1.MainActivity.initRecyclerView(MainActivity.java:53)
at com.example.servicestest1.MainActivity.initRecyclerViewItems(MainActivity.java:38)
at com.example.servicestest1.MainActivity.onCreate(MainActivity.java:27)
at android.app.Activity.performCreate(Activity.java:7136)
at android.app.Activity.performCreate(Activity.java:7127)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:193) 
at android.app.ActivityThread.main(ActivityThread.java:6669) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) 
recyclerView variable is set after its usage, so it's null when you try to set adapter.
Assign recyclerView before setting the adapter
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recycler_view);
initRecyclerViewItems();
}
in Java, calling findViewById(...) initializes the view variable. The variable is usually null when findViewById(..) hasn't been called yet or has been called with an id from a layout which hasn't been inflated yet. In your case. You can fix the error simply by changing your onCreate method.
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recycler_view); //recyclerView gets initialized here
initRecyclerViewItems();
}
Google docs on findViewById
It takes some time to inflate recycler view. Try to add waiting cycle:
recyclerView = findViewById(R.id.recycler_view);
while (recyclerView == null){
Thread.sleep(1);
}
init();

findViewById() may produce NullPointerException for getView() in HomeFragment.java

public class HomeFragment extends Fragment implements HomeView{
private HomeViewModel homeViewModel;
public static final String EXTRA_CATEGORY = "category";
public static final String EXTRA_POSITION = "position";
public static final String EXTRA_DETAIL = "detail";
#BindView(R.id.viewPagerHeader)
ViewPager viewPagerMeal;
#BindView(R.id.recyclerCategory)
RecyclerView recyclerViewCategory;
HomePresenter presenter;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
homeViewModel =
ViewModelProviders.of(this).get(HomeViewModel.class);
View root = inflater.inflate(R.layout.fragment_home, container, false);
super.onCreate(savedInstanceState);
ButterKnife.bind(getActivity());
presenter = new HomePresenter(this);
presenter.getMeals();
presenter.getCategories();
return root;
}
#Override
public void showLoading() {
getView().findViewById(R.id.shimmerMeal).setVisibility(View.VISIBLE);
getView().findViewById(R.id.shimmerCategory).setVisibility(View.VISIBLE);
}
#Override
public void hideLoading() {
getView().findViewById(R.id.shimmerMeal).setVisibility(View.GONE);
getView().findViewById(R.id.shimmerCategory).setVisibility(View.GONE);
}
#Override
public void setMeal(List<Meals.Meal> meal) {
ViewPagerHeaderAdapter headerAdapter = new ViewPagerHeaderAdapter(meal, getActivity());
viewPagerMeal.setAdapter(headerAdapter);
viewPagerMeal.setPadding(20, 0, 150, 0);
headerAdapter.notifyDataSetChanged();
headerAdapter.setOnItemClickListener((view, position) -> {
TextView mealName = view.findViewById(R.id.mealName);
Intent intent = new Intent(getActivity().getApplicationContext(), DetailActivity.class);
intent.putExtra(EXTRA_DETAIL,mealName.getText().toString());
startActivity(intent);
});
}
#Override
public void setCategory(List<Categories.Category> category) {
RecyclerViewHomeAdapter homeAdapter = new RecyclerViewHomeAdapter(category, getActivity());
recyclerViewCategory.setAdapter(homeAdapter);
GridLayoutManager layoutManager = new GridLayoutManager(getActivity(), 3,
GridLayoutManager.VERTICAL, false);
recyclerViewCategory.setLayoutManager(layoutManager);
recyclerViewCategory.setNestedScrollingEnabled(true);
homeAdapter.notifyDataSetChanged();
homeAdapter.setOnItemClickListener((view, position) -> {
Intent intent = new Intent(getActivity(), CategoryActivity.class);
intent.putExtra(EXTRA_CATEGORY, (Serializable) category);
intent.putExtra(EXTRA_POSITION, position);
startActivity(intent);
});
}
#Override
public void onErrorLoading(String message) {
Utils.showDialogMessage(getActivity(), "Title", message);
}
}
public class HomeViewModel extends ViewModel {
private MutableLiveData<String> mText;
public HomeViewModel() {
mText = new MutableLiveData<>();
mText.setValue("This is home fragment");
}
public LiveData<String> getText() {
return mText;
}
}
fragment_home.xml
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.home.HomeFragment"
android:fitsSystemWindows="true">
<android.support.v4.widget.NestedScrollView
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:fillViewport="true"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorBackground">
<RelativeLayout
android:id="#+id/headerView"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="300dp">
<View
android:layout_width="match_parent"
android:layout_height="220dp"
android:background="#color/colorPrimary" />
<TextView
android:id="#+id/title"
android:textColor="#color/colorWhite"
android:text="#string/app_name"
android:textStyle="bold"
android:textSize="30sp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:layout_marginTop="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<android.support.v7.widget.CardView
android:id="#+id/cardSearch"
android:layout_below="#id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:layout_marginTop="15dp"
app:cardBackgroundColor="#color/colorPrimaryDark"
app:cardCornerRadius="10dp"
app:cardElevation="0dp">
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:padding="10dp"
android:text="#string/search_your_recipes"
android:textColor="#color/colorPrimaryLight"
android:gravity="center_vertical"
android:drawableLeft="#drawable/ic_search_primary_light"
android:drawableStart="#drawable/ic_search_primary_light"
android:drawablePadding="10dp"/>
</android.support.v7.widget.CardView>
<android.support.v4.view.ViewPager
android:id="#+id/viewPagerHeader"
android:foregroundGravity="center"
android:overScrollMode="never"
android:clipToPadding="false"
android:layout_below="#id/cardSearch"
android:layout_marginTop="10dp"
android:layout_width="match_parent"
android:layout_height="150dp" />
<include android:id="#+id/shimmerMeal"
layout="#layout/item_view_pager_header_shimmer" />
<TextView
android:id="#+id/titleCategory"
android:text="#string/meal_categories"
android:textSize="19sp"
android:textColor="#color/colorPrimary"
android:textStyle="bold"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:layout_marginTop="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/viewPagerHeader"/>
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerCategory"
android:scrollbars="none"
android:layout_marginTop="10dp"
android:clipToPadding="false"
android:layout_below="#id/titleCategory"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="50dp" />
<include android:id="#+id/shimmerCategory"
layout="#layout/item_recycler_category_shimmer" />
<TextView
android:padding="10dp"
android:gravity="center"
android:textColor="#color/colorWhite"
android:text="#string/app_name"
android:background="#color/colorPrimaryLight"
android:layout_alignParentBottom="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"/>
</RelativeLayout>
</android.support.v4.widget.NestedScrollView>
Here is Logcat file:
2019-12-20 18:04:26.459 4910-4910/com.vikaskonaparthi.origin E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.vikaskonaparthi.origin, PID: 4910
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
at com.vikaskonaparthi.origin.ui.home.HomeFragment.showLoading(HomeFragment.java:63)
at com.vikaskonaparthi.origin.ui.home.HomePresenter.getMeals(HomePresenter.java:29)
at com.vikaskonaparthi.origin.ui.home.HomeFragment.onCreateView(HomeFragment.java:56)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2439)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1460)
at android.support.v4.app.FragmentManagerImpl.addAddedFragments(FragmentManager.java:2646)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2416)
at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2372)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2273)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:733)
at android.os.Handler.handleCallback(Handler.java:874)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:198)
at android.app.ActivityThread.main(ActivityThread.java:6729)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Getting error with the shimmer in HomeFragmentActivity how to resolve this issue?
Should showloading() be kept in FragmentViewModel?
Since I had converted Activity to the fragment here.
The issue is not with the shimmer.
The issue is your getView() in getView().findViewById(R.id.shimmerMeal).setVisibility(View.VISIBLE);
is null.
If you are having your shimmer views in fragment then you need to call showLoading() after your fragments onViewCreated() method is called.
I think you must put everything that connects with layout, like constraints and others widget when onViewCreated() is called.
Call it below your onCreateView(). This error happens because of calling widget but the widget itself not yet exist or created by fragment. Widgets will exist in onViewCreated(). Tell me if it's work

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

Unable to AddView in fragment

I have been trying to add a view that i have created using a class into the layout but i have been getting this following error for days :
10-22 08:32:16.037 2607-2607/com.parse.starter I/perme:
android.content.res.Resources$NotFoundException: Resource ID #0x0
FullStackTrace is as follow :
10-22 08:48:31.879 18805-18805/com.parse.starter E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.parse.starter, PID: 18805
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.parse.starter/com.parse.starter.baseMain}: android.content.res.Resources$NotFoundException: Resource ID #0x0
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4483)
at android.app.ActivityThread.-wrap19(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1466)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
Caused by: android.content.res.Resources$NotFoundException: Resource ID #0x0
at android.content.res.ResourcesImpl.getValue(ResourcesImpl.java:190)
at android.content.res.Resources.loadXmlResourceParser(Resources.java:2094)
at android.content.res.Resources.getLayout(Resources.java:1111)
at android.view.LayoutInflater.inflate(LayoutInflater.java:424)
at com.mindorks.placeholderview.SwipePlaceHolderView.addView(SwipePlaceHolderView.java:221)
at com.parse.starter.socialPeople$override.onCreateView(socialPeople.java:152)
at com.parse.starter.socialPeople$override.access$dispatch(socialPeople.java)
at com.parse.starter.socialPeople.onCreateView(socialPeople.java:0)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2192)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1299)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1595)
at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:2900)
at android.support.v4.app.FragmentController.dispatchActivityCreated(FragmentController.java:201)
at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:603)
at android.support.v7.app.AppCompatActivity.onStart(AppCompatActivity.java:178)
at com.parse.starter.baseMain.onStart(baseMain.java:358)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1248)
at android.app.Activity.performStart(Activity.java:6679)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2609)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) 
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4483) 
at android.app.ActivityThread.-wrap19(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1466) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6077) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756) 
i have drill the error down to this line of code and the variables which i am trying to pass into the method all are not null. The following code causing the error are as follow :
public class socialPeople extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private SwipePlaceHolderView mSwipeView;
private String mParam1;
private String mParam2;
Context mContext;
private profileFrag.OnFragmentInteractionListener mListener;
public static socialPeople newInstance() {
socialPeople fragment = new socialPeople();
return fragment;
}
public socialPeople() {
// Required empty public constructor
}
public static socialPeople newInstance(String param1, String param2) {
socialPeople fragment = new socialPeople();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
mContext = context;
}
int count = 1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragmentschool,
container, false);
if(count == 1) {
mSwipeView = (SwipePlaceHolderView) view.findViewById(R.id.swipeView2);
try {
mSwipeView.getBuilder()
.setDisplayViewCount(1)
.setSwipeDecor(new SwipeDecor()
.setPaddingTop(20)
.setRelativeScale(0.01f)
.setSwipeInMsgLayoutId(R.layout.activity_swipein)
.setSwipeOutMsgLayoutId(R.layout.activity_swipeout));
} catch (Exception e) {
Log.i("permedialog", "" + e.toString());
}
for (TinderProfile tinderprofile : loadProfiles(getActivity())) {
TinderCard tinderCard = new TinderCard(getActivity(), tinderprofile, mSwipeView);
mSwipeView.addView(tinderCard);
}
view.findViewById(R.id.rejectBtn).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mSwipeView.doSwipe(false);
}
});
view.findViewById(R.id.acceptBtn).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mSwipeView.doSwipe(true);
}
});
count -=1;
}
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
I suspect that it has something to do with the widget and here is the widget in the XML :
<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="com.parse.starter.socialPeople">
<LinearLayout
android:id="#+id/search"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:id="#+id/fi"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="end"
android:orientation="horizontal"
android:padding="10dp">
<EditText
android:id="#+id/txtsearch"
android:layout_width="314dp"
android:layout_height="wrap_content"
android:ems="10"
android:hint="search"
android:inputType="textPersonName"
android:text="Name" />
<ImageView
android:id="#+id/spset"
android:layout_width="37dp"
android:layout_height="35dp"
android:layout_marginTop="10dp"
android:layout_weight="0.2"
android:baselineAlignBottom="true"
app:srcCompat="#drawable/search" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="30dp">
<FrameLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/grey">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="80dp"
android:layout_gravity="bottom"
android:gravity="center"
android:orientation="horizontal">
<ImageButton
android:id="#+id/rejectBtn"
android:layout_width="50dp"
android:layout_height="50dp"
android:text="cancel"/>
<ImageButton
android:id="#+id/acceptBtn"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginLeft="30dp"
android:text="accept"/>
</LinearLayout>
<com.mindorks.placeholderview.SwipePlaceHolderView
android:id="#+id/swipeView2"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout>
</LinearLayout>
</LinearLayout>
I have also done research of if the error might be linked to AddView however i have come up with no solution. I look forward to everyone advice! Thanks in Advance !! Cheers!
This error says that you have not initialised the swipeView with its associated resource id or there's some problem with the context you are passing to TinderCard. Try passing getActivity() instead of mContext in your TinderCard and check if it works.

Categories