【问题标题】:Selected path from image showing null从显示 null 的图像中选择的路径
【发布时间】:2016-02-12 07:15:58
【问题描述】:

我已经提到了这个sample

点击上传按钮,一次上传多个文件到服务器。

但是我得到了 selectedpath1 和 selectedpath2 空指针异常。我不知道如何解决这个问题。任何人都可以帮助我。谢谢。

Logcat:

02-12 02:12:15.001: E/selectedImageUri(11964): content://com.android.providers.media.documents/document/image%3A388
02-12 02:12:15.006: E/selectedPath1(11964): null
02-12 02:12:26.949: E/selectedImageUri(11964): content://com.android.providers.media.documents/document/image%3A388
02-12 02:12:26.956: E/selectedPath2(11964): null

MainActivity.java:

public class MainActivity extends Activity {

    private static final int SELECT_FILE1 = 1;
    private static final int SELECT_FILE2 = 2;
    String selectedPath1;
    String selectedPath2;
    TextView tv, res;
    ProgressDialog progressDialog;
    Button b1, b2, b3;
    HttpEntity resEntity;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tv = (TextView) findViewById(R.id.tv);
        res = (TextView) findViewById(R.id.res);
        tv.setText(tv.getText() + selectedPath1 + "," + selectedPath2);
        b1 = (Button) findViewById(R.id.Button01);
        b2 = (Button) findViewById(R.id.Button02);
        b3 = (Button) findViewById(R.id.upload);

        b1.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                openGallery(SELECT_FILE1);
            }
        });

        b2.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                openGallery(SELECT_FILE2);
            }
        });

        b3.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!(selectedPath1.equals(""))
                        && !(selectedPath2.equals(""))) {
                    progressDialog = ProgressDialog.show(MainActivity.this,
                            "", "Uploading files to server.....", false);
                    Thread thread = new Thread(new Runnable() {
                        public void run() {
                            doFileUpload();
                            runOnUiThread(new Runnable() {
                                public void run() {
                                    if (progressDialog.isShowing())
                                        progressDialog.dismiss();
                                }
                            });
                        }
                    });
                    thread.start();
                } else {
                    Toast.makeText(getApplicationContext(),
                            "Please select two files to upload.",
                            Toast.LENGTH_SHORT).show();
                }
            }
        });

    }

    public void openGallery(int req_code) {

        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(
                Intent.createChooser(intent, "Select file to upload "),
                req_code);
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode == RESULT_OK) {  
            Uri selectedImageUri = data.getData();

            Log.e("selectedImageUri", ""+selectedImageUri);

            if (requestCode == SELECT_FILE1) {
                selectedPath1 = getPath(selectedImageUri);  -->path is Null

                Log.e("selectedPath1", ""+selectedPath1);

            }

            if (requestCode == SELECT_FILE2) {
                selectedPath2 = getPath(selectedImageUri);

                Log.e("selectedPath2", ""+selectedPath2);
            }
            tv.setText("Selected File paths : " + selectedPath1 + ","
                    + selectedPath2);
        }  
    }

    public String getPath(Uri uri) {
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }

    private void doFileUpload() {

        File file1 = new File(selectedPath1);
        File file2 = new File(selectedPath2);
        String urlString = "http://10.0.2.2/upload_test/upload_media_test.php";
        try {
            HttpClient client = new DefaultHttpClient();
            HttpPost post = new HttpPost(urlString);
            FileBody bin1 = new FileBody(file1);
            FileBody bin2 = new FileBody(file2);
            MultipartEntity reqEntity = new MultipartEntity();
            reqEntity.addPart("uploadedfile1", bin1);
            reqEntity.addPart("uploadedfile2", bin2);
            reqEntity.addPart("user", new StringBody("User"));
            post.setEntity(reqEntity);
            HttpResponse response = client.execute(post);
            resEntity = response.getEntity();
            final String response_str = EntityUtils.toString(resEntity);
            if (resEntity != null) {
                Log.i("RESPONSE", response_str);
                runOnUiThread(new Runnable() {
                    public void run() {
                        try {
                            res.setTextColor(Color.GREEN);
                            res.setText("n Response from server : n "
                                    + response_str);
                            Toast.makeText(
                                    getApplicationContext(),
                                    "Upload Complete. Check the server uploads directory.",
                                    Toast.LENGTH_LONG).show();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        } catch (Exception ex) {
            Log.e("Debug", "error: " + ex.getMessage(), ex);
        }
    }
}

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Multiple File Upload from CoderzHeaven" />

    <Button
        android:id="@+id/Button01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Get First File" >
    </Button>

    <Button
        android:id="@+id/Button02"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Get Second File" >
    </Button>

    <Button
        android:id="@+id/upload"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start Upload" >
    </Button>

    <TextView
        android:id="@+id/tv"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Selected File path : " />

    <TextView
        android:id="@+id/res"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="" />

</LinearLayout>

【问题讨论】:

    标签: android


    【解决方案1】:

    返回的内容 URI 可能会有所不同,具体取决于选择的来源。特别是由于 Kitkat(API 级别 19)引入了存储访问框架 (SAF),您可以在选择照片时查看所有文档存储提供程序。 此问题(及其修复)已在以下 StackOverflow 线程中得到解决:

    Android Gallery on KitKat returns different Uri for Intent.ACTION_GET_CONTENT

    retrieve absolute path when select image from gallery kitkat android

    或者简单地说,您可以执行以下操作:-

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            InputStream inputStream = context.getContentResolver().openInputStream(data.getData());
            //Now you can do whatever you want with your inpustream, save it as file, upload to a server
        }
    }
    

    【讨论】:

    • 您的问题现在解决了吗?如果这解决了您的问题,您可以接受。
    猜你喜欢
    • 1970-01-01
    • 2016-06-07
    • 1970-01-01
    • 1970-01-01
    • 2023-01-04
    • 2011-11-16
    • 1970-01-01
    • 2015-02-12
    • 2013-12-16
    相关资源
    最近更新 更多