I built a navigation drawer. When the app launches, I direct the user directly to "MainMenuActivity" activity from the MainActivity.
Inside the "MainMenuActivity", there is a button that should direct the user to another activity which is "Order List"; I applied two code parts but non is working:
The first code:
public class MainMenuActivity extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_mainmenu, container, false);
Button Orderlistbtn = (Button) rootView.findViewById(R.id.orderlistbtn);
Orderlistbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainMenuActivity.this, OrderList.class);
startActivity(intent);
}
});
return rootView;
}
}
the app doesn't run, the first code gives me the following error in the logcat:
Error:(41, 33) error: no suitable constructor found for Intent(MainMenuActivity,Class<OrderList>)
constructor Intent.Intent(String,Uri) is not applicable
(argument mismatch; MainMenuActivity cannot be converted to String)
constructor Intent.Intent(Context,Class<?>) is not applicable
(argument mismatch; MainMenuActivity cannot be converted to Context)
The second code:
public class MainMenuActivity extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_mainmenu, container, false);
Button Orderlistbtn = (Button) rootView.findViewById(R.id.orderlistbtn);
Orderlistbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), OrderList.class);
startActivity(intent);
}
});
return rootView;
}
}
but the app crashes once it launches with the following logcat error
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{package/package.MainMenuActivity}: java.lang.ClassCastException: package.MainMenuActivity cannot be cast to android.app.Activity
this is "activity_mainmenu.xml" file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:background="#android:color/background_light">
<Button
android:background="#ffff8800"
android:textColor="#android:color/white"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" My order list "
android:id="#+id/orderlistbtn"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
/>
</RelativeLayout>
getActivity() in a Fragment returns the Activity the Fragment is currently associated with .
Intent intent = new Intent(getActivity(), OrderList.class);
startActivity(intent);
Edit
Secondly, You are getting ClassCastException
Thrown to indicate that the code has attempted to cast an object to a
subclass of which it is not an instance.
Use below code to call next activity, Hope this will solve your problem
Intent intent = new Intent((ParentActivity)getActivity(), NextActivity.class);
(ParentActivity)getActivity().startActivity(myIntent);
Related
This question already has answers here:
android.content.ActivityNotFoundException:
(24 answers)
Closed 4 years ago.
i just want to open SkipActivity from MondayFragment, and fail in error. The swipe between fragments is work, but when i click on skip button move to another Activity- the app is crushed(closed):
All relevant code is attached, please help:
public class MondayFragment extends Fragment {
final String LOG_TAG="myLogs";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v=inflater.inflate(R.layout.fragment_monday, container, false);
TextView txt=(TextView) v.findViewById(R.id.skip);
txt.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
((TextView)getActivity().findViewById(R.id.skip)).setText("Access from Monday Fragment");
//Start your activity here
Intent i = new Intent(getActivity(),SkipActivity.class);
startActivity(i);
}
});
return v;
}
}
This is java Activity class :
public class SkipActivity extends AppCompatActivity {
#Override
protected void onCreate( Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.after_skip_scr);
}
}
This is MainActivity class - i think there is nothing to change here:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set the content of the activity to use the activity_main.xml layout file
setContentView(R.layout.activity_main);
// Find the view pager that will allow the user to swipe between fragments
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
// Create an adapter that knows which fragment should be shown on each page
SimpleFragmentPagerAdapter adapter = new SimpleFragmentPagerAdapter(getSupportFragmentManager());
// Set the adapter onto the view pager
viewPager.setAdapter(adapter);
}
}
Below is res-layout files: The first one is for monday fragment
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/monday_main"
android:background="#a7cbeb">
<TextView
android:id="#+id/welcome_message"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:layout_centerInParent="true"
android:textColor="#191970"
android:text="Welcome to Circles"
android:textSize="29sp"
/>
<TextView
android:id="#+id/skip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="54px"
android:textStyle="italic"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:layout_marginRight="25dp"
android:layout_marginTop="25dp"
android:text="skip"
android:textColor="#ffffff"
android:onClick="openSkipActivity"
/>
</RelativeLayout>
And this one is for main activity:
<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"
android:orientation="vertical"
tools:context="MainActivity">
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
you can call activity by :
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getActivity(), Contact_Developer.class);
getActivity().startActivity(intent);
}
});
why are you take this line
((TextView)getActivity().findViewById(R.id.skip)).setText("Access from Monday Fragment");
and share logcat error log.
or try this
decalare this
Context context;
txt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, SkipActivity.class);
context.startActivity(intent);
}
});
Your app is crashing on click event because your view is null the reason is you are trying to find out the view by using activity.findViewById which will obvious return null.
((TextView)getActivity().findViewById(R.id.skip)).setText("Access from Monday Fragment");
Change above line with this
((TextView)v.findViewById(R.id.skip)).setText("Access from Monday Fragment");
After all you are launching activity from onClick event so doesn't make sense to update the text of skip textview. but if still you want to do that, no problem.
Just replace the above line of code, it should fix your issue.
As a suggestion in case you want to update the skip textview text in on click event or any other place, create a class level instance say TextView skipTextView and initialize in onCreateView then simply use skipTextView.setTex("<text>")" all over the place where ever required.
#Dima , Try this :
public class MondayFragment extends Fragment implements OnClickListener
{
final String LOG_TAG="myLogs";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v=inflater.inflate(R.layout.fragment_monday, container, false);
// Views
TextView txt=(TextView) v.findViewById(R.id.skip);
txt.setOnClickListener(this);
return v;
}
// onClick Method
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.skip:
((TextView)getActivity().findViewById(R.id.skip)).setText("Access from Monday Fragment");
Intent i = new Intent(getActivity(),SkipActivity.class);
startActivity(i);
break;
default:
break;
}
}
}
tnx for answers!
The problem was - i didn't declare the SkipActivity in manifest file.
At the moment i did it- the app is running and i can swipe between fragments and launch another Activity from fragment.
tnx a lot!
I've been searching the error for about 2 hours on google , i can't figure out what it's wrong . It just force closes when I tap the button "butonCap", I didn't work with fragments until now
ERROR:
java.lang.IllegalStateException: Could not find method butonCap(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'cap'
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:423)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:380)
at android.view.View.performClick(View.java:6897)
at android.widget.TextView.performClick(TextView.java:12693)
at android.view.View$PerformClick.run(View.java:26101)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
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)
Butoane.java - i just made another java file because i can't write any code in the fragment java file
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_fata);
final Button butonCap = (Button) findViewById(R.id.cap);
butonCap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent butonCap = new Intent(Butoanele.this, capul.class);
Butoanele.this.startActivity(butonCap);
}
});
}
}
fragment_fata.xml - this is just one of the 2 fragments from navigation view
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".FragmentFata"
android:background="#drawable/fata">
<!-- TODO: Update blank fragment layout -->
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/cap"
android:layout_width="wrap_content"
android:layout_height="65dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="4dp"
android:background="#drawable/button_outline"
android:paddingBottom="30dp"
android:onClick="butonCap"
android:text="Cap"
android:textSize="18sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
/>
You class should extends Fragment and inflate layout in onCreateView() callback.
Call getActivity().findViewById in onViewCreated() callback.
watch this guide
In fragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_fata, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
if (getView() == null) {
return;
}
final Button butonCap = (Button) getView().findViewById(R.id.cap);
butonCap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getView().getContext(), capul.class);
startActivity(intent);
}
});
}
I need to open a new activity by clicking the button on the fragment xml file .
I have coded a bit in my fragment java file to call the new activity by clicking the button on my fragment xml file
When i run the app, it crashes
The error am getting is in the fragment java file in the line
"public void electronics(View view)"
08-02 10:58:55.654 3519-3519/com.example.mohammadzakriya.tabhost E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.mohammadzakriya.tabhost, PID: 3519
java.lang.IllegalStateException: Could not find method electronics(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'button2'
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:327)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:284)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
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"
android:orientation="vertical"
tools:context=".FolderScale">
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="1"
android:textAlignment="center" />
<Button
android:id="#+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Electronics"
android:onClick="electronics"/>
</LinearLayout>
Java
public class TopfreeFragment extends Fragment {
public TopfreeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_topfree, container, false);
}
public void electronics(View view) {
Intent intent = new Intent(getActivity(),Electronicspage.class);
startActivity(intent);
}
}
You are using electronics inside onClick and in method it is electronic not electronics
Use electronics instead of electronic
Finally got the solution for the answer with some eidt's according to my code
thanks # vrund purohit for the link How to handle button clicks using the XML onClick within Fragments .
It helped me to understand finally the code is below
// Fragment java file updated
public class TopfreeFragment extends Fragment implements View.OnClickListener {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_topfree, container, false);
Button b = (Button) v.findViewById(R.id.button2);
b.setOnClickListener(this);
return v;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button2:
Intent intent = new Intent(getActivity(),Electronicspage.class);
startActivity(intent);
break;
}
}
}
Here is another way you can use to handle click event from button:
public class TopfreeFragment extends Fragment implements View.OnClickListener{
View view;
private Button btn;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_topfree, container, false);
btn = (Button) view.findViewById(R.id.button2);
btn.setOnClickListener(this);
return view;
}
public void onClick(View view) {
switch(view.getId()) {
case R.id.button2:
startActivity(new Intent(getActivity(),Electronicspage.class));
break;
case R.id.XXXXX:
break;
// more button......
}
}
}
This article will really helpful for you: Android: how to handle button click
I encounter some issue with getting the reference to a Texview inside a Fragment, and I really have no idea why.
Here is my layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/tvSettings"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/tvLogout"
android:layout_below="#+id/tvSettings"
android:layout_marginTop="20dp"
android:layout_marginLeft="5dp"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>
And here is the Java Class
public class TabPersonnalSpace extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab_personnal_space, container, false);
TextView tvSettings = (TextView)rootView.findViewById(R.id.tvSettings);
Log.d("Debug", tvSettings.getText().toString());
tvSettings.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), "Settings", Toast.LENGTH_SHORT);
}
});
return rootView;
}
}
Thing is : I get the text printed to the logcat when swipe to the Fragment, and nothing happened when I click on the TextView.
Does anyone have a clue for me?
You forget .show() to display Toast
Toast.makeText(getActivity(), "Settings", Toast.LENGTH_SHORT).show();
implement onViewCreated like this :
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//instantiate tvSettings
TextView tvSettings = (TextView)rootView.findViewById(R.id.tvSettings);
}
I'm writing and android 4.4 project using android studio.
I'm new to the fragments idea and trying to create a simple application with a button that the click handler sends a message to the log.
this is the fragment class
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_menu, container, false);
return rootView;
}
public void addStringClickHandler(View v) {
Log.d("tag","hello");
}
}
this is the fragment layout XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.tuxin.myalcoholist.myalcoholist.myalcoholist.MainMenuActivity$PlaceholderFragment">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/add_drink"
android:id="#+id/add_drink"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="36dp"
android:onClick="addStringClickHandler" />
</RelativeLayout>
as you can see i set in the XML android:onclick to addStringClickHandler
and in the fragment class i created that function, but when I execute the application
I get an error that the runtime could not find a method addStringClickHandler(view)
what am I missing?
Your android:onClick handler method has to belong to the Activity hosting your fragment. Just move addStringClickHandler() method to the activity.
If you want to have a listener method in the fragment you have to set listener in the code like this.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_menu, container, false);
rootView.findViewById(R.id.add_drink).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.d("tag","hello");
}
});
return rootView;
}
Try to register the onClick method when inflating the view.
View rootView = inflater.inflate(R.layout.fragment_main_menu, container, false);
rootView.findViewById(R.id.add_drink).setOnClickListener(new OnClickListener() {
public void onClick(View view) {
// do what you need
}
});
return rootView;
Or you can set the fragment to be the on click listener
View rootView = inflater.inflate(R.layout.fragment_main_menu, container, false);
rootView.findViewById(R.id.add_drink).setOnClickListener(this);
return rootView;
and then make the fragment implement OnClickListener.