如何从Android上传JSON文件到Firebase存储?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (237)

以下是我的代码:

package com.example.shiv.uploadcontacts;

import android.app.ProgressDialog;
import android.database.Cursor;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.provider.ContactsContract;
import android.widget.Toast;
import java.io.BufferedWriter;
import java.io.File;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import org.json.JSONObject;
import java.io.FileWriter;
import java.io.Writer;


public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "shivanshTag";
    Button uploadButton;

    private Uri filePath;
    JSONObject contacts;

    private StorageReference mStorageRef;

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

        uploadButton = (Button) findViewById(R.id.uploadButton); 
        uploadButton.setOnClickListener(this);

        mStorageRef = FirebaseStorage.getInstance().getReference();
    }


    @Override
    public void onClick(View v) {

        contacts = createContactJSON();  //Contacts added to a JSON Object
        Log.i(TAG, ""+contacts);

        filePath = listToFile();         //JSON file saved to filePath
        Log.i(TAG, "File done");

        uploadToServer();               //App crashes in this method

    }

    public JSONObject createContactJSON(){

        //to store name-number pair
        JSONObject contacts = new JSONObject();

        try {
            Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);

            while (phones.moveToNext()) {
                String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                contacts.put(name, phoneNumber);
            }
            phones.close();
        }
        catch (Exception e){
            e.printStackTrace();
        }
        return contacts;
    }

    private Uri listToFile() {

        String path = null;
        try {
            Writer output = null;
            path = "/sdcard/sample.json";
            File file = new File(path);
            output = new BufferedWriter(new FileWriter(file));
            output.write(contacts.toString());
            output.close();
            Toast.makeText(getApplicationContext(), "Saved", Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
        }
        finish();
        return Uri.fromFile(new File("/sdcard/sample.json"));

    }

    //this method will upload the file
    private void uploadToServer() {
        //if there is a file to upload
        if (filePath != null) {
            //displaying a progress dialog while upload is going on
            final ProgressDialog progressDialog = new ProgressDialog(this);
            progressDialog.setTitle("Uploading...");
            progressDialog.show();

            StorageReference riversRef = mStorageRef.child("jsonFile/sample.json");
            riversRef.putFile(filePath)
                    .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                            progressDialog.dismiss();
                            Toast.makeText(getApplicationContext(), "File Uploaded", Toast.LENGTH_LONG).show();
                        }
                    })
                    .addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception exception) {
                            progressDialog.dismiss();
                            Toast.makeText(getApplicationContext(), exception.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    })
                    .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                            Log.i(TAG, "Here");
                            double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
                            progressDialog.setMessage("Uploaded " + ((int) progress) + "%...");
                        }
                    });
        }
        //if there is not any file
        else {
            Log.i(TAG, "Error");
            Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG).show();
        }
    }
}

logcat

  --------- beginning of crash
06-07 11:37:32.662 19856-19856/com.example.shiv.uploadcontacts E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.shiv.uploadcontacts, PID: 19856
    java.lang.IllegalArgumentException: View=DecorView@897e1ab[Uploading] not attached to window manager
        at android.view.WindowManagerGlobal.findViewLocked(WindowManagerGlobal.java:485)
        at android.view.WindowManagerGlobal.removeView(WindowManagerGlobal.java:394)
        at android.view.WindowManagerImpl.removeViewImmediate(WindowManagerImpl.java:124)
        at android.app.Dialog.dismissDialog(Dialog.java:371)
        at android.app.Dialog.dismiss(Dialog.java:354)
        at com.example.shiv.uploadcontacts.MainActivity$3.onSuccess(MainActivity.java:116)
        at com.example.shiv.uploadcontacts.MainActivity$3.onSuccess(MainActivity.java:113)
        at com.google.firebase.storage.zzj.zzi(Unknown Source:13)
        at com.google.firebase.storage.zzaa.run(Unknown Source:10)
        at android.os.Handler.handleCallback(Handler.java:790)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6494)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
提问于
用户回答回答于

我使用相同的代码,在上传功能中需要注释进度条

扫码关注云+社区

领取腾讯云代金券

玩转腾讯云 有奖征文活动