1

I followed the Kii Cloud tutorial on creating and archieving an object, and tried to implement it to my own app. What it basically does is, when user clicks on the "existingButton", it opens a new activity where user can pick an image from the gallery and upload it. I'm facing no issues on the second activity, yet the uri from the first activity comes as "null" to the second activity and I'm getting a NullPointerException eventually, since I'm trying to parse a null String. I examined this issue through debugger and found out that the problem is in the first activity's "onSaveCompleted" method. The if (exception == null) condition is not met, which basically means that I'm getting some kind of an exception, I guess. Then, if (exception instanceof CloudExecutionException) condition is not met, too. As a result, it shows the Toast of the else condition of my main if. Code is below. Thanks for any help guys.

First Activity:

public class SendNotePreActivity extends AppCompatActivity {

public static final String APP_BUCKET_NAME = "tutorial";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_send_note_pre);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    Button existingButton = (Button) findViewById(R.id.existingButton);
    existingButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            KiiBucket bucket = Kii.bucket(APP_BUCKET_NAME);
            KiiObject object = bucket.object();
            object.set("deneme", 313131);
            object.save(new KiiObjectCallBack() {

                @Override
                public void onSaveCompleted(int token, @NonNull KiiObject object,
                                            Exception exception) {
                    if (exception == null) {
                        final String uri = object.toUri().toString();
                        SharedPreferences.Editor mEditor = getSharedPreferences("args", MODE_PRIVATE).edit();
                        mEditor.putString("uri", uri);
                        mEditor.apply();
                        Toast.makeText(SendNotePreActivity.this, "SUCCESSFUL", Toast.LENGTH_LONG).show();
                    } else {
                        if (exception instanceof CloudExecutionException) {
                            Toast.makeText(SendNotePreActivity.this, "Please choose an image", Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(SendNotePreActivity.this, "Please choose an image222", Toast.LENGTH_LONG).show();
                        }
                    }
                }
            });
            Intent intent = new Intent(SendNotePreActivity.this, SendNoteActivity.class);
            startActivity(intent);
        }
    });
}
}

Second Activity:

public class SendNoteActivity extends AppCompatActivity {
ImageView imagePreview;
private static final int PICK_IMAGE = 1;
String filePath = null;
String objectUri = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_send_note);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    imagePreview = (ImageView) findViewById(R.id.imagePreview);

    Button chooseButton = (Button) findViewById(R.id.chooseButton);
    chooseButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Select Note"), PICK_IMAGE);
        }
    });
    Button sendButton = (Button) findViewById(R.id.sendButton);
    sendButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (filePath == null) {
                Toast.makeText(SendNoteActivity.this, "Please choose an image", Toast.LENGTH_LONG).show();
            } else {
                uploadFile(filePath);
            }
        }
    });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == PICK_IMAGE && resultCode == Activity.RESULT_OK && data != null) {
        Uri selectedFileUri = data.getData();
        imagePreview.setImageURI(selectedFileUri);
        filePath = getFilePathByUri(selectedFileUri);
        if (filePath == null) {
            Toast.makeText(SendNoteActivity.this, "File does not exist", Toast.LENGTH_LONG).show();
            return;
        }
    } else {
        super.onActivityResult(requestCode, resultCode, data);
        Toast.makeText(SendNoteActivity.this, "Picking failed", Toast.LENGTH_SHORT).show();
    }
}

private String getFilePathByUri(Uri selectedFileUri) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        // Workaround of retrieving file image through ContentResolver
        // for Android4.2 or later
        String filePath = null;
        FileOutputStream fos = null;
        try {
            Bitmap bmp = MediaStore.Images.Media.getBitmap(
                    SendNoteActivity.this.getContentResolver(), selectedFileUri);

            String cacheDir = Environment.getExternalStorageDirectory()
                    .getAbsolutePath() + File.separator + "tutorialapp";
            File createDir = new File(cacheDir);
            if (!createDir.exists()) {
                createDir.mkdir();
            }
            filePath = cacheDir + File.separator + "upload.jpg";
            File file = new File(filePath);

            fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 95, fos);
            fos.flush();
            fos.getFD().sync();
        } catch (Exception e) {
            filePath = null;
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (Exception e) {
                    // Nothing to do
                }
            }
        }
        return filePath;
    } else {
        String[] filePathColumn = { MediaStore.MediaColumns.DATA };
        Cursor cursor = SendNoteActivity.this.getContentResolver().query(
                selectedFileUri, filePathColumn, null, null, null);

        if (cursor == null)
            return null;
        try {
            if (!cursor.moveToFirst())
                return null;
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            if (columnIndex < 0) {
                return null;
            }
            String picturePath = cursor.getString(columnIndex);
            return picturePath;
        } finally {
            cursor.close();
        }
    }
}
private void uploadFile(String path) {
    SharedPreferences prefs = getSharedPreferences("args", MODE_PRIVATE);
    objectUri = prefs.getString("uri", "OLMADI AQ");
    KiiObject object = KiiObject.createByUri(Uri.parse(objectUri));
    File f = new File(path);
    KiiUploader uploader = object.uploader(SendNoteActivity.this, f);
    uploader.transferAsync(new KiiRTransferCallback() {

        @Override
        public void onStart(KiiRTransfer operator) {
        }

        @Override
        public void onTransferCompleted(KiiRTransfer operator, Exception e) {
            if (e == null) {
                Toast.makeText(SendNoteActivity.this, "Successful", Toast.LENGTH_LONG).show();
            } else {
                Throwable cause = e.getCause();
                if (cause instanceof CloudExecutionException)
                    Toast.makeText(SendNoteActivity.this, "Error", Toast.LENGTH_LONG).show();
                else
                    Toast.makeText(SendNoteActivity.this, "Error2", Toast.LENGTH_LONG).show();
            }
        }
    });
}
}

log:

FATAL EXCEPTION: main
                                                           Process: com.theoc.proto, PID: 8050
                                                           java.lang.NullPointerException: uriString
                                                               at android.net.Uri$StringUri.<init>(Uri.java:470)
                                                               at android.net.Uri$StringUri.<init>(Uri.java:460)
                                                               at android.net.Uri.parse(Uri.java:432)
                                                               at com.theoc.proto.SendNoteActivity.uploadFile(SendNoteActivity.java:163)
                                                               at com.theoc.proto.SendNoteActivity.access$000(SendNoteActivity.java:44)
                                                               at com.theoc.proto.SendNoteActivity$2.onClick(SendNoteActivity.java:82)
                                                               at android.view.View.performClick(View.java:4763)
                                                               at android.view.View$PerformClick.run(View.java:19821)
                                                               at android.os.Handler.handleCallback(Handler.java:739)
                                                               at android.os.Handler.dispatchMessage(Handler.java:95)
                                                               at android.os.Looper.loop(Looper.java:135)
                                                               at android.app.ActivityThread.main(ActivityThread.java:5272)
                                                               at java.lang.reflect.Method.invoke(Native Method)
                                                               at java.lang.reflect.Method.invoke(Method.java:372)
                                                               at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:909)
                                                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:704)
Onur Çevik
  • 1,560
  • 13
  • 21
  • Why don't you print the exception.getMessage() to the toast? And even more importantly: write the full exception stack to the log and post it to the question. – Gavriel Feb 01 '16 at 16:43
  • @Gavriel I updated the question with the log. Also, I didn't know about exception.getMessage() till now. I did that, and it said "KiiClient not initialized" in the toast. Hope it helps. – Onur Çevik Feb 01 '16 at 16:49
  • @Gavriel so I managed to solve that exception by following the guide on how to initialize KiiClient, and now I'm getting the other exception which is "CloudExecutionException". I tried to use getMessage for that, and it gave me a very long error message: "errorCode": "UNAUTHORIZED" "message": "Access to this resource is forbidden within current authentication context." What I understood from that is I need to provide a login screen first for a user to save an object. Is that correct? – Onur Çevik Feb 01 '16 at 17:04
  • without seeing more, it sounds correct. – Gavriel Feb 01 '16 at 17:15

1 Answers1

0

Move startActivity into onSaveCompleted, because now you start the 2nd activity before save is finishec

Gavriel
  • 18,880
  • 12
  • 68
  • 105
  • Thanks for the correction. Yet, this does not solve my problem. I'm still facing the same issue, since I'm still not able not save the object properly. – Onur Çevik Feb 01 '16 at 16:31