单击浮动操作按钮时应用程序崩溃

时间:2018-05-14 18:08:40

标签: android fragment

我正在使用浮动操作按钮从一个活动导航到另一个活动但是当我点击然后应用程序崩溃时,浮动操作按钮没有问题,问题出现在导航的另一个活动中。它被导航到uploadPost类。

   public class uploadPost extends Fragment implements SelectPhotoDialog.OnPhotoSelectedListener {

    private static final String TAG = "uploadPost";

    @Override
    public void getImagePath(Uri imagePath) {
        Log.d(TAG, "getImagePath: setting the image to imageview");
        UniversalImageLoader.setImage(imagePath.toString(), mPostImage);
        //assign to global variable
        mSelectedBitmap = null;
        mSelectedUri = imagePath;
    }

    @Override
    public void getImageBitmap(Bitmap bitmap) {
        Log.d(TAG, "getImageBitmap: setting the image to imageview");
        mPostImage.setImageBitmap(bitmap);
        //assign to a global variable
        mSelectedUri = null;
        mSelectedBitmap = bitmap;
    }

    //widgets
    private ImageView mPostImage;
    private EditText mTitle, mDescription, mPrice, mCountry, mStateProvince, mCity, mContactEmail,mCollege;
    private Button mPost;
    private ProgressBar mProgressBar;

    //vars
    private Bitmap mSelectedBitmap;
    private Uri mSelectedUri;
    private byte[] mUploadBytes;
    private double mProgress = 0;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_upload_post, container, false);
        mPostImage = view.findViewById(R.id.post_image);
        mTitle = view.findViewById(R.id.input_title);
        mDescription = view.findViewById(R.id.input_description);
        mPrice = view.findViewById(R.id.input_price);
        mCountry = view.findViewById(R.id.input_country);
        mStateProvince = view.findViewById(R.id.input_state_province);
        mCity = view.findViewById(R.id.input_city);
        mContactEmail = view.findViewById(R.id.input_email);
        mCollege = view.findViewById(R.id.input_clg);
        mPost = view.findViewById(R.id.btn_post);
        mProgressBar = (ProgressBar) view.findViewById(R.id.progressBar);

        mCountry.setText("India");
        mStateProvince.setText("Maharashtra");
        mCity.setText("Pune");

        getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);

        init();

        return view;
    }

    private void init(){

        mPostImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "onClick: opening dialog to choose new photo");
                SelectPhotoDialog dialog = new SelectPhotoDialog();
                dialog.show(getFragmentManager(), getString(R.string.dialog_select_photo));
                dialog.setTargetFragment(uploadPost.this, 1);
            }
        });

        mPost.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "onClick: attempting to post...");
                if(!isEmpty(mTitle.getText().toString())
                        && !isEmpty(mDescription.getText().toString())
                        && !isEmpty(mPrice.getText().toString())
                        && !isEmpty(mCountry.getText().toString())
                        && !isEmpty(mStateProvince.getText().toString())
                        && !isEmpty(mCity.getText().toString())
                        && !isEmpty(mContactEmail.getText().toString())){

                    //we have a bitmap and no Uri
                    if(mSelectedBitmap != null && mSelectedUri == null){
                        uploadNewPhoto(mSelectedBitmap);
                    }
                    //we have no bitmap and a uri
                    else if(mSelectedBitmap == null && mSelectedUri != null){
                        uploadNewPhoto(mSelectedUri);
                    }
                }else{
                    Toast.makeText(getActivity(), "You must fill out all the fields", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void uploadNewPhoto(Bitmap bitmap){
        Log.d(TAG, "uploadNewPhoto: uploading a new image bitmap to storage");
        BackgroundImageResize resize = new BackgroundImageResize(bitmap);
        Uri uri = null;
        resize.execute(uri);
    }

    private void uploadNewPhoto(Uri imagePath){
        Log.d(TAG, "uploadNewPhoto: uploading a new image uri to storage.");
        BackgroundImageResize resize = new BackgroundImageResize(null);
        resize.execute(imagePath);
    }

    public class BackgroundImageResize extends AsyncTask<Uri, Integer, byte[]>{

        Bitmap mBitmap;

        public BackgroundImageResize(Bitmap bitmap) {
            if(bitmap != null){
                this.mBitmap = bitmap;
            }
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            Toast.makeText(getActivity(), "compressing image", Toast.LENGTH_SHORT).show();
            showProgressBar();
        }

        @Override
        protected byte[] doInBackground(Uri... params) {
            Log.d(TAG, "doInBackground: started.");

            if(mBitmap == null){
                try{
                    RotateBitmap rotateBitmap = new RotateBitmap();
                    mBitmap = rotateBitmap.HandleSamplingAndRotationBitmap(getActivity(), params[0]);
                }catch (IOException e){
                    Log.e(TAG, "doInBackground: IOException: " + e.getMessage());
                }
            }
            byte[] bytes = null;
            Log.d(TAG, "doInBackground: megabytes before compression: " + mBitmap.getByteCount() / 1000000 );
            bytes = getBytesFromBitmap(mBitmap, 100);
            Log.d(TAG, "doInBackground: megabytes before compression: " + bytes.length / 1000000 );
            return bytes;
        }

        @Override
        protected void onPostExecute(byte[] bytes) {
            super.onPostExecute(bytes);
            mUploadBytes = bytes;
            hideProgressBar();
            //execute the upload task
            executeUploadTask();
        }
    }

    private void executeUploadTask(){
        Toast.makeText(getActivity(), "uploading image", Toast.LENGTH_SHORT).show();

        final String postId = FirebaseDatabase.getInstance().getReference().push().getKey();

        final StorageReference storageReference = FirebaseStorage.getInstance().getReference()
                .child("posts/users/" + FirebaseAuth.getInstance().getCurrentUser().getUid() +
                        "/" + postId + "/post_image");

        UploadTask uploadTask = storageReference.putBytes(mUploadBytes);
        uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                Toast.makeText(getActivity(), "Post Success", Toast.LENGTH_SHORT).show();

                //insert the download url into the firebase database
                Uri firebaseUri = taskSnapshot.getDownloadUrl();

                Log.d(TAG, "onSuccess: firebase download url: " + firebaseUri.toString());
                DatabaseReference reference = FirebaseDatabase.getInstance().getReference();

                Post post = new Post();
                post.setImage(firebaseUri.toString());
                post.setCity(mCity.getText().toString());
                post.setContact_email(mContactEmail.getText().toString());
                post.setCountry(mCountry.getText().toString());
                post.setDescription(mDescription.getText().toString());
                post.setPost_id(postId);
                post.setPrice(mPrice.getText().toString());
                post.setState_province(mStateProvince.getText().toString());
                post.setTitle(mTitle.getText().toString());
                post.setUser_id(FirebaseAuth.getInstance().getCurrentUser().getUid());
                post.setCollege(mCollege.getText().toString());

                reference.child(getString(R.string.node_posts))
                        .child(postId)
                        .setValue(post);

                resetFields();
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Toast.makeText(getActivity(), "could not upload photo", Toast.LENGTH_SHORT).show();
            }
        }).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                double currentProgress = (100 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
                if( currentProgress > (mProgress + 15)){
                    mProgress = (100 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
                    Log.d(TAG, "onProgress: upload is " + mProgress + "& done");
                    Toast.makeText(getActivity(), mProgress + "%", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    public static byte[] getBytesFromBitmap(Bitmap bitmap, int quality){
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, quality,stream);
        return stream.toByteArray();
    }


    private void resetFields(){
        UniversalImageLoader.setImage("", mPostImage);
        mTitle.setText("");
        mDescription.setText("");
        mPrice.setText("");
        mCountry.setText("India");
        mStateProvince.setText("Maharashtra");
        mCity.setText("Pune");
        mContactEmail.setText("");
        mCollege.setText("");
    }

    private void showProgressBar(){
        mProgressBar.setVisibility(View.VISIBLE);
    }

    private void hideProgressBar(){
        if(mProgressBar.getVisibility() == View.VISIBLE){
            mProgressBar.setVisibility(View.INVISIBLE);
        }
    }

    /**
     * Return true if the @param is null
     * @param string
     * @return
     */
    private boolean isEmpty(String string){
        return string.equals("");
    }
}

它已从SearchActivity类导航

public class SearchActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{

    private static final String TAG = "SearchActivity";
    private static final int REQUEST_CODE = 1;

    private FirebaseAuth.AuthStateListener mAuthStateListener;

    //widgets
    private TabLayout mTabLayout;
    public ViewPager mViewPager;

    //vars
    public SectionsPagerAdapter mPagerAdapter;

    //navigation drawer
    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mToggle;

    //user info
    TextView uname,uemail;
    String pemail,pname;
    ImageView pimage;
    CoordinatorLayout navigation;

    FloatingActionButton fab;

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);



        mTabLayout = (TabLayout) findViewById(R.id.tabs);
        mViewPager  = (ViewPager) findViewById(R.id.viewpager_container);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer);
        navigation = (CoordinatorLayout) findViewById(R.id.error);
        mToggle = new ActionBarDrawerToggle(this,mDrawerLayout,R.string.open,R.string.close)
        {
            /* Called when a drawer has settled in a completely close state. */
            public void onDrawerClosed(View view) {
               // fab.setVisibility(View.VISIBLE);
               //navigation.setVisibility(View.VISIBLE);
            }

            /** Called when a drawer has settled in a completely open state. */
            public void onDrawerOpened(View drawerView) {
              // fab.setVisibility(View.INVISIBLE);
                // navigation.setVisibility(View.INVISIBLE);
            }

        };
        mDrawerLayout.addDrawerListener(mToggle);
        mToggle.syncState();
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        NavigationView navigationView = (NavigationView) findViewById(R.id.navigation_view);
        navigationView.setNavigationItemSelectedListener(this);
        fab = (FloatingActionButton) findViewById(R.id.fab);

        fab.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(getApplicationContext(),R.color.red4)));

        View header = navigationView.getHeaderView(0);
        pimage = (ImageView) header.findViewById(R.id.pimage);
        uname = (TextView) header.findViewById(R.id.uname);
        uemail = (TextView) header.findViewById(R.id.emailo);

        SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(SearchActivity.this);
        pemail = sharedPref.getString("email", "Not Available");
        pname = sharedPref.getString("username", "Not Available");

        uname.setText(pname);
        uemail.setText(pemail);

        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(SearchActivity.this,uploadPost.class);
                startActivity(intent);
            }
        });

        setupFirebaseListener();
        verifyPermissions();

    }


    private void setupFirebaseListener() {
        Log.d(TAG, "setupFirebaseListener: setting up the auth state listener.");
        mAuthStateListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser user = firebaseAuth.getCurrentUser();
                if (user != null) {
                    Log.d(TAG, "onAuthStateChanged: signed_in: " + user.getUid());
                } else {
                    Log.d(TAG, "onAuthStateChanged: signed_out");
                    Toast.makeText(SearchActivity.this, "Signed out", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(SearchActivity.this, LoginActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    startActivity(intent);
                }
            }
        };
    }

    @Override
    public void onStart() {
        super.onStart();
        FirebaseAuth.getInstance().addAuthStateListener(mAuthStateListener);
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mAuthStateListener != null) {
            FirebaseAuth.getInstance().removeAuthStateListener(mAuthStateListener);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if(mToggle.onOptionsItemSelected(item)){

            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void setupViewPager(){
        mPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
        mPagerAdapter.addFragment(new SearchFragment());
        mPagerAdapter.addFragment(new WatchListFragment());
       // mPagerAdapter.addFragment(new PostFragment());

        mViewPager.setAdapter(mPagerAdapter);
        mTabLayout.setupWithViewPager(mViewPager);
        mTabLayout.getTabAt(0).setText(getString(R.string.fragment_search));
        mTabLayout.getTabAt(1).setText(getString(R.string.fragment_watch_list));
       // mTabLayout.getTabAt(2).setText(getString(R.string.fragment_post));
    }

    private void verifyPermissions(){
        Log.d(TAG, "verifyPermissions: asking user for permissions");
        String[] permissions = {Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.CAMERA};

        if(ContextCompat.checkSelfPermission(this.getApplicationContext(),
                permissions[0]) == PackageManager.PERMISSION_GRANTED
                && ContextCompat.checkSelfPermission(this.getApplicationContext(),
                permissions[1]) == PackageManager.PERMISSION_GRANTED
                && ContextCompat.checkSelfPermission(this.getApplicationContext(),
                permissions[2]) == PackageManager.PERMISSION_GRANTED){
            setupViewPager();
        }else{
            ActivityCompat.requestPermissions(SearchActivity.this,
                    permissions,
                    REQUEST_CODE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        verifyPermissions();
    }

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

        if(id == R.id.profile){

            Intent intent = new Intent(SearchActivity.this,test.class);
            startActivity(intent);
            Toast.makeText(this,"Profile",Toast.LENGTH_SHORT).show();

        }

        if(id == R.id.aboutus){

            Intent intent = new Intent(SearchActivity.this,Aboutus.class);
            startActivity(intent);

            Toast.makeText(this,"About Us",Toast.LENGTH_SHORT).show();

        }

        if(id == R.id.mypost){

            Intent intent = new Intent(SearchActivity.this,MyPosts.class);
            startActivity(intent);

            Toast.makeText(this,"My Post",Toast.LENGTH_SHORT).show();

        }

        if(id == R.id.logout){

            Log.d(TAG, "onClick: attempting to sign out the user.");
            FirebaseAuth.getInstance().signOut();

        }


        return false;

    }
}

我无法理解我在日志中看到的错误

 FATAL EXCEPTION: main
Process: codingwithmitch.com.forsale, PID: 13518
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{codingwithmitch.com.forsale/codingwithmitch.com.forsale.uploadPost}: java.lang.ClassCastException: codingwithmitch.com.forsale.uploadPost cannot be cast to android.app.Activity
   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2561)
   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724)
   at android.app.ActivityThread.-wrap12(ActivityThread.java)
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473)
   at android.os.Handler.dispatchMessage(Handler.java:102)
   at android.os.Looper.loop(Looper.java:154)
   at android.app.ActivityThread.main(ActivityThread.java:6123)
   at java.lang.reflect.Method.invoke(Native Method)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
Caused by: java.lang.ClassCastException: codingwithmitch.com.forsale.uploadPost cannot be cast to android.app.Activity
   at android.app.Instrumentation.newActivity(Instrumentation.java:1100)
   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2551)
   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724) 
   at android.app.ActivityThread.-wrap12(ActivityThread.java) 
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473) 
   at android.os.Handler.dispatchMessage(Handler.java:102) 
   at android.os.Looper.loop(Looper.java:154) 
   at android.app.ActivityThread.main(ActivityThread.java:6123) 

我的SearchActivity xml文件:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:fab="http://schemas.android.com/tools"
    android:id="@+id/drawer"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/White"
    android:fitsSystemWindows="true">

    <android.support.design.widget.CoordinatorLayout
        android:id="@+id/error"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.design.widget.AppBarLayout
            android:id="@+id/app_bar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/white"
            android:elevation="10dp"
            android:fitsSystemWindows="true">

            <android.support.design.widget.CollapsingToolbarLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:layout_scrollFlags="scroll|exitUntilCollapsed">

                <android.support.design.widget.TabLayout
                    android:id="@+id/tabs"
                    android:layout_width="match_parent"
                    android:layout_height="50dp"
                    app:layout_collapseMode="parallax">

                </android.support.design.widget.TabLayout>

            </android.support.design.widget.CollapsingToolbarLayout>

        </android.support.design.widget.AppBarLayout>


        <android.support.v4.view.ViewPager
            android:id="@+id/viewpager_container"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior">


        </android.support.v4.view.ViewPager>

        <com.getbase.floatingactionbutton.FloatingActionButton
            android:id="@+id/fab"
            android:layout_width="42dp"
            android:layout_height="53dp"
            android:layout_gravity="bottom|end"
            android:layout_margin="@dimen/fab_margin"
            android:scaleType="center"
            android:src="@drawable/ic_camera_alt_black_24dp"
            app:fabSize="normal"
            fab:layout_editor_absoluteX="342dp"
            fab:layout_editor_absoluteY="458dp">

        </com.getbase.floatingactionbutton.FloatingActionButton>
    </android.support.design.widget.CoordinatorLayout>

    <android.support.design.widget.NavigationView
        android:id="@+id/navigation_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:headerLayout="@layout/header"
        app:menu="@menu/nav_menu"></android.support.design.widget.NavigationView>


</android.support.v4.widget.DrawerLayout>

1 个答案:

答案 0 :(得分:1)

您收到错误:

  

无法转换为android.app.Activity

因为您尝试将uploadPost加载为Activity,但它会扩展Fragment,因此您无法将#34;强制转换为android.app.Activity&#34;错误。

您必须决定是将其加载为Fragment还是Activity。如果您想将uploadPost加载为Activity,则需要扩展为Activity而不是Fragment

修改

如果您希望继续将其用作Fragment,则必须FragmentTransaction使用add() Fragmentreplace() a {{1}在您的活动布局中。

您可以像这个例子一样替换Fragment

Fragment

Fragment fragment = new UploadPost(); if(fragment != null) { FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); //If you want to play around with different transaction animations //fragmentTransaction.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out); fragmentTransaction.replace(R.id.content_main, fragment, "0"); fragmentTransaction.commit(); } 只是我的MainActivity中的R.id.content_main,被RelativeLayout片段取代。

正如0X0nosugar所指出的那样:大写类名是java命名约定。请采用此惯例 - 否则您将更难理解您的代码。

编辑2

通常会使用uploadPost来交换容器Fragment中的视图。例如,我使用它们与Activity组合交换视图。在这种情况下,我将继续替换片段,但绝不会真正删除片段。

例如,我将有一个与你的&#34; SearchActivity&#34;非常类似的xml布局文件。文件。在DrawerLayout代码下方,我将介绍</android.support.design.widget.AppBarLayout>,其代码为RelativeLayout。这个android:id="@+id/content_main"只是一个虚容器视图,正在被我选中的RelativeLayout中的任何内容替换。因此,您需要更改Fragment代码以替换上面显示的片段。

使用其他操作,您可能要删除该片段或将其替换为另一个...这一切都取决于您的应用设计 - 我不知道。