Android Studio图片上传android.database.CursorIndexOutOfBoundsException

时间:2017-11-05 20:52:48

标签: android image android-studio upload

我编写了一个图片上传脚本。在我的模拟手机上一切正常,但如果我使用真正的手机,我会收到以下错误:

if (select value... >0)
{-- do whatever}
else{--do something different}

UploadFragment.java:

11-05 21:44:01.133 19445-19445/com.testaccount.testapp E/AndroidRuntime: FATAL EXCEPTION: main
                                                                      Process: com.testaccount.testapp, PID: 19445
                                                                      android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
                                                                          at android.database.AbstractCursor.checkPosition(AbstractCursor.java:460)
                                                                          at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
                                                                          at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
                                                                          at android.database.CursorWrapper.getString(CursorWrapper.java:137)
                                                                          at com.testaccount.testapp.UploadFragment.getPath(UploadFragment.java:141)
                                                                          at com.testaccount.testapp.UploadFragment.uploadMultipart(UploadFragment.java:85)
                                                                          at com.testaccount.testapp.UploadFragment.onClick(UploadFragment.java:186)
                                                                          at android.view.View.performClick(View.java:6213)
                                                                          at android.widget.TextView.performClick(TextView.java:11074)
                                                                          at android.view.View$PerformClick.run(View.java:23645)
                                                                          at android.os.Handler.handleCallback(Handler.java:751)
                                                                          at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                          at android.os.Looper.loop(Looper.java:154)
                                                                          at android.app.ActivityThread.main(ActivityThread.java:6692)
                                                                          at java.lang.reflect.Method.invoke(Native Method)
                                                                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
                                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)

上传与constants.java一起发布:

package com.testaccount.testapp;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import net.gotev.uploadservice.MultipartUploadRequest;
import net.gotev.uploadservice.UploadNotificationConfig;

import java.io.IOException;
import java.util.UUID;

import static android.app.Activity.RESULT_OK;

public class UploadFragment extends Fragment implements View.OnClickListener {

    //Declaring views
    private Button buttonChoose;
    private Button buttonUpload;
    private ImageView imageView;
    private EditText editText;

    //Image request code
    private int PICK_IMAGE_REQUEST = 1;

    //storage permission code
    private static final int STORAGE_PERMISSION_CODE = 123;

    //Bitmap to get image from gallery
    private Bitmap bitmap;

    //Uri to store the image uri
    private Uri filePath;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_upload);

        //Requesting storage permission
        requestStoragePermission();

        View view = inflater.inflate(R.layout.activity_upload, container, false);

        //Initializing views
        buttonChoose = (Button) view.findViewById(R.id.buttonChoose);
        buttonUpload = (Button) view.findViewById(R.id.buttonUpload);
        imageView = (ImageView) view.findViewById(R.id.imageView);
        editText = (EditText) view.findViewById(R.id.editTextName);

        //Setting clicklistener
        buttonChoose.setOnClickListener(this);
        buttonUpload.setOnClickListener(this);

        return view;
    }


    /*
    * This is the method responsible for image upload
    * We need the full image path and the name for the image in this method
    * */
    public void uploadMultipart() {
        //getting name for the image
        String name = editText.getText().toString().trim();

        //getting the actual path of the image
        String path = getPath(filePath);

        //Uploading code
        try {
            String uploadId = UUID.randomUUID().toString();

            //Creating a multi part request
            new MultipartUploadRequest(this.getContext(), uploadId, Constants.UPLOAD_URL)
                    .addFileToUpload(path, "image") //Adding file
                    .addParameter("name", name) //Adding text parameter to the request
                    .setNotificationConfig(new UploadNotificationConfig())
                    .setMaxRetries(2)
                    .startUpload(); //Starting the upload

        } catch (Exception exc) {
            Toast.makeText(this.getContext(), exc.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    //method to show file chooser
    private void showFileChooser() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
    }

    //handling the image chooser activity result
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
            filePath = data.getData();
            try {
                bitmap = MediaStore.Images.Media.getBitmap(this.getContext().getContentResolver(), filePath);
                imageView.setImageBitmap(bitmap);

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //method to get the file path from uri
    public String getPath(Uri uri) {
        Cursor cursor = this.getContext().getContentResolver().query(uri, null, null, null, null);
        cursor.moveToFirst();
        String document_id = cursor.getString(0);
        document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
        cursor.close();

        cursor = this.getContext().getContentResolver().query(
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
        cursor.moveToFirst();
        String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
        cursor.close();

        return path;
    }


    //Requesting permission
    private void requestStoragePermission() {
        if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
            return;

        if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE)) {
            //If the user has denied the permission previously your code will come to this block
            //Here you can explain why you need this permission
            //Explain here why you need this permission
        }
        //And finally ask for the permission
        ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
    }


    //This method will be called when the user will tap on allow or deny
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

        //Checking the request code of our request
        if (requestCode == STORAGE_PERMISSION_CODE) {

            //If permission is granted
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //Displaying a toast
                Toast.makeText(this.getContext(), "Permission granted now you can read the storage", Toast.LENGTH_LONG).show();
            } else {
                //Displaying another toast if permission is not granted
            }
        }
    }


    @Override
    public void onClick(View v) {
        if (v == buttonChoose) {
            showFileChooser();
        }
        if (v == buttonUpload) {
            uploadMultipart();
        }
    }
}

我服务器上的三个php脚本:

  1. dbDetails.php:
  2. /**
     * Created by Mario on 28/10/2017.
     */
    public final class Constants {
        public static final String UPLOAD_URL = "[MY-URL]/AndroidUploadImage/upload.php";
        public static final String IMAGES_URL = "[MY-URL]/AndroidUploadImage/getImages.php";
    }
    
    1. upload.php的

      <?php define('HOST','rdbms.strato.de'); define('USER','MY-USERNAME'); define('PASS','MY-PASSWORD'); define('DB','MY-DATABASENAME'); ?> ?&GT;
    2. getImages.php:

      //importing dbDetails file require_once 'dbDetails.php'; //this is our upload folder $upload_path = 'uploads/'; //Getting the server ip $server_ip = gethostbyname(gethostname()); //creating the upload url $upload_url = 'http://'.$server_ip.'/AndroidUploadImage/'.$upload_path; //response array $response = array(); if($_SERVER['REQUEST_METHOD']=='POST'){ //checking the required parameters from the request if(isset($_POST['name']) and isset($_FILES['image']['name'])){ //connecting to the database $con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect...'); //getting name from the request $name = $_POST['name']; //getting file info from the request $fileinfo = pathinfo($_FILES['image']['name']); //getting the file extension $extension = $fileinfo['extension']; //file url to store in the database $file_url = $upload_url . getFileName() . '.' . $extension; //file path to upload in the server $file_path = $upload_path . getFileName() . '.'. $extension; //trying to save the file in the directory try{ //saving the file move_uploaded_file($_FILES['image']['tmp_name'],$file_path); $sql = "INSERT INTO `db_images`.`images` (`id`, `url`, `name`) VALUES (NULL, '$file_url', '$name');"; //adding the path and name to database if(mysqli_query($con,$sql)){ //filling response array with values $response['error'] = false; $response['url'] = $file_url; $response['name'] = $name; } //if some error occurred }catch(Exception $e){ $response['error']=true; $response['message']=$e->getMessage(); } //displaying the response echo json_encode($response); //closing the connection mysqli_close($con); }else{ $response['error']=true; $response['message']='Please choose a file'; } } /* We are generating the file name so this method will return a file name for the image to be upload */ function getFileName(){ $con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect...'); $sql = "SELECT max(id) as id FROM images"; $result = mysqli_fetch_array(mysqli_query($con,$sql)); mysqli_close($con); if($result['id']==null) return 1; else return ++$result['id']; } ?&GT;
    3. 什么可能导致此错误,我该如何解决?

1 个答案:

答案 0 :(得分:0)

根据您提供的信息(几乎没有),我只能假设您正在尝试上传图片而且就是这样(不知道图片的来源,存储位置以及您要将其上传到何处)怎么样)。无论如何,堆栈跟踪非常清楚:Index 0 requested, with a size of 0。您已请求空光标的索引0,因此您获得CursorIndexOutOfBoundsException

您可能想检查光标中是否有任何数据,如果您正确保存图像等。没有更多信息,我可以帮助您。