Adding code to Fragment files in Bottomnavigtaionview - java

I want to know how to code inside a fragment.java file. Firstly, I am a beginner in coding. I have created a Bottomnavigationview with three navigation buttons in the bottomnaviation bar and I have created Fragment activity for each of the navigation buttons. One of the navigation options in the bottom navigation bar is 'more' and I have added a button with the id "btn_Logoff". when I click the button I want it to go the activity_login.xml or LoginActivity.java. I dont know what is the code for that and where to add the code in the default fragment java file so here is what is written on the fragment file by default:
filename is MoreFragment.java
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link MoreFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link MoreFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class MoreFragment 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;
public MoreFragment() {
// 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 MoreFragment.
*/
// TODO: Rename and change types and number of parameters
public static MoreFragment newInstance(String param1, String param2) {
MoreFragment fragment = new MoreFragment();
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_more, container, false);
}
// 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 onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
Toast.makeText(context, "Notification Fragment Attached", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
Ive been having a lot of trial and errors and still no resolution. Any help appreciated. Thank you.

Can you explain this part?
when I click the button I want it to go the activity_login.xml or LoginActivity.java.
Do you want to execute something in activity after click on button in fragment, am I right?
You can do it for some ways. Easiest is set listener that listening when you clicking on the button.
Create interface:
public interface OnNavigationButtonClickListener {
void onMoreClick();
}
Create listener variable in fragment:
private OnNavigationButtonClickListener navigationListener;
and setter for it:
public void setNavigationListener(OnNavigationButtonClickListener listener) {
this.navigationListener = listener;
}
3.Notify your listeners in fragment on more button click:
onMoreButton.setOnClickListener(new OnClickListener {
navigationListener.onMoreClick();
});
4. Then set listener in your activity:
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fragment.setNavigationListener(new OnNavigationButtonClickListener() {
#Override
public void onMoreClick() {
// you clicked 'more' button in fragment
// do what you want
}
});

Assuming thay you already identified btn_Logoff with the findViewById and everything
all you need to do is add a onclickListener that launchs the activity you want, your code for the clicklistener will look similar to this
Button btn_Logoff;
your class{
btn_Logoff = (Button) findViewById(R.id.IdOfYourBtnInTheXmlFile);
btn_Logoff.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(intent);
}
});
}

Related

Android Fragment argument bundle: getString returning null when key exists

I am pretty confident I'm missing something simple here. Apologies in advance, I'm new to Android.
So far my app sends a request to the Strava OAuth server, which returns to my app's implicit deep link via the callback URI I used in the request. I'm trying to get the 'code' and the 'scope' arguments that are passed with the callback URI passed to the fragment. The argument received is this, found via getArguments.
Bundle[{android-support-nav:controller:deepLinkIntent=Intent { act=android.intent.action.VIEW cat=[android.intent.category.BROWSABLE] dat=myapp://localhost/fibonacci/itemFragment?state=&code=d37efb9e5b66325ddd34614c41550dd1c00d8444&scope=read,activity:read_all,read_all flg=0x1440c000 cmp=com.example.fibonacci/.MainActivity (has extras) }}]
When I inspect the bundle variable while debugging I also see a hierarchy that includes this:
bundle -> mMap -> value[0] -> mData -> uriString
The uriString is a subset of the overall bundle derived from the arguments to the Fragment:
myapp://localhost/fibonacci/itemFragment?state=&code=d37efb9e5b66325ddd34614c41550dd1c00d8444&scope=read,activity:read_all,read_all
The code I've been experimenting with is below (see onCreate() ). I'm obviously doing something in a way that is too naive, because it is returning null for the things I'm trying to get out of the argument bundle. If there's a page in the Android documentation that I've overlooked I'd appreciate a link or suggestion.
Thanks!
package com.example.fibonacci;
import android.content.Context;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.fibonacci.dummy.DummyContent;
/**
* A fragment representing a list of Items.
*/
public class ItemFragment extends Fragment {
// TODO: Customize parameter argument names
private static final String ARG_COLUMN_COUNT = "column-count";
private static final String ARG_STRAVA_CODE = "code";
private static final String ARG_STRAVA_SCOPE = "scope";
private static final String ARG_STRAVA_URISTRING = "uriString";
// TODO: Customize parameters
private int mColumnCount = 1;
private String mCode = null;
private String mScope = null;
private String mUriString = null;
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public ItemFragment() {
}
// TODO: Customize parameter initialization
#SuppressWarnings("unused")
public static ItemFragment newInstance(int columnCount) {
ItemFragment fragment = new ItemFragment();
Bundle args = new Bundle();
args.putInt(ARG_COLUMN_COUNT, columnCount);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get arguments
if (getArguments() != null) {
mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT);
Bundle bundle = getArguments();
mUriString = bundle.getString(ARG_STRAVA_URISTRING);
mCode = bundle.getString(ARG_STRAVA_CODE);
mScope = bundle.getString(ARG_STRAVA_SCOPE);
}
// GET the refresh and short-lived access token
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_item_list, container, false);
// Set the adapter
if (view instanceof RecyclerView) {
Context context = view.getContext();
RecyclerView recyclerView = (RecyclerView) view;
if (mColumnCount <= 1) {
recyclerView.setLayoutManager(new LinearLayoutManager(context));
} else {
recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
}
recyclerView.setAdapter(new MyItemRecyclerViewAdapter(DummyContent.ITEMS));
}
return view;
}
}
Edit: I also don't understand why the 'column-count' argument doesn't show up in the bundle. That one was auto-created by the Fragment template I chose, but I would expect it to be in the overall bundle.
What I was missing was that the Bundle had a full Intent object inside of it. I had to query the Intent from the fragment's Activity with the code below:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get arguments
if (getArguments() != null) {
mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT);
Bundle bundle = getArguments();
Intent intent = getActivity().getIntent();
Uri data = intent.getData();
mCode = data.getQueryParameter(ARG_STRAVA_CODE);
mScope = data.getQueryParameter(ARG_STRAVA_SCOPE);
}
// GET the refresh and short-lived access token
}

onClick: Method can not be found [duplicate]

This question already has answers here:
Android Fragment onClick button Method
(7 answers)
Closed 2 years ago.
I am very new to Android Studio. What I want is simple: I press on a button and something should happen.
So I have a button in my fragment that looks in XML like this:
<Button
android:id="#+id/button"
android:layout_width="match_parent"
android:layout_height="60dp"
android:gravity="center_vertical"
android:text="#string/hello"
android:onClick="doSumth"
/>
My code in GeneralFragment.java looks like this:
package ch.yourclick.kitt.fragments;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import ch.yourclick.kitt.R;
/**
* A simple {#link Fragment} subclass.
* Use the {#link GeneralFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class GeneralFragment extends Fragment {
public GeneralFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #return A new instance of fragment General.
*/
// TODO: Rename and change types and number of parameters
public static GeneralFragment newInstance() {
GeneralFragment fragment = new GeneralFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_general, container, false);
}
public void doSumth() {
System.out.println("Hello");
}
}
My problem is that I get the error:
java.lang.IllegalStateException: Could not find method doSumth(View) in a parent or ancestor Context for android:onClick attribute defined on view class androidx.appcompat.widget.App
What am I doing wrong?
You have to add a View argument to a function. It has to look like this:
public void doSumth(View view)
{
System.out.println("Hello");
}
Responding to Click Events - Android docs
Also You can make it in code like this:
public class MainActivity extends AppCompatActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button bt1 = (Button) findViewById(R.id.b1);
bt1.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
System.out.println("Hello");
}
});
}
}
You need add a View parameter in your method. When you use android:onClick in XML , the method need a view like parameter.
The this code:
public void doSumth(View view) {
System.out.println("Hello");
}

Is there a method like setResult() in fragment?

I am using a fragment. I am getting an error in the onResult() method. I need a substitute method for setResult(RESULT_OK, data) that I can use in my fragment. Please help.
CalendarFragment:
package app.pal.study.samplestudy;
import android.app.Fragment;
import android.content .Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import java.util.Date;
import java.util.List;
public class CalendarFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_calendar, container, false);
return rootView;
}
#Override
public void onResume() {
super.onResume();
refresh();
}
private void refresh() {
CalendarEventDataSource dataSource = new CalendarEventDataSource(getActivity());
dataSource.openReadOnlyDB();
final List<CalendarEvent> calendarEvents = dataSource.getAllEvents();
dataSource.close();
CalAllEventsListAdapter adapter = new CalAllEventsListAdapter(calendarEvents);
ListView listView = (ListView) getView().findViewById(R.id.all_event_list);
listView.setAdapter(adapter);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
end();
return true;
}
return super.onOptionsItemSelected(item);
}
public void onBackPressed() {
end();
}
private void end() {
Intent data = new Intent();
data.putExtra(Constants.DATE_KEY, (Date)(getArguments().get(Constants.DATE_KEY)));
setResult(RESULT_OK, data);
}
}
You should call it on your fragment owning activity:
getActivity().setResult(Activity.RESULT_OK, data)
also you might want to finish your activity:
getActivity().finish();
If you starting your fragment from another fragment.
You need to use:
/**
* Optional target for this fragment. This may be used, for example,
* if this fragment is being started by another, and when done wants to
* give a result back to the first. The target set here is retained
* across instances via {#link FragmentManager#putFragment
* FragmentManager.putFragment()}.
*
* #param fragment The fragment that is the target of this one.
* #param requestCode Optional request code, for convenience if you
* are going to call back with {#link #onActivityResult(int, int, Intent)}.
*/
public void setTargetFragment(Fragment fragment, int requestCode) {
}
When starting your Fragment.
Like this:
Fragment newFragment = new YourFragment();
newFragment .setTargetFragment(this, SOME_REQUEST_INT);
And then, in YourFragment
Intent data = new Intent();
data.putExtra(Constants.DATE_KEY, (Date)(getArguments().get(Constants.DATE_KEY)));
getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, intent);
Or
getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_CANCELED, null);
Use this it may be help to you..
getActivity().setResult(Activity.RESULT_OK, data);
Use
getActivity().setResult(Activity.RESULT_OK, data);

Inconsistency errors between android.support.v4.app and android.app

I'm trying to create an activity that shows some fragments. I'm following this example here: http://developer.android.com/training/animation/screen-slide.html, however there seems to be some missing code / inconsistencies. I've narrowed down many of the problems but I'm stuck on one part, though it seems it would be simple to someone that knows how this works.
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm); // error on fm
}
error underlines fm on super(fm);: "FragmentStatePagerAdapter (android.support.v4.app.FragmentManager) in FragmentStatePagerAdapter cannot be applied to (android.app.FragmentManager)"
#Override
public Fragment getItem(int position) { // error on Fragment
return ScreenSlidePageFragment.create(position);
}
error underlines Fragment on public Fragment getItem(int position) {: 'getItem(int)' in 'com.example.Application.ScreenSlideActivity.ScreenSlidePagerAdapter' clashes with 'getItem(int)' in 'android.support.v4.app.FragmentStatePagerAdapter'; attempting to use incompatible return type
ScreenSlideActivity.java:
package com.example.dgzl.corvegas;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.NavUtils;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;
/**
* Demonstrates a "screen-slide" animation using a {#link ViewPager}. Because {#link ViewPager}
* automatically plays such an animation when calling {#link ViewPager#setCurrentItem(int)}, there
* isn't any animation-specific code in this sample.
*
* <p>This sample shows a "next" button that advances the user to the next step in a wizard,
* animating the current screen out (to the left) and the next screen in (from the right). The
* reverse animation is played when the user presses the "previous" button.</p>
*
* #see ScreenSlidePageFragment
*/
public class ScreenSlideActivity extends android.support.v4.app.FragmentActivity {
/* The number of pages (wizard steps) to show in this demo.*/
private static final int NUM_PAGES = 3;
/* The pager widget, which handles animation and allows swiping horizontally to access previous
* and next wizard steps.*/
private ViewPager mPager;
/* The pager adapter, which provides the pages to the view pager widget.*/
private PagerAdapter mPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen_slide);
// Instantiate a ViewPager and a PagerAdapter.
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getFragmentManager());
mPager.setAdapter(mPagerAdapter);
mPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// When changing pages, reset the action bar actions since they are dependent
// on which page is currently active. An alternative approach is to have each
// fragment expose actions itself (rather than the activity exposing actions),
// but for simplicity, the activity provides the actions in this sample.
invalidateOptionsMenu();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.activity_screen_slide, menu);
menu.findItem(R.id.action_prev).setEnabled(mPager.getCurrentItem() > 0);
// Add either a "next" or "finish" button to the action bar, depending on which page
// is currently selected.
MenuItem item = menu.add(Menu.NONE, R.id.action_next, Menu.NONE,
(mPager.getCurrentItem() == mPagerAdapter.getCount() - 1)
? "action_finish"
: "action_next");
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// Navigate "up" the demo structure to the launchpad activity.
// See http://developer.android.com/design/patterns/navigation.html for more.
NavUtils.navigateUpTo(this, new Intent(this, MainActivity.class));
return true;
case R.id.action_previous:
// Go to the previous step in the wizard. If there is no previous step,
// setCurrentItem will do nothing.
mPager.setCurrentItem(mPager.getCurrentItem() - 1);
return true;
case R.id.action_next:
// Advance to the next step in the wizard. If there is no next step, setCurrentItem
// will do nothing.
mPager.setCurrentItem(mPager.getCurrentItem() + 1);
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A simple pager adapter that represents 5 {#link ScreenSlidePageFragment} objects, in
* sequence.
*/
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return ScreenSlidePageFragment.create(position);
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
}
ScreenSlidePageFragment.java"
package com.example.Application
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class ScreenSlidePageFragment extends Fragment {
public static final String ARG_PAGE = "page";
private int mPageNumber;
public static ScreenSlidePageFragment create(int pageNumber) {
ScreenSlidePageFragment fragment = new ScreenSlidePageFragment();
Bundle args = new Bundle();
args.putInt(ARG_PAGE, pageNumber);
fragment.setArguments(args);
return fragment;
}
public ScreenSlidePageFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPageNumber = getArguments().getInt(ARG_PAGE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout containing a title and body text.
ViewGroup rootView = (ViewGroup) inflater
.inflate(R.layout.fragment_today, container, false);
// Set the title view to show the page number.
((TextView) rootView.findViewById(android.R.id.text1)).setText(
getString(R.string.title_template_step, mPageNumber + 1));
return rootView;
}
/**
* Returns the page number represented by this fragment object.
*/
public int getPageNumber() {
return mPageNumber;
}
}
You must import Fragment and FragmentManager class from support library please change your first two lines of import like below in your ScreenSlideActivity class
import android.support.v4.app.FragmentManager
import android.support.v4.app.Fragment

Android Studio: Creating a Swipe Tab Application that Reads Fragments. Forced Close

I'm essentially a new Android Studio developer and currently I am attempting to switch between 3 tabs for my program. Unfortunately, the program forces a close when I try to open things up. I'm not entirely sure where the problem lies since I declared an instance of the classes in regards to the tab.
MainActivity.java
import java.util.Locale;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.support.v13.app.FragmentPagerAdapter;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class Main extends Activity implements ActionBar.TabListener {
Fragment FragmentTab1 = new Tab1();
Fragment FragmentTab2 = new Tab2();
Fragment FragmentTab3 = new Tab3();
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v13.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(
actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.auth_port, menu);
return true;
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
Fragment fragment = null;
if (position == 0)
{
fragment = FragmentTab1;
}
if (position == 1)
{
fragment = FragmentTab2;
}
if (position == 2)
{
fragment = FragmentTab3;
}
return fragment;
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
Tab1 (The Other 2 Tabs are the same)
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link Tab1.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link Charge#newInstance} factory method to
* create an instance of this fragment.
*
*/
public class Tab1 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;
/**
* 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 Tab1
*/
// TODO: Rename and change types and number of parameters
public static Charge newInstance(String param1, String param2) {
Tab1 fragment = new Tab1();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public Tab1() {
// Required empty public constructor
}
#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_tab1, container, false);
}
// 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 onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
}
I've looked on other websites for help on this, mostly they cover programs that are obsolete or don't cover the question completely, I have nothing else to turn to so any help on this problem I'd appreciate it.
Edit: I've learned it has to do with creating a .newinstance of the class but how this gets accomplished I haven't quite grasped yet.
Logcat output. Only included error portion
10-29 21:04:04.599 9452-9452/com.example.main
E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.authpayx.authportbeta04, PID: 9452
java.lang.ClassCastException: com.example.main.main#42d45398 must implement
OnFragmentInteractionListener
at com.example.main.Tab1.onAttach(Tab1.java:84)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:849)
at android.app.FragmentManagerImpl.performPendingDeferredStart(FragmentManager.java:785)
at android.app.Fragment.setUserVisibleHint(Fragment.java:997)
at android.support.v13.app.FragmentCompatICSMR1.setUserVisibleHint(FragmentCompatICSMR1.java:23)
at android.support.v13.app.FragmentCompat$ICSMR1FragmentCompatImpl.setUserVisibleHint(FragmentCompat.java:48)
at android.support.v13.app.FragmentCompat.setUserVisibleHint(FragmentCompat.java:76)
at android.support.v13.app.FragmentPagerAdapter.setPrimaryItem(FragmentPagerAdapter.java:134)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1071)
at android.support.v4.view.ViewPager.populate(ViewPager.java:919)
at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1441)
at android.view.View.measure(View.java:17478)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5364)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:17478)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5364)
at com.android.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:412)
at android.view.View.measure(View.java:17478)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5364)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2548)
at android.view.View.measure(View.java:17478)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2262)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1391)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1590)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1249)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6585)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:803)
at android.view.Choreographer.doCallbacks(Choreographer.java:603)
at android.view.Choreographer.doFrame(Choreographer.java:573)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:789)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5579)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
at dalvik.system.NativeStart.main(Native Method)
You must implement OnFragmentInteractionListener inside your main activity.
change
public class Main extends Activity implements ActionBar.TabListener
to
public class Main extends Activity implements ActionBar.TabListener, OnFragmentInteractionListener
Then make sure your implement
public void onFragmentInteraction(Uri uri);
inside your main activity.
A little info on the new instance method. This is a common practice not a special method you are implementing. You can call it anything that you want but the idea is that new instance method takes your parameters and adds them to a bundle. when android destroys your fragment it gets recreated using its default constructor which does not have your data.
The solution is to use a new instance method and put your data in a bundle because when android recreates your fragment its bundle sticks around.
The only time you would not care about new instance is when you are not passing anything into your fragment.
It seems that this issue related to your Tab1 Fragment class. Also it seems that you created this Fragment class by android studio auto generated blank Fragment class.
For fixing this issue you can change codes of auto generated Fragment classes like Tab1 with code like below.
package com.example.android.actionbarcompat.styled;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by taher on 1/7/15.
*/
public class MainFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.main_view, container, false);
}
}
If you want to use your Tab1 fragment class please not that below comment from your Fragment Class.
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
I had the same problem, and in my case,
delete
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
these code, problem solved

Categories