1

我遵循了关于创建和归档对象的 Kii Cloud 教程,并尝试在我自己的应用程序中实现它。它的基本作用是,当用户单击“existingButton”时,它会打开一个新活动,用户可以在其中从图库中选择图像并上传。我在第二个活动中没有遇到任何问题,但是来自第一个活动的 uri 对第二个活动来说是“null”并且我最终得到了 NullPointerException,因为我正在尝试解析一个空字符串。我通过调试器检查了这个问题,发现问题出在第一个活动的“onSaveCompleted”方法中。不满足 if (exception == null) 条件,这基本上意味着我遇到了某种异常,我猜。那么,if (exception instanceof CloudExecutionException) 条件也不满足。结果,它显示了我的 main if 的 else 条件的 Toast。代码如下。感谢您的帮助。

第一个活动:

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

第二个活动:

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

日志:

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)
4

1 回答 1

0

将 startActivity 移到 onSaveCompleted 中,因为现在您在 save 完成之前开始了第二个活动

于 2016-02-01T16:17:15.253 回答