Android应用程序从错误的活动开始&无法将图像上传到firebase

时间:2017-06-28 08:59:27

标签: android firebase firebase-realtime-database firebase-authentication firebase-storage

首先,对于任何误解,遗憾,因为英语不是我的母语。我试图在Android Studio中编写我的第一个应用程序。

我的应用做了什么:(至少''应该做''):

1:用户登录屏幕为MainActivity 2:如果用户信用为真,则将用户定向到第二个屏幕,即请求表单。 3:用户输入他的姓氏,主题和主题解释。

4:用户CAN也可以从图像按钮上传图片。没有必要。 5,6,7 ....:这部分将被添加到程序中。目前它只有4个步骤:D

现在我的问题, 1:当我运行应用程序时,它从请求表单(第二个活动)开始,即使我在运行之前清理项目。 2:当用户输入名称,对象和说明的一些输入并单击发送按钮时,信息存储在firebase数据库中。但是,当我为图像按钮选择图像时,它不会存储在firebase中。所有身份验证都已设置。

登录屏幕代码

 package com.example.jalea.requestingform;

import android.content.Intent;
import android.preference.EditTextPreference;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;

public class MainActivity extends AppCompatActivity {
    EditText edt_email,edt_sifre;
    Button bt_giris;
    FirebaseAuth mAuth;
    FirebaseAuth.AuthStateListener authStateListener;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        edt_email = (EditText) findViewById(R.id.et_mail);
        edt_sifre = (EditText) findViewById(R.id.et_sifre);
        bt_giris = (Button) findViewById(R.id.btn_giris);
        mAuth = FirebaseAuth.getInstance();
        authStateListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                if(firebaseAuth.getCurrentUser() !=null){
                    Intent intent = new Intent(MainActivity.this,RequestActivity.class);
                    startActivity(intent);
                    //finish();
                    Log.w("1 : ","2.activity'e geçildi");
                }
                else{
                    Log.w("1 : ", "onAuthStateChanged:çıkış yaptı");
                }
            }
        };
        bt_giris.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SignIn();
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        mAuth.addAuthStateListener(authStateListener);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if(authStateListener != null) {
            mAuth.removeAuthStateListener(authStateListener);
        }
    }
    public void SignIn(){
        String email = edt_email.getText().toString();
        String sifre = edt_sifre.getText().toString();

        if(TextUtils.isEmpty(email) || TextUtils.isEmpty(sifre)){
            Toast.makeText(MainActivity.this,"Kullanıcı adı veya şifre alanı boş",Toast.LENGTH_LONG).show();
        }
        else{
            mAuth.signInWithEmailAndPassword(email,sifre).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if(!task.isSuccessful()){
                        Toast.makeText(MainActivity.this,"Kullanıcı adı veya şifre hatası ",Toast.LENGTH_LONG).show();
                    }
                    /**if(task.isSuccessful()){
                        Intent intent = new Intent(MainActivity.this,RequestActivity.class);
                        startActivity(intent);**/


                }
            });
        }



    }
}

申请表格代码

package com.example.jalea.requestingform;

import android.content.Intent;
import android.net.Uri;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;

import java.io.File;
import java.net.URI;

public class RequestActivity extends AppCompatActivity {
    FirebaseAuth mAuth;
    FirebaseDatabase database;
    DatabaseReference databaseReference;
    FirebaseAuth.AuthStateListener authStateListener;
    Button btn_cikis,btn_gonder;
    ImageButton imgbutton;
    EditText et_isim,et_konu,et_aciklama;
    StorageReference storageReference;
    Uri uri=null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_request);
        btn_cikis = (Button) findViewById(R.id.btn_cikis);
        storageReference = FirebaseStorage.getInstance().getReference();
        et_isim= (EditText) findViewById(R.id.et_isim);
        et_konu= (EditText) findViewById(R.id.et_konu);
        et_aciklama = (EditText) findViewById(R.id.et_text);
        database = FirebaseDatabase.getInstance();
        btn_gonder = (Button) findViewById(R.id.btn_Send);
        btn_cikis.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mAuth = FirebaseAuth.getInstance();
                mAuth.signOut();
                startActivity(new Intent(RequestActivity.this,MainActivity.class));
            }
        });
        btn_gonder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String isim = et_isim.getText().toString();
                String konu = et_konu.getText().toString();
                String aciklama = et_aciklama.getText().toString();
                Uri file = Uri.fromFile(new File("path/to/images/rivers.jpg"));
                databaseReference = database.getReference("Kullanicilar").child(isim);

                if (!TextUtils.isEmpty(isim) && !TextUtils.isEmpty(konu) && !TextUtils.isEmpty(aciklama)) {
                    databaseReference.child("adSoyad").setValue(isim);
                    databaseReference.child("Konu").setValue(konu);
                    databaseReference.child("Aciklama").setValue(aciklama);
                    Toast.makeText(RequestActivity.this, "Talep gönderildi", Toast.LENGTH_LONG).show();
                    StorageReference filePath = storageReference.child("Resim").child(uri.getLastPathSegment());
                    filePath.putFile(uri)
                            .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                                @Override
                                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                                    @SuppressWarnings("VisibleForTests")
                                    Uri downloadUrl = taskSnapshot.getDownloadUrl();
                                    Toast.makeText(RequestActivity.this, "Resim eklendi", Toast.LENGTH_LONG).show();
                                }
                            });
                    filePath.putFile(uri).addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            Log.w("İmage hata : ", e);
                        }
                    });

                }



            }

        });

    }

    public void imageButtonClicked(View View){
        Intent gallery_intent = new Intent(Intent.ACTION_GET_CONTENT);
        gallery_intent.setType("image/*");
        startActivityForResult(gallery_intent,2);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 2 && resultCode == RESULT_OK){
            uri = data.getData();
            imgbutton = (ImageButton) findViewById(R.id.imageButton);
            imgbutton.setImageURI(uri);
        }
    }
}

的Manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.jalea.requestingform">
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".RequestActivity"></activity>

    </application>

</manifest>

3 个答案:

答案 0 :(得分:0)

首先:

只有在您编写此

之后,它才会从您的第二个活动开始
  if(firebaseAuth.getCurrentUser() !=null){
                Intent intent = new Intent(MainActivity.this,RequestActivity.class);
                startActivity(intent);
                //finish(); 
                Log.w("1 : ","2.activity'e geçildi");
            } 

肯定您可能已登录并存储了auth以让用户直接转到下一个活动

对于你的第二个问题,我能够像这样做

 @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
           if (requestCode == ConstantsCustomGallery.REQUEST_CODE && resultCode == Activity.RESULT_OK && data != null) {
        //The array list has the image paths of the selected images
        ArrayList<Image> images = data.getParcelableArrayListExtra(ConstantsCustomGallery.INTENT_EXTRA_IMAGES);
        boolean showMinMax = true;
        final MaterialDialog dialog = new MaterialDialog.Builder(this)
                .title("Please wait")
                .content("This won't take too long")
                .progress(false, images.size(), showMinMax)
                .show();
        for (int i = 0; i < images.size(); i++) {
            Uri uri = Uri.fromFile(new File(images.get(i).path));
            StorageReference storage = FirebaseStorage.getInstance().getReference();

            String Fpath = getFileName(uri) ;

            //Uri file = Uri.fromFile(new File("path/to/images/rivers.jpg"));
            StorageReference riversRef = storage.child(FirebaseAuth.getInstance().getCurrentUser().getEmail()+"/images/"+Fpath);


            riversRef.putFile(uri)
                    .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                            // Get a URL to the uploaded content
                            int maxUploading = dialog.getMaxProgress();
                            dialog.incrementProgress(1);
                            if(dialog.getCurrentProgress() == dialog.getMaxProgress()){
                                dialog.dismiss();
                                new MaterialDialog.Builder(HomePageActivity.this)
                                        .title("DONE")
                                        .content("Congratulations")

                                        .show();
                            }
                            Uri downloadUrl = taskSnapshot.getDownloadUrl();
                            DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
                            String key = mDatabase.child("users").push().getKey();
                            Map<String, Object> postValues = new HashMap<String, Object>();
                            postValues.put("/user-profile/" + FirebaseAuth.getInstance().getCurrentUser().getEmail()
                                    .substring(0, FirebaseAuth.getInstance().getCurrentUser().getEmail().indexOf("@"))+"/user-images/"+key,downloadUrl.toString());
                            postValues.put("/user-profile/" + FirebaseAuth.getInstance().getCurrentUser().getEmail()
                                    .substring(0, FirebaseAuth.getInstance().getCurrentUser().getEmail().indexOf("@"))+"/imagesuploaded/",maxUploading);
                            mDatabase.updateChildren(postValues);
                        }
                    })
                    .addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception exception) {
                            // Handle unsuccessful uploads
                            // ...
                        }
                    });

        }
        dialog.setContent("Hurray!!!!");
    }
} 

答案 1 :(得分:0)

要从您想要的活动启动应用程序,请在活动的manifest.xml文件中输入以下代码

  <activity
        android:name="SpinnerActivity"
        android:screenOrientation="portrait">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

答案 2 :(得分:0)

您的应用程序会绕过MainActivity,因为您有以下代码:

 authStateListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            if(firebaseAuth.getCurrentUser() !=null){
                Intent intent = new Intent(MainActivity.this,RequestActivity.class);
                startActivity(intent);
                //finish();
                Log.w("1 : ","2.activity'e geçildi");
            }
            else{
                Log.w("1 : ", "onAuthStateChanged:çıkış yaptı");
            }
        }
    };

该代码检查用户是否已登录,然后跳过MainActivity并直接进入RequestActivity。如果您希望用户每次打开应用程序时登录,请删除该代码。

关于第二个问题,请查看以下示例代码:

    private void startPosting() {

    mProgress.setMessage("Posting... ");


    final String title_val = mPostTitle.getText().toString();
    final String desc_val = mPostDesc.getText().toString();
    final String cat_val = mPostCat.getSelectedItem().toString();
    final String currency_val = mPostCurrency.getSelectedItem().toString();
    final String amount_val = mPostAmount.getText().toString();
    final String offer_val = mPostOffer.getText().toString();
    final String pNumber_val = mPostPNumber.getText().toString();



    if(!TextUtils.isEmpty(title_val) && !TextUtils.isEmpty(desc_val) && !TextUtils.isEmpty(cat_val)&& !TextUtils.isEmpty(currency_val) && !TextUtils.isEmpty(amount_val) &&!TextUtils.isEmpty(offer_val) && !TextUtils.isEmpty(pNumber_val) && mImageUri != null ){

        mProgress.show();

        StorageReference filepath = mStorage.child("Classifieds_Images").child(mImageUri.getLastPathSegment());

        filepath.putFile(mImageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                final Uri downloadUrl = taskSnapshot.getDownloadUrl();

                final DatabaseReference newPost = mDatabase.push();



                mDatabaseUsers.child(mCurrentUser.getUid()).addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {

                        newPost.child("name").setValue(title_val);
                        newPost.child("desc").setValue(desc_val);
                        newPost.child("category").setValue(cat_val);
                        newPost.child("currency").setValue(currency_val);
                        newPost.child("amount").setValue(amount_val);
                        newPost.child("offer").setValue(offer_val);
                        newPost.child("phone number").setValue(pNumber_val);
                        newPost.child("latitude").setValue(mLastKnownLocation.getLatitude());
                        newPost.child("longitude").setValue(mLastKnownLocation.getLongitude());
                        newPost.child("timestamp").setValue(ServerValue.TIMESTAMP);
                        newPost.child("image").setValue(downloadUrl.toString());
                        newPost.child("uid").setValue(mCurrentUser.getUid());
                        newPost.child("profileImage").setValue(dataSnapshot.child("profile_image").getValue());
                        newPost.child("username").setValue(dataSnapshot.child("username").getValue()).addOnCompleteListener(new OnCompleteListener<Void>() {
                            @Override
                            public void onComplete(@NonNull Task<Void> task) {
                                if(task.isSuccessful()){

                                    startActivity(new Intent(PostActivity.this, MainActivity.class));
                                }
                            }
                        });
                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }
                });

                mProgress.dismiss();




            }
        });

    }
}
@SuppressLint("NewApi")
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    switch (requestCode) {
        case 0:
            if (resultCode == RESULT_OK) {

                mImageUri = data.getData();
                mSelectImage.setImageURI(mImageUri);

                CropImage.activity(mImageUri)
                        .setGuidelines(CropImageView.Guidelines.ON)
                        .start(this);
            }


            break;

        case 1:
            if(resultCode == RESULT_OK){
                mImageUri = data.getData();
                activity(mImageUri)
                        .setGuidelines(CropImageView.Guidelines.ON)
                        .start(this);
                mSelectImage.setImageURI(mImageUri);

            }
            break;
    }


    if (requestCode == CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
        ActivityResult result = getActivityResult(data);
        if (resultCode == RESULT_OK) {

            mImageUri = result.getUri();

            mSelectImage.setImageURI(mImageUri);

        } else if (resultCode == CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
            Exception error = result.getError();
        }
    }
}



private void selectImage() {

    final CharSequence[] items = {"Take Photo", "Choose from Library",
            "Cancel"};


    AlertDialog.Builder builder = new AlertDialog.Builder(
            PostActivity.this);


    builder.setTitle("Add Photo");
    builder.setItems(items, new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int item) {
            if (items[item].equals("Take Photo")) {
                Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                if (takePicture.resolveActivity(getPackageManager()) != null) {
                    startActivityForResult(takePicture, 0);}

            } else if (items[item].equals("Choose from Library")) {
                Intent pickPhoto = new Intent(Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(pickPhoto , 1);
            } else if (items[item].equals("Cancel")) {
                dialog.dismiss();
            }
        }
    });
    builder.show();

}

希望这有帮助