单击几次图像后我的应用程序崩溃-为什么?

时间:2018-11-24 14:17:21

标签: java android android-fragments

我正在制作一个应用程序,该应用程序调用内置摄像头来单击图像并将其上传到Firebase Firestore。但是单击2张或更多张照片后,该应用程序崩溃了。我正在使用一个名为MainActivity.java的导航抽屉,并且有一个片段提供一些按钮。在片段中有一个列表视图。

MainActivity.java

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener,OnFragmentInteractionListener{

    private StorageReference mStorageRef;
    AlertDialog.Builder builder;
    LayoutInflater inflater;
    View vv;

    private AlertDialog dialog;
    FirebaseFirestore db = FirebaseFirestore.getInstance();
    @Override
    public void onFragmentInteraction(Uri uri){

    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //uploadImage.doInBackground("ABCD");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        builder = new AlertDialog.Builder(MainActivity.this);
        builder.setCancelable(false);
        inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        vv = inflater.inflate(R.layout.layout_logging_in_dialog,null);
        builder.setView(vv);
        dialog = builder.create();
        mStorageRef = FirebaseStorage.getInstance().getReference();
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        //FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        Fragment fragment = new TakeAttendance();
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.content,fragment).commit();
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        Fragment fragment = null;
        Class fragmentClass;


        int id = item.getItemId();

        if (id == R.id.take_attendance) {
            fragment = new TakeAttendance();
        } else if (id == R.id.nav_gallery) {

        } else if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.account_settings) {
            fragment = new AccountSettings();
        } else if (id == R.id.logout) {
            fragment = new TakeAttendance();
            FirebaseAuth mAuth = FirebaseAuth.getInstance();
            mAuth.signOut();
            Intent intent = new Intent(MainActivity.this,LoginActivity.class);
            startActivity(intent);
            finish();
        }

        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.content,fragment).commit();


        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data){
        super.onActivityResult(requestCode,resultCode,data);
        Log.d("myMSG","cammmeeee22");
        if(requestCode == 100 && resultCode == RESULT_OK){
            Bundle extras = data.getExtras();
            Bitmap imageBitmap = (Bitmap) extras.get("data");
            StorageReference ref = mStorageRef.child("taken_images/"+Globals.course_id+".jpg");
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
            int qualityFactor=100;

            byte[] uploadData = bytes.toByteArray();

            uploadData = bytes.toByteArray();

            String imageString = Base64.encodeToString(uploadData,Base64.DEFAULT);
            Toast.makeText(MainActivity.this,"ASDF",Toast.LENGTH_SHORT).show();

        }

    }
}

TakeAttendance.java

public class TakeAttendance extends Fragment {
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    private String mParam1;
    private String mParam2;
    private    ArrayList<Course> arr = new ArrayList<>();
    private StorageReference mStorageRef;
    AlertDialog.Builder builder;
    LayoutInflater inflater;
    View vv;

    private AlertDialog dialog;

    private OnFragmentInteractionListener mListener;
    private ListView listView;
    private View inflatedView;
    FirebaseFirestore db;
    public TakeAttendance() {
        // Required empty public constructor
    }


    public static TakeAttendance newInstance(String param1, String param2) {
        TakeAttendance fragment = new TakeAttendance();
        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);
        }
    }
    private   ArrayList<String> courseIds = new ArrayList<>();
    private TakeAttendanceCustomAdapter adap;

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

        inflatedView = inflater.inflate(R.layout.fragment_take_attendance, container, false);
        builder = new AlertDialog.Builder(getContext());
        builder.setCancelable(false);
        inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        vv = inflater.inflate(R.layout.layout_logging_in_dialog,null);
        builder.setView(vv);
        dialog = builder.create();

        listView = (ListView)inflatedView.findViewById(R.id.listView);
        db = FirebaseFirestore.getInstance();
        dialog.show();
        Log.d("myMSG",getActivity().getIntent().getStringExtra("uid"));
        db.collection("teacher_course").document(getActivity().getIntent().getStringExtra(Constants.uid_parameter)).get().addOnSuccessListener(
                new OnSuccessListener<DocumentSnapshot>() {
                    @Override
                    public void onSuccess(DocumentSnapshot documentSnapshot) {
                        Log.d("myMSG","Success");
                        Map<String,Object> map = documentSnapshot.getData();
                        Log.d("myMSG",new Integer(map.size()).toString());
                        Iterator it = map.entrySet().iterator();
                        while(it.hasNext()){
                            Log.d("myMSG","entered");
                            Map.Entry pair = (Map.Entry)it.next();
                            Log.d("myMSG",pair.getKey().toString());
                            final String courseId = pair.getKey().toString();
                            db.collection("courses").document(courseId).get().addOnSuccessListener(
                                    new OnSuccessListener<DocumentSnapshot>() {
                                        @Override
                                        public void onSuccess(DocumentSnapshot documentSnapshot) {
                                            Map <String, Object> map = documentSnapshot.getData();
                                            arr.add(new Course(map.get(Constants.course_name).toString(),map.get(Constants.course_number).toString(),courseId));
                                            adap = new TakeAttendanceCustomAdapter(arr,getContext(),getActivity());

                                            listView.setAdapter(adap);

                                        }
                                    }
                            );
                            it.remove();
                        }

                        dialog.hide();
                        Log.d("myMSG",new Integer(arr.size()).toString());




                    }
                }
        );







        return inflatedView;
    }

    // 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 {
            throw new RuntimeException(context.toString()
                    + " must implement com.example.redwanulsourav.attendance.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.
        */

}

TakeAttendanceCustomAdapter.java

    public class TakeAttendanceCustomAdapter extends ArrayAdapter<Course>{
        private ArrayList<Course> dataSet;
        Context mContext;
        Activity mActivity;

        public TakeAttendanceCustomAdapter(ArrayList < Course> data, Context context, Activity activity){
            super(context,0,data);
            this.dataSet = data;
            this.mContext=context;
            mActivity = activity;
        }


        @NonNull
        @Override
        public View getView(int position, View convertView, ViewGroup parent){
            View listItem = convertView;
            if(listItem == null){
                listItem = LayoutInflater.from(mContext).inflate(R.layout.take_picture_list_single_element,parent,false);

            }

            final Course currentCourse = dataSet.get(position);

            TextView tv = (TextView)listItem.findViewById(R.id.course_name);
            tv.setText(currentCourse.getCourse_name());

            tv = (TextView)listItem.findViewById(R.id.course_number);
            tv.setText(currentCourse.getCourse_number());

            Button btn = (Button)listItem.findViewById(R.id.take_picture_button);
            Button btn2 = (Button)listItem.findViewById(R.id.browse);
            btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {

                        ActivityCompat.requestPermissions(mActivity, new String[] { Manifest.permission.CAMERA }, 0);
                    }
                    else{
                        Log.d("Message","Already has permissions");
                    }
                    Globals.course_id = currentCourse.getCourse_id();
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    mActivity.startActivityForResult(intent, 100);
                }
            });

            btn2.setOnClickListener(
                    new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                            intent.setType("*/*");
                            mActivity.startActivityForResult(intent,200);
                        }
                    }
            );
            return listItem;

        }
    }

**Course.java**

package com.example.redwanulsourav.attendance;

public class Course {
    public String getCourse_number() {
        return course_number;
    }

    public void setCourse_number(String course_number) {
        this.course_number = course_number;
    }

    public String getCourse_name() {
        return course_name;
    }

    public void setCourse_name(String course_name) {
        this.course_name = course_name;
    }

    private String course_number;
    private String course_name;

    public String getCourse_id() {
        return course_id;
    }

    public void setCourse_id(String course_id) {
        this.course_id = course_id;
    }

    private String course_id;

    public Course(String _course_name, String _course_number, String _course_id){
        this.course_name = _course_name;
        this.course_number = _course_number;
        this.course_id=_course_id;
    }

    public Course(){


    }


}

Logcat引发以下异常

Logcat

2018-11-24 21:02:16.833 1115-2308/? E/Watchdog: Failed to write to /sys/kernel/hungtask/vm_heart
    java.io.FileNotFoundException: /sys/kernel/hungtask/vm_heart (Permission denied)
        at java.io.FileOutputStream.open0(Native Method)
        at java.io.FileOutputStream.open(FileOutputStream.java:287)
        at java.io.FileOutputStream.<init>(FileOutputStream.java:223)
        at java.io.FileOutputStream.<init>(FileOutputStream.java:110)
        at com.android.server.Watchdog.writeHungtask(Watchdog.java:790)
        at com.android.server.Watchdog.run(Watchdog.java:542)

正在从TakeAttendance.java中调用摄影机意图

1 个答案:

答案 0 :(得分:1)

解决您的问题 在清单中的应用程序标记下添加此行。

android:largeHeap="true"