0

I'm developing this app just for learning, so it has just one "upload" button. Pressing it should store all the contacts in a JSON file and then upload the JSON file to firebase storage.

The code works fine up to the JSON File creation but the app crashes as soon as the uploadToServer method starts executing. Here is my code...

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();
        }
    }
}

I'm a newbie to android, so forgive any silly mistakes.

This is the 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)
Temu
  • 859
  • 4
  • 11
Shivansh Kuchhal
  • 266
  • 2
  • 13

1 Answers1

0

I'm using the same code, and in upload function, just I commented the progress bar. It works really good.

CJara
  • 69
  • 9