AlertDialog不会显示我的edittext

时间:2017-08-27 06:33:30

标签: android firebase android-edittext alertdialog

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    public static final String ANONYMOUS = "anonymous";
    public static final int RC_SIGN_IN = 1;
    private static final int RC_PHOTO_PICKER = 2;
    private String mUsername;

    // Firebase instance variables
    private FirebaseDatabase mFirebaseDatabase;
    private DatabaseReference mMessagesDatabaseReference;
    private ChildEventListener mChildEventListener;
    private FirebaseAuth mFirebaseAuth;
    private FirebaseAuth.AuthStateListener mAuthStateListener;
    private FirebaseStorage mFirebaseStorage;
    private StorageReference mChatPhotosStorageReference;
    private FirebaseRemoteConfig mFirebaseRemoteConfig;

    private SeekBar seekBar;

    private RecyclerView recyclerView;
    private FloatingActionButton floatingActionButton;
    NotificationCompat.Builder notificationBuilder;
    VideoAdapter videoAdapter;
    List<Video> videoList;


    NotificationManager notificationManager;
    AlertDialog.Builder alertDialog;
    EditText input;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mUsername = ANONYMOUS;
        recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
        floatingActionButton = (FloatingActionButton) findViewById(R.id.floatingactionbutton);
        videoList = new ArrayList();
        // Initialize Firebase components
        mFirebaseDatabase = FirebaseDatabase.getInstance();
        mFirebaseAuth = FirebaseAuth.getInstance();
        mFirebaseStorage = FirebaseStorage.getInstance();
        mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
        seekBar = (SeekBar) findViewById(R.id.seekbar);

        mMessagesDatabaseReference = mFirebaseDatabase.getReference().child("videomessages");
        mChatPhotosStorageReference = mFirebaseStorage.getReference().child("videos");

        mAuthStateListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser user = firebaseAuth.getCurrentUser();
                if (user != null) {
                    // User is signed in
                    onSignedInInitialize(user.getDisplayName());
                } else {
                    // User is signed out
                    onSignedOutCleanup();
                    startActivityForResult(
                            AuthUI.getInstance()
                                    .createSignInIntentBuilder()
                                    .setIsSmartLockEnabled(false)
                                    .setProviders(
                                            AuthUI.EMAIL_PROVIDER,
                                            AuthUI.GOOGLE_PROVIDER)
                                    .build(),
                            RC_SIGN_IN);
                }
            }
        };




        floatingActionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("video/*");
                intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
                startActivityForResult(Intent.createChooser(intent, "Complete action using"), RC_PHOTO_PICKER);
                alertDialog = new AlertDialog.Builder(MainActivity.this);
                alertDialog.setTitle("Upload");
                alertDialog.setMessage("Enter Name");

                input = new EditText(MainActivity.this);
                LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.MATCH_PARENT,
                        LinearLayout.LayoutParams.MATCH_PARENT);
                input.setLayoutParams(lp);
                alertDialog.show();

            }
        });


        attachDatabaseReadListener();



    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RC_SIGN_IN) {
            if (resultCode == RESULT_OK) {
                // Sign-in succeeded, set up the UI
                Toast.makeText(this, "Signed in!", Toast.LENGTH_SHORT).show();
            } else if (resultCode == RESULT_CANCELED) {
                // Sign in was canceled by the user, finish the activity
                Toast.makeText(this, "Sign in canceled", Toast.LENGTH_SHORT).show();
                finish();
            }
        } else if (requestCode == RC_PHOTO_PICKER && resultCode == RESULT_OK) {
            Uri selectedImageUri = data.getData();


            new MyAsyncTask().execute(selectedImageUri);
            // Get a reference to store file at chat_photos/<FILENAME>

        }
        ;
    }

    @Override
    protected void onResume() {
        super.onResume();
        mFirebaseAuth.addAuthStateListener(mAuthStateListener);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mAuthStateListener != null) {
            mFirebaseAuth.removeAuthStateListener(mAuthStateListener);
        }
    }

    private void onSignedInInitialize(String username) {
        mUsername = username;
        attachDatabaseReadListener();
    }

    private void onSignedOutCleanup() {
        mUsername = ANONYMOUS;

    }

    private void attachDatabaseReadListener() {

        mMessagesDatabaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot snapshot) {
                videoList.clear();
                for (DataSnapshot postSnapshot : snapshot.getChildren()) {

                    Video postSnapshotValue = postSnapshot.getValue(Video.class);
                    if (!videoList.contains(postSnapshotValue)) {
                        videoList.add(postSnapshotValue);
                        Log.i(TAG, "onDataChange: " + videoList);
                    }

                }

                videoAdapter = new VideoAdapter(videoList, MainActivity.this);
                recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));

                recyclerView.setAdapter(videoAdapter);

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {


            }
        });
    }


    public class MyAsyncTask extends AsyncTask<Uri, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }

        @Override
        protected Void doInBackground(final Uri... params) {
            final StorageReference photoRef = mChatPhotosStorageReference.child(params[0].getLastPathSegment());
            alertDialog.setView(input);

            alertDialog.setPositiveButton("YES",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            photoRef.putFile(params[0])
                                    .addOnSuccessListener(MainActivity.this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
                                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                                            // When the image has successfully uploaded, we get its download URL
                                            //  progressBar.setVisibility(View.VISIBLE);
                                           // Uri downloadUrl = taskSnapshot.getDownloadUrl();
                                            //String nameUrl=taskSnapshot.getMetadata().getName();
                                            String TempImageName = input.getText().toString().trim();
                                            Video video = new Video(TempImageName);
                                            mMessagesDatabaseReference.push().setValue(video);

                                        }
                                    }).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                                @Override
                                public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                                    int  progress = (int) ((100 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount());

                                    seekBar.setProgress(progress);

                                    notificationBuilder = new NotificationCompat.Builder(getApplicationContext())
                                            .setColor(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimary))
                                            .setSmallIcon(R.mipmap.ic_launcher)
                                            .setContentText("Download in progress")
                                            .setContentIntent(contentIntent(getApplicationContext()))
                                            .setAutoCancel(true);

                                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                                        notificationBuilder.setPriority(Notification.PRIORITY_HIGH);
                                    }

                                    notificationManager = (NotificationManager)
                                            getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);

                                    for (int incr = progress; incr <= 100; incr += 5) {


                                        notificationBuilder.setProgress(100, progress, false);

                                        notificationManager.notify(20, notificationBuilder.build());

                                    }
                                    if(progress>=100){
                                        notificationBuilder.setContentText("Download complete").setProgress(0, 0, false);
                                        notificationManager.notify(20, notificationBuilder.build());

                                    }



                                }
                            });
                        }});

            alertDialog.setNegativeButton("NO",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    });


           return null;
        }

        @Override
        protected void onPostExecute(Void integer) {
            super.onPostExecute(integer);

            // Do the "lengthy" operation 20 times

        }


    }

    private PendingIntent contentIntent(Context context) {

        Intent startActivityIntent = new Intent(context, MainActivity.class);
        return PendingIntent.getActivity(
                context,
                0,
                startActivityIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
    }

}

我有一个浮动操作按钮。点击它,我显示用户手机中的所有视频文件。当选择一个特定文件时,它会上传到firebase存储。但我想要显示一个带有EdiText的警报对话框,其中包含用户选择的文件名。然后用户可以编辑文件的名称,单击是按钮,文件上传应该开始。我正在显示我的alertdialog处于浮动状态操作按钮。我无法在AsyncTask中显示警告对话框,因为它会出错。 所以我想要的是,当用户在点击浮动操作按钮时选择文件时显示AlertDialogEditText的{​​{1}}应该具有用户选择的文件的名称,用户可以编辑如果他/她想要,只需点击“是”按钮,该文件就应该上传到AlertDialog存储。

1 个答案:

答案 0 :(得分:0)

您在show中呼叫alertdialog到onCreate,之前您打开文件选择活动。 将{1}}中的警报对话框创建移动到您将获取文件数据的位置。

然后在ok按钮onActivityResult中,调用异步任务执行