Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call startactivity or call intent from onitemclick event of listview in fragment?

Tags:

android

I have a fragment that has its own layout. In the layout, there is a listview and i attached onitemclick listener that will start/open an intent when the list row is clicked. Unfortunately, I always get this error :

Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag

But I do not prefer to set the flag activity. I could not open the SamplePage.class

public class FrontPageFragment extends Fragment
{

    private ArrayList<Order> m_orders = null;
    private OrderAdapter m_adapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View fragmentView=inflater.inflate(R.layout.frontpage, container, false);

        m_orders = new ArrayList<Order>();
        this.m_adapter = new OrderAdapter(this.getActivity().getApplicationContext(), R.layout.name, m_orders);

        View eView=(View)fragmentView.findViewById(R.id.approvedOrders);
        ListView listView=(ListView)eView.findViewById(R.id.listview);

         listView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {

                Intent intent = new Intent(view.getContext(), SamplePage.class);
                intent.putExtra("id", "1");
                view.getContext().startActivity(intent);

            }
         });

        //bind data
        listView.setAdapter(this.m_adapter);


        return fragmentView;

    }
like image 382
qme Avatar asked Aug 24 '11 14:08

qme


2 Answers

When I copied ur code I got the same error. So I changed it a little bit, and it worked. Check this:

Intent intent = new Intent(getActivity().getBaseContext(), Sampleclass.class);

intent.putExtra("id", 1);

startActivity(intent);
like image 80
MGDroid Avatar answered Nov 05 '22 16:11

MGDroid


Try this:

FrontPageFragment.this.startActivity(intent);
like image 39
Peter Knego Avatar answered Nov 05 '22 15:11

Peter Knego