首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何将JSON文件从android上传到Firebase Storage?

如何将JSON文件从android上传到Firebase Storage?
EN

Stack Overflow用户
提问于 2018-06-07 13:23:29
回答 1查看 1.5K关注 0票数 0

我开发这个应用程序只是为了学习,所以它只有一个“上传”按钮。按下它可以将所有联系人存储在JSON文件中,然后将JSON文件上传到firebase存储中。

在创建JSON文件之前,代码工作得很好,但是一旦uploadToServer方法开始执行,应用程序就会崩溃。这是我的代码。

代码语言:javascript
复制
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();
        }
    }
}

我是android的新手,所以请原谅我犯的愚蠢的错误。

这是Logcat..。

代码语言:javascript
复制
  --------- 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)
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50733478

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档