Is there a method like setResult() in fragment? - java

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);

Related

Adding code to Fragment files in Bottomnavigtaionview

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);
}
});
}

Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?

Am new in android, trying to go to the next Activity through an Adapter, and i am using onBindViewHolder() with an Intent , below is the code :
#Override
public void onBindViewHolder(CurrencyViewHolder holder, int position) {
final BureauRateObject br = itemList.get(position);
holder.bureauname.setText(br.getBureau_name());
holder.rates.setText(br.getBuysell());
final String BureauId = br.getBureau_id();
final String BureauName = br.getBureau_name();
holder.root.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(context, SingleForexActivity.class);
// i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("bureau_id", BureauId);
i.putExtra("bureau_name",BureauName);
context.startActivity(i);
}
});
}
and this is the error which comes :
android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
at android.app.ContextImpl.startActivity(ContextImpl.java:677)
at android.app.ContextImpl.startActivity(ContextImpl.java:664)
at android.content.ContextWrapper.startActivity(ContextWrapper.java:331)
at Adapters.CurrencySelectorAdapter$1.onClick(CurrencySelectorAdapter.java:64)
at android.view.View.performClick(View.java:5265)
at android.view.View$PerformClick.run(View.java:21534)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5728)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
I tried out this solution , but the Next Activity doesn't goes back to the previous Activity.
My solution :(But didn't work)
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Below is the entire Adapter code:
package Adapters;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.example.naavanito.eamobileforex2.R;
import com.example.naavanito.eamobileforex2.SingleForexActivity;
import java.util.Currency;
import java.util.List;
import Holders.CurrencyViewHolder;
import model.BureauRateObject;
/**
* Created by Admin on 1/21/2017.
*/
public class CurrencySelectorAdapter extends RecyclerView.Adapter<CurrencyViewHolder> {
private List<BureauRateObject> itemList;
private Context context;
public CurrencySelectorAdapter(List<BureauRateObject> itemList, Context context) {
this.itemList = itemList;
this.context = context;
}
#Override
public CurrencyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View layoutview = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_currency_rate,parent,false);
CurrencyViewHolder rcv = new CurrencyViewHolder(layoutview,context);
return rcv;
}
#Override
public void onBindViewHolder(CurrencyViewHolder holder, int position) {
final BureauRateObject br = itemList.get(position);
holder.bureauname.setText(br.getBureau_name());
holder.rates.setText(br.getBuysell());
final String BureauId = br.getBureau_id();
final String BureauName = br.getBureau_name();
holder.root.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(context, SingleForexActivity.class);
// i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("bureau_id", BureauId);
i.putExtra("bureau_name",BureauName);
context.startActivity(i);
}
});
}
#Override
public int getItemCount() {
return itemList.size();
}
}
The Context that you pass into the CurrencySelectorAdapter constructor should be the Activity that hosts this RecyclerView. Then, you will not get this error.
Replacing getApplicationContext() with this helped in my case.
for example I had:
adapter= new CustomAdapter(dataModels,getApplicationContext());
in my activity file before changing it to:
adapter= new CustomAdapter(dataModels,this);
and that fixed the error.
Another reason on getting such issue like this is when using rootView context
Example
val view = window.decorView.rootView
view.context.startActivity(intent)
To those who are doing like this for some reason like using the view and its context for a singleton class. You should instead using your parent view from xml than relying on rootview to avoid such behavior.

Unable to pass intent in custom array adapter

I am unable to pass an intent in this case. Nothing is displayed on the screen or Logs from the movie_detail.java. I cannot figure out hat is wrong, please help!
MainActivityFragment.java
package com.example.coderahul.a9to12;
import android.content.Context;
import android.content.Intent;
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.AdapterView;
import android.widget.GridView;
import java.util.Arrays;
public class MainActivityFragment extends Fragment {
private movieListAdapter movieListA;
MovieList[] movieLists = {
new MovieList("Cupcake - 1.5", "/is6QqgiPQlI3Wmk0bovqUFKM56B.jpg", "368596"),
new MovieList("Donut - 1.6", "/cGOPbv9wA5gEejkUN892JrveARt.jpg", "209112"),
new MovieList("Eclair - 2.0-2.1", "/9KQX22BeFzuNM66pBA6JbiaJ7Mi.jpg", "47933"),
new MovieList("Froyo - 2.2-2.2.3", "/z09QAf8WbZncbitewNk6lKYMZsh.jpg", "127380"),
new MovieList("GingerBread - 2.3-2.3.7", "/5N20rQURev5CNDcMjHVUZhpoCNC.jpg", "271110"),
new MovieList("Honeycomb - 3.0-3.2.6", "/jjBgi2r5cRt36xF6iNUEhzscEcb.jpg", "135397"),
new MovieList("Ice Cream Sandwich - 4.0-4.0.4", "/6FxOPJ9Ysilpq0IgkrMJ7PubFhq.jpg", "258489"),
new MovieList("Jelly Bean - 4.1-4.3.1", "/tSFBh9Ayn5uiwbUK9HvD2lrRgaQ.jpg", "262504"),
new MovieList("Honeycomb - 3.0-3.2.6", "/inVq3FRqcYIRl2la8iZikYYxFNR.jpg", "87101"),
new MovieList("Ice Cream Sandwich - 4.0-4.0.4", "/zSouWWrySXshPCT4t3UKCQGayyo.jpg", "293660"),
new MovieList("Jelly Bean - 4.1-4.3.1", "/MZFPacfKzgisnPoJIPEFZUXBBT.jpg", "76341"),
new MovieList("Jelly Bean - 4.1-4.3.1", "/sM33SANp9z6rXW8Itn7NnG1GOEs.jpg", "246655")
};
public MainActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
movieListA = new movieListAdapter(getActivity(), Arrays.asList(movieLists));
// Get a reference to the ListView, and attach this adapter to it.
GridView gridView = (GridView) rootView.findViewById(R.id.movies_grid);
gridView.setAdapter(movieListA);
final Context context = getActivity();
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
MovieList detail = (MovieList) movieListA.getItem(position);
Intent intent = new Intent(context, movie_detail.class)
.putExtra(Intent.EXTRA_TEXT, detail.title);
context.startActivity(intent);
Log.v("Check", detail.title);
}
});
return rootView;
}
}
movie_detail.java
package com.example.coderahul.a9to12;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class movie_detail extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.movie_detail);
}
public static class DetailFragment extends Fragment {
public DetailFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.movie_detail, container, false);
Log.v("Check", "Inside Intent");
// The detail Activity called via intent. Inspect the intent for forecast data.
Intent intent = getActivity().getIntent();
if (intent != null && intent.hasExtra(Intent.EXTRA_TEXT)) {
String detail = intent.getStringExtra(Intent.EXTRA_TEXT);
Log.v("Check", detail);
((TextView) rootView.findViewById(R.id.movie_detail))
.setText(detail);
}
return rootView;
}
}
}
movieListAdapter.java
package com.example.coderahul.a9to12;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.List;
public class movieListAdapter extends ArrayAdapter<MovieList> {
private static final String LOG_TAG = movieListAdapter.class.getSimpleName();
/**
* This is our own custom constructor (it doesn't mirror a superclass constructor).
* The context is used to inflate the layout file, and the List is the data we want
* to populate into the lists
*
* #param context The current context. Used to inflate the layout file.
A List of AndroidFlavor objects to display in a list
*/
public movieListAdapter(Activity context, List<MovieList> movieList) {
// Here, we initialize the ArrayAdapter's internal storage for the context and the list.
// the second argument is used when the ArrayAdapter is populating a single TextView.
// Because this is a custom adapter for two TextViews and an ImageView, the adapter is not
// going to use this second argument, so it can be any value. Here, we used 0.
super(context, 0, movieList);
}
/**
* Provides a view for an AdapterView (ListView, GridView, etc.)
*
* #param position The AdapterView position that is requesting a view
* #param convertView The recycled view to populate.
* (search online for "android view recycling" to learn more)
* #param parent The parent ViewGroup that is used for inflation.
* #return The View for the position in the AdapterView.
*/
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Gets the AndroidFlavor object from the ArrayAdapter at the appropriate position
MovieList movieList = getItem(position);
// Adapters recycle views to AdapterViews.
// If this is a new View object we're getting, then inflate the layout.
// If not, this view already has the layout inflated from a previous call to getView,
// and we modify the View widgets as usual.
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(
R.layout.movie_item, parent, false);
}
ImageView iconView = (ImageView) convertView.findViewById(R.id.movie_image);
Picasso.with(getContext())
.load("http://image.tmdb.org/t/p/w185//" + movieList.link)
.resize(200, 200)
.centerCrop()
.into(iconView);
TextView versionNameView = (TextView) convertView.findViewById(R.id.movie_title);
versionNameView.setText(movieList.title);
return convertView;
}
}
You will be able to get your Intent in Activity's onCreate() method not in your fragment onCreateView() method because intent will be recevied by activity and not by fragment.
To get your intent in your movie_detail activity do it like this
static String detail="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.movie_detail);
Intent intent =getIntent();
if (intent != null && intent.hasExtra(Intent.EXTRA_TEXT)) {
detail = intent.getStringExtra(Intent.EXTRA_TEXT);
}
}
After doing this you can use detail String to set Text in your textview
In your fragment class
((TextView) rootView.findViewById(R.id.movie_detail))
.setText(movie_detail.detail);
You must attach the fragment to your activity's layout in order to make you fragment visible in your activity
in your movie_detail activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.movie_detail);
Intent intent = getActivity().getIntent();
if (intent != null && intent.hasExtra(Intent.EXTRA_TEXT)) {
String detail = intent.getStringExtra(Intent.EXTRA_TEXT);
Log.v("Check", detail);
}
Bundle extra = new Bundle();
extra.putExtra(Intent.EXTRA_TEXT,detail);
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction =
fragmentManager.beginTransaction();
DetailFragment fragment = new DetailFragment();
fragment.setArguments(extra);
fragmentTransaction.replace(android.R.id.content, fragment);
}
And in your fragment get the arguments and set the details wherever necessary

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

How do I start a new Activity from non Activity class

I know this question already exist in this forum, but every solution I founded not worked. I want to start an Activity from a non-Activity class. The non-Activity class is the DetailFragment.java of a Navigation-Drawer
DetaiFragment:
package com.developing.konstantin.besmart;
import android.annotation.TargetApi;
import android.app.Fragment;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class DetailFragment extends Fragment {
FrameLayout fLayout;
View view;
public DetailFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle args) {
view = inflater.inflate(R.layout.menu_detail_fragment, container, false);
String menu = getArguments().getString("Menu");
switch (menu) {
case ("Home"): {
fLayout = (FrameLayout) view.findViewById(R.id.home) ;
fLayout.setVisibility(View.VISIBLE);
break;
}
case ("Info"): {
fLayout = (FrameLayout) view.findViewById(R.id.info) ;
fLayout.setVisibility(View.VISIBLE);
break;
}
case ("Video"): {
break;
}
}
return view;
}
}
I want to start the Activity in the 3rd case ("Video"). How can I do that?
You can use the context :
inflater.getContext()
as:
startActivity(new Intent(inflater.getContext(), Video.class));
or you can use the getActivity() method like:
startActivity(new Intent(getActivity(), Video.class));
It depends on from where you are calling the activity.
It is better to create an instance of
Context context;
and initialize it like
context = AnyActivity.this; // if you are calling from Activity
context = getActivity(); // if you are using Fragments
And call it like
Intent intent = new Intent(context,ActivityToOpen.class);
startActivity(intent);

Categories