Here is my MainActivity.java:
public class MainActivity extends AppCompatActivity {
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabLayout.findViewById(R.id.tabLayout);
viewPager.findViewById(R.id.viewPager);
tabLayout.setupWithViewPager(viewPager);
VPAdapter vpAdapter = new VPAdapter(getSupportFragmentManager(), FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
vpAdapter.addFragment(new statistics(),"Statistics");
vpAdapter.addFragment(new connectivity(),"Connectivity");
vpAdapter.addFragment(new maskSensor(),"Mask Sensor");
viewPager.setAdapter(vpAdapter);
} }
Here The MainActivity.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">
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent">
<com.google.android.material.tabs.TabItem
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Statistics" />
<com.google.android.material.tabs.TabItem
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Connectivity" />
<com.google.android.material.tabs.TabItem
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Mask Sensor" />
</com.google.android.material.tabs.TabLayout>
<androidx.viewpager.widget.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toTopOf="#+id/tabLayout"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Here My VPAdapter.java
public class VPAdapter extends FragmentPagerAdapter {
private final ArrayList<Fragment> fragmentArrayList = new ArrayList<>();
private final ArrayList<String> fragmentTitle = new ArrayList<>();
public VPAdapter(#NonNull #NotNull FragmentManager fm, int behavior) {
super(fm, behavior);
}
#NonNull
#NotNull
#Override
public Fragment getItem(int position) {
return fragmentArrayList.get(position);
}
#Override
public int getCount() {
return fragmentArrayList.size();
}
public void addFragment(Fragment fragment , String title)
{
fragmentArrayList.add(fragment);
fragmentTitle.add(title);
}
#Nullable
#org.jetbrains.annotations.Nullable
#Override
public CharSequence getPageTitle(int position) {
return fragmentTitle.get(position);
}
}
And This My Logcat
11-11 16:18:36.645 21916-21916/com.nekat.sippanto E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.nekat.sippanto, PID: 21916
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.nekat.sippanto/com.nekat.sippanto.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View com.google.android.material.tabs.TabLayout.findViewById(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2464)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2526)
at android.app.ActivityThread.access$800(ActivityThread.java:169)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1421)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5549)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:964)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:759)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View com.google.android.material.tabs.TabLayout.findViewById(int)' on a null object reference
at com.nekat.sippanto.MainActivity.onCreate(MainActivity.java:22)
at android.app.Activity.performCreate(Activity.java:5977)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1111)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2417)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2526)
at android.app.ActivityThread.access$800(ActivityThread.java:169)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1421)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5549)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:964)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:759)
You are not initializing your TabLayout and ViewPager properly. Change these lines
tabLayout.findViewById(R.id.tabLayout);
viewPager.findViewById(R.id.viewPager);
to
tabLayout = findViewById(R.id.tabLayout);
viewPager = findViewById(R.id.viewPager);
Related
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"
/>
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);
I was trying to add a collapsing Toolbar to a Fragment, but the app crashed as soon as I opened the Fragment:
This is the error I get:
2018-10-19 18:05:38.950 13301-13301/io.github.davidwickerhf.diceroller E/AndroidRuntime: FATAL EXCEPTION: main
Process: io.github.davidwickerhf.diceroller, PID: 13301
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
at androidx.appcompat.app.AppCompatDelegateImpl.<init>(AppCompatDelegateImpl.java:249)
at androidx.appcompat.app.AppCompatDelegate.create(AppCompatDelegate.java:182)
at androidx.appcompat.app.AppCompatActivity.getDelegate(AppCompatActivity.java:520)
at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:191)
at io.github.davidwickerhf.diceroller.ProfileFragment.onCreateView(ProfileFragment.java:36)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2439)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManager.java:1460)
at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1784)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManager.java:1852)
at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:802)
at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManager.java:2625)
at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2411)
at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2366)
at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2273)
at androidx.fragment.app.FragmentManagerImpl$1.run(FragmentManager.java:733)
at android.os.Handler.handleCallback(Handler.java:809)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:166)
at android.app.ActivityThread.main(ActivityThread.java:7436)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:469)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:963)
Fragment Java:
public class ProfileFragment extends Fragment {
private MainActivity mMainActivity;
private SettingsViewModel settingsViewModel;
private SettingAdapter adapter;
private CoordinatorLayout coordinatorLayout;
private View fragmentView;
private TabLayout mTabLayout;
private ViewPager mViewPager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
fragmentView = inflater.inflate(R.layout.fragment_profile, container, false);
mMainActivity = new MainActivity();
androidx.appcompat.widget.Toolbar mToolbar = fragmentView.findViewById(R.id.profile_toolbar);
mMainActivity.setSupportActionBar(mToolbar);
mViewPager = (ViewPager) fragmentView.findViewById(R.id.viewpager);
ViewPagerAdapter adapter = new ViewPagerAdapter(mMainActivity.getSupportFragmentManager());
adapter.AddFragment(new ProfileInfoFragment(), "Profile");
adapter.AddFragment(new ProfileMessagingFragment(), "Messages");
mViewPager.setAdapter(adapter);
mTabLayout = (TabLayout) fragmentView.findViewById(R.id.tab_layout_profile);
mTabLayout.setupWithViewPager(mViewPager);
return fragmentView;
}
}
The Fragment XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".ProfileFragment"
android:orientation="vertical">
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/appBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme"
app:toolbarId="#id/profile_toolbar">
<com.google.android.material.appbar.CollapsingToolbarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:layout_scrollFlags="scroll|exitUntilCollapsed"
app:titleEnabled="false">
<ImageView
android:id="#+id/background_image_Toolbar"
android:layout_width="match_parent"
android:layout_height="256dp"
android:fitsSystemWindows="true"
android:scaleType="centerCrop"
app:layout_collapseMode="parallax" />
<androidx.appcompat.widget.Toolbar
android:layout_marginTop="24dp"
android:id="#+id/profile_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
app:popupTheme="#style/AppTheme" />
</com.google.android.material.appbar.CollapsingToolbarLayout>
<com.google.android.material.tabs.TabLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabGravity="fill"
app:tabMode="fixed"
android:id="#+id/tab_layout_profile"
app:tabTextColor="#color/greyText"
app:tabIndicatorColor="#color/greyText"
android:background="#fafafa"
android:elevation="0dp">
</com.google.android.material.tabs.TabLayout>
</com.google.android.material.appbar.AppBarLayout>
<androidx.viewpager.widget.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/viewpager">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.viewpager.widget.ViewPager>
Please help?
I guess you are getting that error because you are instantiating a new MainActivity object:
mMainActivity = new MainActivity();
In case of Fragments, you can call getActivity() to get the reference of the activity that is hosting your Fragment. Something like:
private MainActivity mMainActivity;
....
mMainActivity = (MainActivity) getActivity();
Or, you don't even need to cast to MainActivity since you are invoking a common method (available on Activity)
private Activity mMainActivity;
....
mMainActivity = getActivity();
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.
I have been trying to solve a problem for a few hours now, but I failed to figure it out.i try a set adapter for expandable list view but i take this error. thanks.
"Attempt to invoke virtual method 'void android.widget.ExpandableListView.setAdapter(android.widget.ExpandableListAdapter)' on a null object reference"
Main_Activity
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button b1;
private ResideMenu resideMenu;
private Context mContext;
private ResideMenuItem itemAnasayfa;
private ResideMenuItem itemRastgele;
private ResideMenuItem itemEncok;
private ResideMenuItem itemTarifyaz;
private ExpandableListView listView;
private ExpandableListAdapter listAdapter;
private List<String> listDataHeader;
private HashMap<String,List<String>> listHash;
#Override
protected void onCreate(Bundle savedInstanceState) {
listView=(ExpandableListView)findViewById(R.id.exp2);
initData();
listAdapter=new com.yeni.ExpandableListAdapter(this,listDataHeader,listHash);
listView.setAdapter(listAdapter);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
setUpMenu();
if (savedInstanceState == null) {
changeFragment(new F_ana_sayfa());
}
}
private void initData() {
listDataHeader=new ArrayList<>();
listHash=new HashMap<>();
listDataHeader.add("et");
listDataHeader.add("tavuk");
listDataHeader.add("sebze");
listDataHeader.add("diger");
List<String> l_et=new ArrayList<>();
l_et.add("kemikli");
l_et.add("kuşbaşı");
List<String> l_tavuk=new ArrayList<>();
l_tavuk.add("bonfile");
l_tavuk.add("but");
l_tavuk.add("bütün tavuk");
List<String> l_sebze=new ArrayList<>();
l_sebze.add("patates");
l_sebze.add("biber");
l_sebze.add("kabak");
l_sebze.add("patlıcan");
List<String> l_diger=new ArrayList<>();
l_diger.add("tuz");
l_diger.add("yağ");
l_diger.add("kekik");
listHash.put(listDataHeader.get(0),l_et);
listHash.put(listDataHeader.get(1),l_tavuk);
listHash.put(listDataHeader.get(2),l_sebze);
listHash.put(listDataHeader.get(3),l_diger);
}
private void setUpMenu() {
resideMenu = new ResideMenu(this);
resideMenu.setBackground(R.drawable.menu_background);
resideMenu.attachToActivity(this);
resideMenu.setMenuListener(menuListener);
resideMenu.setScaleValue(0.6f);
//create menu items;
itemAnasayfa = new ResideMenuItem(this, R.drawable.icon_home, "Ana Sayfa");
itemRastgele = new ResideMenuItem(this, R.drawable.icon_profile, "Random tarif bul");
itemEncok = new ResideMenuItem(this, R.drawable.icon_calendar, "En cok begenilenler");
itemTarifyaz = new ResideMenuItem(this, R.drawable.icon_settings, "tarif Yaz");
itemAnasayfa.setOnClickListener(this);
itemRastgele.setOnClickListener(this);
itemEncok.setOnClickListener(this);
itemTarifyaz.setOnClickListener(this);
resideMenu.addMenuItem(itemAnasayfa, ResideMenu.DIRECTION_LEFT);
resideMenu.addMenuItem(itemRastgele, ResideMenu.DIRECTION_LEFT);
resideMenu.addMenuItem(itemEncok, ResideMenu.DIRECTION_RIGHT);
resideMenu.addMenuItem(itemTarifyaz, ResideMenu.DIRECTION_RIGHT);
findViewById(R.id.title_bar_left_menu).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
resideMenu.openMenu(ResideMenu.DIRECTION_LEFT);
}
});
findViewById(R.id.title_bar_right_menu).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
resideMenu.openMenu(ResideMenu.DIRECTION_RIGHT);
}
});
}
#Override
public boolean dispatchTouchEvent(MotionEvent ev) {
return resideMenu.dispatchTouchEvent(ev);
}
#Override
public void onClick(View view) {
if (view == itemAnasayfa) {
changeFragment(new F_ana_sayfa());
} else if (view == itemRastgele) {
changeFragment(new F_rastgele_tarif());
} else if (view == itemEncok) {
changeFragment(new F_encok_beg());
} else if (view == itemTarifyaz) {
changeFragment(new F_tarif_yaz());
}
else
changeFragment(new F_ana_sayfa());
resideMenu.closeMenu();
}
private ResideMenu.OnMenuListener menuListener = new ResideMenu.OnMenuListener() {
#Override
public void openMenu() {
Toast.makeText(mContext, "Menu is opened!", Toast.LENGTH_SHORT).show();
}
#Override
public void closeMenu() {
Toast.makeText(mContext, "Menu is closed!", Toast.LENGTH_SHORT).show();
}
};
private void changeFragment(Fragment targetFragment) {
resideMenu.clearIgnoredViewList();
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.main_fragment, targetFragment, "fragment")
.setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.commit();
}
public ResideMenu getResideMenu(){
return resideMenu;}
}
Adapter Class
public class ExpandableListAdapter extends BaseExpandableListAdapter {
private Context cont;
private List<String> listDataHeader;
private HashMap<String,List<String>> listHashMap;
public ExpandableListAdapter(Context cont, List<String> listDataHeader, HashMap<String, List<String>> listHashMap) {
this.cont = cont;
this.listDataHeader = listDataHeader;
this.listHashMap = listHashMap;
}
#Override
public int getGroupCount() {
return listDataHeader.size();
}
#Override
public int getChildrenCount(int i) {
return listHashMap.get(listDataHeader.get(i)).size();
}
#Override
public Object getGroup(int i) {
return listDataHeader.get(i);
}
#Override
public Object getChild(int i, int i1) { // i=group position i=item position
return listHashMap.get(listDataHeader.get(i)).get(i1);
}
#Override
public long getGroupId(int i) {
return i;
}
#Override
public long getChildId(int i, int i1) {
return i1;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getGroupView(int i, boolean b, View view, ViewGroup viewGroup) {
String headerTitle=(String)getGroup(i);
if (view==null){
LayoutInflater inflater1=(LayoutInflater)this.cont.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view=inflater1.inflate(R.layout.list_group,null);
}
TextView lblHeader=(TextView)view.findViewById(R.id.header);
lblHeader.setTypeface(null, Typeface.BOLD);
lblHeader.setText(headerTitle);
return view;
}
#Override
public View getChildView(int i, int i1, boolean b, View view, ViewGroup viewGroup) {
final String childText=(String)getChild(i,i1);
if (view==null){
LayoutInflater inflater1=(LayoutInflater)this.cont.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view=inflater1.inflate(R.layout.list_item,null);
}
TextView txtListChild=(TextView)view.findViewById(R.id.list_item);
txtListChild.setText(childText);
return view;
}
#Override
public boolean isChildSelectable(int i, int i1) {
return true;
}
}
Activity_Main XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#android:color/white"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ExpandableListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/exp2" />
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/layout_top">
<!--<ImageView-->
<!--android:layout_width="match_parent"-->
<!--android:layout_height="3dp"-->
<!--android:background="#2ea3fe"/>-->
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<Button
android:layout_width="28dp"
android:layout_height="28dp"
android:background="#drawable/titlebar_menu_selector"
android:id="#+id/title_bar_left_menu"
android:layout_gravity="left|center_vertical"
android:layout_marginLeft="10dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="7dp"
android:text="Yemek Do"
android:textSize="24sp"
android:layout_gravity="center"
android:textColor="?attr/actionModeSplitBackground" />
<Button
android:layout_width="28dp"
android:layout_height="28dp"
android:background="#drawable/titlebar_menu_selector"
android:id="#+id/title_bar_right_menu"
android:layout_gravity="right|center_vertical"
android:layout_marginRight="10dp"/>
</FrameLayout>
<View
android:layout_width="match_parent"
android:layout_height="5dp"
android:background="#bcb8b8"/>
</LinearLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/main_fragment">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:text="Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="107dp"
android:layout_marginStart="107dp"
android:layout_marginTop="188dp"
android:id="#+id/button2" />
<Button
android:text="Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignRight="#+id/button2"
android:layout_alignEnd="#+id/button2"
android:layout_marginTop="78dp"
android:id="#+id/button3" />
</RelativeLayout>
</FrameLayout>
</LinearLayout>
list_group.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:text="TextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/header" />
</LinearLayout>
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:text="TextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/list_item" />
</LinearLayout>
error_log
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.yeni, PID: 2404
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.yeni/com.yeni.MainActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.ExpandableListView.setAdapter(android.widget.ExpandableListAdapter)'
on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
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:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.ExpandableListView.setAdapter(android.widget.ExpandableListAdapter)'
on a null object reference
at com.yeni.MainActivity.onCreate(MainActivity.java:55)
at android.app.Activity.performCreate(Activity.java:6662)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
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:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
what are you doing:
listView=(ExpandableListView)findViewById(R.id.exp2);
initData();
listAdapter=new com.yeni.ExpandableListAdapter(this,listDataHeader,listHash);
listView.setAdapter(listAdapter);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
you intialize listview object before setContentView its wrong. it should be like this
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView=(ExpandableListView)findViewById(R.id.exp2);
initData();
listAdapter=new
com.yeni.ExpandableListAdapter(this,listDataHeader,listHash);
listView.setAdapter(listAdapter);
Change your onCreate method to this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
setUpMenu();
if (savedInstanceState == null) {
changeFragment(new F_ana_sayfa());
}
listView=(ExpandableListView)findViewById(R.id.exp2);
initData();
listAdapter=new com.yeni.ExpandableListAdapter(this,listDataHeader,listHash);
listView.setAdapter(listAdapter);
}