0

I am trying to open new activity from a fragment,but it is give error of closing app when using this code. Pls help in what code is added into onclick methode for call the another activity.i am getting problem in following code.

package info.androidhive.summit;


import android.app.Fragment;
import android.content.Intent;
 import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
 import android.widget.Toast;

 public class CommunityFragment extends Fragment implements OnClickListener {

   public CommunityFragment(){}
  Button btn;
  @Override
     public View onCreateView(LayoutInflater inflater, ViewGroup container,
         Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_community, container, false);

    btn = (Button) rootView.findViewById(R.id.button1);
    btn.setOnClickListener(this); 

    return rootView;
    }

   @Override
    public void onClick(View v) {
     // TODO Auto-generated method stub


     Intent intent = new Intent(getActivity(),trail.class);
       getActivity().startActivity(intent);


       Toast.makeText(this.getActivity(), 
         "Button is clicked!", Toast.LENGTH_LONG).show(); 

   }
 }

3 Answers3

0
Intent intent = new Intent(getActivity(), trail.class);
startActivity(intent);
Miki Franko
  • 687
  • 3
  • 7
0

You were using the Button inside onCreateView, but you can't use the View before it is attached. Add the code show below & don't forget to remove the Button you created inside onCreateView

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    btn = (Button) rootView.findViewById(R.id.button1);
    btn.setOnClickListener(this); 
}

P.S : Let me if it works or not

Akshay Chordiya
  • 4,761
  • 3
  • 40
  • 52
0

The activity you're trying to start isn't declared in your manifest. Add this to your manifest:

<activity android:name=".trail" />
max59
  • 606
  • 1
  • 7
  • 16