Aswathy K R
Aswathy K R

Reputation: 177

How to capture an image in xamarin android using the camera in fragment

I am a beginner in xamarin android.I want to take photo using my device camera,I am using the following code to to capture the image but, I got an exception when running the code

Here is my Fragment.CS

  public class ScanFragments : Fragment
{
    ImageView imageView;

    public override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
    }

    public static ScanFragments NewInstance()
    {
        var scan = new ScanFragments { Arguments = new Bundle() };
        return scan;
    }


    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        var ignored = base.OnCreateView(inflater, container, savedInstanceState);

        imageView =View.FindViewById<ImageView>(Resource.Id.Iv_ScanImg);
        var btnCamera =View. FindViewById<Button>(Resource.Id.btnCamera);

        btnCamera.Click += BtnCamera_Click;


        return inflater.Inflate(Resource.Layout.ScanLayout, null);
    }

    private void BtnCamera_Click(object sender, EventArgs e)
    {
        Intent intent = new Intent(MediaStore.ActionImageCapture);
        StartActivityForResult(intent, 0);
    }
}

Upvotes: 0

Views: 851

Answers (1)

FreakyAli
FreakyAli

Reputation: 16587

Well now I see your mistake its actually very simple you get the null reference because of the following reasons

1.OnCreateView does not contain a definition of View basically what I mean here is View is a class which you are using as an object of that class.

2.The actual way I recommend using fragments is first you define it an XML or an AXML as its foreground view in on OnCreateView as follows :

 return inflater.Inflate(Resource.Layout.ScanLayout, null);

3.Override the OnViewCreated method and use its View to do all your work as follows :

 public override void OnViewCreated(View view, Bundle savedInstanceState)
{
    base.OnViewCreated(view, savedInstanceState);
    imageView =view.FindViewById<ImageView>(Resource.Id.Iv_ScanImg);
    var btnCamera =view. FindViewById<Button>(Resource.Id.btnCamera);

    btnCamera.Click += BtnCamera_Click;

}

4.For details related to the Android Activity and Fragment lifecycle check here

Goodluck!

Upvotes: 1

Related Questions