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.
Related
My Android app crashes when resuming after being killed by OS due to low memory.
So I have built the smallest possible app to reproduce the bug.
My app is composed of a MainActivity, which contains 1 page in a viewPager2, which contains a fragment.
This fragment is added dynamically by replacing "structure_placeholder" (in the real app, the type of fragment depends on some parameters)
MainActivity.java:
public class MainActivity extends AppCompatActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this);
ViewPager2 viewPage = findViewById(R.id.viewpager);
viewPage.setAdapter(sectionsPagerAdapter);
}
/***************************************************************************/
class SectionsPagerAdapter extends FragmentStateAdapter
{
private SectionsPagerAdapter(FragmentActivity fa)
{
super(fa);
}
#NonNull #Override
public Fragment createFragment(int position)
{
return new MyPageFragment();
}
#Override
public int getItemCount()
{
return 1;
}
}
}
activity_main.xml:
<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"
tools:context=".MainActivity">
<androidx.viewpager2.widget.ViewPager2
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
MyPageFragment.java:
public class MyPageFragment extends Fragment
{
public MyPageFragment()
{ /* Required empty public constructor*/}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.inflate(R.layout.my_page_fragment, container, false);
}
#Override
public void onStart()
{
super.onStart();
Fragment listFragment = SubFragment.newInstance();
FragmentTransaction ft = requireActivity().getSupportFragmentManager().beginTransaction();
ft.replace(R.id.structure_placeholder, listFragment);
ft.commit();
}
}
my_page_fragment.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context=".MyPageFragment">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_blank_fragment" />
<FrameLayout
android:id="#+id/structure_placeholder"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
tools:layout_width="100dp"
tools:layout_height="150dp"
tools:background="#color/design_default_color_secondary"
>
</FrameLayout>
</LinearLayout>
SubFragment.java:
public class SubFragment extends Fragment
{
public SubFragment()
{ /* Required empty public constructor*/ }
public static SubFragment newInstance()
{
SubFragment fragment = new SubFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.inflate(R.layout.sub_fragment, container, false);
}
}
sub_fragment.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/line1" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/line2" />
</LinearLayout>
Here is the error log when resuming the app after it has been killed:
2021-11-19 15:46:55.739 8298-8298/com.delrocq.mytestapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.delrocq.mytestapp, PID: 8298
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.delrocq.mytestapp/com.delrocq.mytestapp.MainActivity}: java.lang.IllegalArgumentException: No view found for id 0x7f0801db (com.delrocq.mytestapp:id/structure_placeholder) for fragment SubFragment{9eb5496} (ada1c808-c885-49ed-9cd3-f4de1855c6af id=0x7f0801db)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2957)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6944)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
Caused by: java.lang.IllegalArgumentException: No view found for id 0x7f0801db (com.delrocq.mytestapp:id/structure_placeholder) for fragment SubFragment{9eb5496} (ada1c808-c885-49ed-9cd3-f4de1855c6af id=0x7f0801db)
I tried to put some logs to understand the lifecycle of the activity/fragments, but it did not help.
What am I doing wrong?
I finally found the solution after hours of searching and many wrong tracks.
Inside a fragment, getChildFragmentManager() shall be used instead of getSupportFragmentManager().
It is so easy when you know it :)
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 am developing an application in which I want to insert data in firebase, but when I want to open the fragment in the application I get an error.
I am using nav_graph for navigation between screens and I am also using movile_navigation. I don't know if that is information that could be important.
This is the java code, I don't know what causes the error:
```
public class Pantalla1Fragment extends Fragment{
TextView editTextName;
TextView editTextEdad;
TextView editTextApellidos;
TextView editTextGenero;
TextView editPadecimientos;
TextView editTextObservaciones;
TextView getEditTextTratamientos;
Button btnRegistar;
FirebaseAuth mAuth;
DatabaseReference mDatabase;
// 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";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public Pantalla1Fragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment Pantalla1Fragment.
*/
// TODO: Rename and change types and number of parameters
public static Pantalla1Fragment newInstance(String param1, String param2) {
Pantalla1Fragment fragment = new Pantalla1Fragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
/*#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}*/
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_pantalla1, container, false);
}
#Override
public void onViewCreated(#NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
editTextName = view.findViewById(R.id.editTextName);
editTextEdad = view.findViewById(R.id.editTextEdad);
editTextApellidos = view.findViewById(R.id.editTextApellidos);
editTextGenero = view.findViewById(R.id.editTextGenero);
editPadecimientos = view.findViewById(R.id.editTextPadesimientos);
editTextObservaciones = view.findViewById(R.id.editTextObservaciones);
getEditTextTratamientos = view.findViewById(R.id.editTextTratamientos);
btnRegistar = view.findViewById(R.id.btnRegistar);
btnRegistar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
registerPerfil();
}
});
}
public void registerPerfil() {
String nombre=editTextName.getText().toString();
String apellidos=editTextApellidos.getText().toString();
String edad=editTextEdad.getText().toString();
String genero=editTextGenero.getText().toString();
String padecimientos=editPadecimientos.getText().toString();
String tratamiento=getEditTextTratamientos.getText().toString();
String observaciones=editTextObservaciones.getText().toString();
if(!TextUtils.isEmpty(nombre)){
String id=mDatabase.push().getKey();
Registro_Perfiles perfil = new Registro_Perfiles(nombre, apellidos, edad, genero, padecimientos, tratamiento, observaciones);
mDatabase.child("Users").child(id).setValue(perfil);
//Toast.makeText(this, "Datos introducidos", Toast.LENGTH_LONG).show();
}
}
}
And this part is the fragment view:
<?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=".Pantalla1Fragment">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
android:padding="15dp"
app:layout_constraintTop_toTopOf="parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Nombre" />
<EditText
android:id="#+id/editTextName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:hint="#string/editTextNombre" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Apellidos" />
<EditText
android:id="#+id/editTextApellidos"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:hint="Apellidos" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Edad" />
<EditText
android:id="#+id/editTextEdad"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:hint="Edad" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Genero" />
<EditText
android:id="#+id/editTextGenero"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:hint="Genero" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Padesimientos" />
<EditText
android:id="#+id/editTextPadesimientos"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:hint="Padesimientos" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Tratamientos" />
<EditText
android:id="#+id/editTextTratamientos"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:hint="Tratamientos" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Observaciones" />
<EditText
android:id="#+id/editTextObservaciones"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:hint="Observaciones" />
<Button
android:id="#+id/btnRegistar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="REGISTRAR NUEVO PERFIL" />
</LinearLayout>
</ScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>
Error in the logcat
--------- beginning of crash
2020-08-26 12:13:05.893 17635-17635/com.example.thebestapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.thebestapp, PID: 17635
java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.firebase.database.DatabaseReference com.google.firebase.database.DatabaseReference.push()' on a null object reference
at com.example.thebestapp.Pantalla1Fragment.registerPerfil(Pantalla1Fragment.java:126)
at com.example.thebestapp.Pantalla1Fragment$1.onClick(Pantalla1Fragment.java:111)
at android.view.View.performClick(View.java:6297)
at android.view.View$PerformClick.run(View.java:24797)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6626)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:811)
You should never be using getActivity().findViewById in a Fragment.
Instead, override onViewCreated() and use view.findViewById() - the view that is passed to that method is the view you inflated in onCreateView():
#Override
public void onViewCreated(#NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
editTextName = view.findViewById(R.id.editTextName);
editTextEdad = view.findViewById(R.id.editTextEdad);
editTextApellidos = view.findViewById(R.id.editTextApellidos);
editTextGenero = view.findViewById(R.id.editTextGenero);
editPadecimientos = view.findViewById(R.id.editTextPadesimientos);
editTextObservaciones = view.findViewById(R.id.editTextObservaciones);
getEditTextTratamientos = view.findViewById(R.id.editTextTratamientos);
btnRegistar = view.findViewById(R.id.btnRegistar);
btnRegistar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
registerPerfil();
}
});
}
I am facing some problem when calling onCheckedCahngedListener inside fragment on radio group app crashes.
when clicking on any item inside radio group the app crashed.
fragment_sell.xml
<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"
tools:context="com.example.syedsaadali.myapplication.SellFragment"
android:orientation="vertical">
<HorizontalScrollView
android:id="#+id/scrollView"
android:layout_width="wrap_content"
android:layout_height="75dp"
android:layout_gravity="center"
android:background="#FFFFFF"
android:fillViewport="true"
android:measureAllChildren="false"
android:scrollbars="none">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<RadioGroup
android:id="#+id/RadioButton1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:checkedButton="#+id/first"
>
<RadioButton
android:id="#+id/sApartment"
android:layout_width="100dp"
android:layout_height="fill_parent"
android:button="#drawable/apartment"
android:padding="15dp"
android:onClick="apartment"/>
<TextView
android:layout_width="0.2dp"
android:layout_height="fill_parent"
android:layout_alignParentRight="true"
android:background="#mipmap/vertical" />
<RadioButton
android:id="#+id/sBuilder"
android:layout_width="100dp"
android:layout_height="fill_parent"
android:button="#drawable/house"
android:padding="15dp"
android:onClick="house"/>
<TextView
android:layout_width="0.2dp"
android:layout_height="fill_parent"
android:layout_alignParentRight="true"
android:background="#mipmap/vertical" />
<RadioButton
android:id="#+id/sPlot"
android:layout_width="100dp"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:button="#drawable/land"
android:padding="15dp"
android:onClick="land"/>
<TextView
android:layout_width="0.2dp"
android:layout_height="fill_parent"
android:layout_alignParentRight="true"
android:background="#mipmap/vertical" />
<RadioButton
android:id="#+id/sHouse"
android:layout_width="100dp"
android:layout_height="match_parent"
android:button="#drawable/builder"
android:padding="15dp"
android:onClick="builder"/>
<TextView
android:layout_width="0.2dp"
android:layout_height="fill_parent"
android:layout_alignParentRight="true"
android:background="#mipmap/vertical" />
<RadioButton
android:id="#+id/sStudioApartment"
android:layout_width="100dp"
android:layout_height="fill_parent"
android:button="#drawable/farmhouse"
android:padding="15dp"
android:onClick="farmhouse"/>
<TextView
android:layout_width="0.2dp"
android:layout_height="fill_parent"
android:layout_alignParentRight="true"
android:background="#mipmap/vertical" />
<RadioButton
android:id="#+id/sFarmHouse"
android:layout_width="100dp"
android:layout_height="fill_parent"
android:button="#drawable/serviceapartment"
android:padding="15dp"
android:onClick="servicedapartment"/>
<TextView
android:layout_width="0.2dp"
android:layout_height="fill_parent"
android:layout_alignParentRight="true"
android:background="#mipmap/vertical" />
<RadioButton
android:id="#+id/sServicedApartment"
android:layout_width="100dp"
android:layout_height="fill_parent"
android:button="#drawable/studioapartment"
android:padding="15dp"
android:onClick="studioapartment"/>
<TextView
android:layout_width="0.2dp"
android:layout_height="fill_parent"
android:layout_alignParentRight="true"
android:background="#mipmap/vertical" />
</RadioGroup>
</LinearLayout>
</HorizontalScrollView>
SellFragment.java
public class SellFragment 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";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
private RadioGroup mRadioGroup1;
private RadioButton mapartment;
private RadioButton mBuilder;
private RadioButton mplot;
private RadioButton mHouse;
private RadioButton mStudioApartment;
private RadioButton mFarmhouse;
private RadioButton mServicedApartment;
private Spinner city;
private View layout;
public static SellFragment newInstance(String param1, String param2) {
SellFragment fragment = new SellFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
layout = inflater.inflate(R.layout.fragment_sell, container, false);
mRadioGroup1=(RadioGroup) layout.findViewById(R.id.RadioButton1);
mapartment=(RadioButton)layout.findViewById(R.id.sApartment);
mBuilder=(RadioButton)layout.findViewById(R.id.sBuilder);
mplot=(RadioButton)layout.findViewById(R.id.sPlot);
mHouse=(RadioButton)layout.findViewById(R.id.sHouse);
mStudioApartment=(RadioButton)layout.findViewById(R.id.sStudioApartment);
mFarmhouse=(RadioButton)layout.findViewById(R.id.sFarmHouse);
mServicedApartment=(RadioButton)layout.findViewById(R.id.sServicedApartment);
mRadioGroup1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId == R.id.sApartment) {
Toast.makeText(getActivity(), "Sell Fragment", Toast.LENGTH_SHORT).show();
} else if (checkedId == R.id.sBuilder) {
Toast.makeText(getActivity(), "Sell Fragment", Toast.LENGTH_SHORT).show();
}
else if (checkedId == R.id.sPlot) {
Toast.makeText(getActivity(), "Sell Fragment", Toast.LENGTH_SHORT).show();
}
else if (checkedId == R.id.sHouse) {
Toast.makeText(getActivity(), "Sell Fragment", Toast.LENGTH_SHORT).show();
}
else if (checkedId == R.id.sStudioApartment) {
Toast.makeText(getActivity(), "Sell Fragment", Toast.LENGTH_SHORT).show();
}
else if (checkedId == R.id.sFarmHouse) {
Toast.makeText(getActivity(), "Sell Fragment", Toast.LENGTH_SHORT).show();
}
else if (checkedId == R.id.cServicedApartment) {
Toast.makeText(getActivity(), "Sell Fragment", Toast.LENGTH_SHORT).show();
}
}
});
return layout;
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}}
Logcat:
03-23 02:50:57.703 4697-4697/com.example.syedsaadali.myapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.syedsaadali.myapplication, PID: 4697
java.lang.IllegalStateException: Could not find method apartment(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatRadioButton with id 'cApartment'
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:307)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:266)
at android.view.View.performClick(View.java:4780)
at android.widget.CompoundButton.performClick(CompoundButton.java:120)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
You have defined <RadioButton ... android:onClick="apartment"/> In the XML But any method apartment was not created in Activity.
To resolve this Either remove that onClick attribute (if note needed) OR create a method apartment in java as well like
public void apartment(View view){
}
You can directly click Alt + Enter in onClick attribute of XML to get the hint of resolving this error by creating method.