Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/229.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 单击浮动操作按钮时,应用程序正在崩溃_Android_Fragment - Fatal编程技术网

Android 单击浮动操作按钮时,应用程序正在崩溃

Android 单击浮动操作按钮时,应用程序正在崩溃,android,fragment,Android,Fragment,我使用浮动操作按钮从一个活动导航到另一个活动,但当我单击时,应用程序崩溃了,浮动操作按钮没有问题,问题是在另一个活动中导航了它。它被导航到uploadPost类 public class uploadPost extends Fragment implements SelectPhotoDialog.OnPhotoSelectedListener { private static final String TAG = "uploadPost"; @Override

我使用浮动操作按钮从一个活动导航到另一个活动,但当我单击时,应用程序崩溃了,浮动操作按钮没有问题,问题是在另一个活动中导航了它。它被导航到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("");
    }
}
我无法理解我在日志中看到的错误

 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>

您将收到以下错误:

无法强制转换为android.app.Activity

因为您试图将
uploadPost
作为
活动加载,但它扩展了
片段
,因此您会出现“无法转换到android.app.Activity”错误

您必须决定是将其作为
片段
还是作为
活动
加载。如果要将
uploadPost
作为
活动加载
,则需要扩展到
活动
而不是
片段

编辑

如果希望继续将其用作
片段
,则必须使用
片段事务
在活动布局中添加
片段
替换
片段

您可以替换
片段
,如下示例所示:

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();
}
其中,
R.id.content\u main
只是my main活动中的一个
RelativeLayout
,由
uploadPost
片段替换

正如0X0nosugar所指出的:将类名大写是java命名约定。请采用这种约定——否则您将使代码更难理解

编辑2

通常使用
片段
交换容器
活动
中的视图。例如,我使用它们与
抽屉布局组合交换视图。在本例中,我将继续替换片段,但永远不会显式删除片段

例如,我将有一个与您的“SearchActivity”文件非常相似的xml布局文件。在
标记的正下方,我将引入一个id为
android:id=“@+id/content\u main”
RelativeLayout
。此
RelativeLayout
只是一个虚拟容器视图,正在替换为我选择的
片段中的任何内容。因此,您需要更改
onClick
code来替换上面显示的片段


通过另一个操作,您可能希望删除该片段或用另一个片段替换它。。。这一切都取决于你的应用程序设计——我不知道。

请显示当点击按钮时你是如何启动其他活动的。你想查看代码吗?是的,没错。logcat显示你有一个ClassCastException,你正在尝试操作
uploadPost
,就好像它是一个
活动一样。这不是一个
活动
,因此在对其执行操作时会崩溃。我已更新了我的问题,请看一看,我必须将其作为一个片段加载,为此我必须这样做do@VishalSharma当前位置我已经编辑了答案。如果您需要更多信息来实现此功能,请编辑您的问题并提供
SearchActivity
的xml布局——如果您希望在此处显示
片段
我已附上我的SearchActivity的xml布局,请look@VishalSharma::我希望我在“编辑2”中提供的信息对您有所帮助。如果没有关于应用程序的深入信息,就很难获得更多指导
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();
}