没有这样的文件或目录异常Android

时间:2016-06-21 14:58:55

标签: android android-asynctask file-handling

在我的应用程序中,我从文档目录和意图中获取图像和视频文件,然后在请求代码匹配2的OnActivityResult()方法中获取绝对路径,然后有一个AsyncTask负责发送该文件(用于测试服务器)但它在doPlaceUpload()内的doInBackground()方法中捕获异常

例外:  /document/image:1665: open failed: ENOENT (No such file or directory)

我想我无法从绝对路径获取文件,但因为我是android的新手,所以我无法弄清楚如何做到这一点。

代码:

public class AddPlaceActivity extends ActionBarActivity {
    Button addMap,selectFiles;
    ImageView uploadBtn;
    TextView placeName,placeDesc;
    double lat;
    double lng;
    String FilePath;
    ProgressDialog pDialog;
    HttpEntity resEntity;
    ArrayList<String> FileNames=new ArrayList<String>();
    ArrayList<File> FilesToUpload=new ArrayList<File>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_place);


        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        toolbar.setTitleTextColor(0xFFFFFFFF);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        init_views();
    }

private void init_views(){
    uploadBtn = (ImageView)findViewById(R.id.place_uplaod_btn);
    addMap = (Button)findViewById(R.id.add_map_place);
    selectFiles = (Button)findViewById(R.id.add_files);

    //Listeners
    uploadBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new PostTask().execute("http://www.petrichors.com/eguide/upload_media_test.php");
        }
    });
    selectFiles.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            openGallery(2);
        }
    });
    addMap.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(AddPlaceActivity.this,AddPlaceMap.class);
            startActivityForResult(intent,1);
        }
    });
}
    public void openGallery(int req_code){

        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("*/*");
        String[] mimetypes = {"image/*", "video/*"};
        intent.putExtra(Intent.EXTRA_MIME_TYPES, mimetypes);
        startActivityForResult(intent, req_code);

    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_add_place, menu);
        return true;
    }

    // Call Back method  to get the Message form Map Activity
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        // check if the request code is same as what is passed  here it is 2
        if (resultCode == RESULT_OK) {
        if(requestCode==1)
        {
           // String message=data.getStringExtra("MESSAGE");
            lat = data.getDoubleExtra("Lat",0.0);
            lng = data.getDoubleExtra("Lng",0.0);
            //show();


        }

            //
            if (requestCode == 2)
            {
                Uri selectedFileUri = data.getData();
                File myFile = new File(selectedFileUri.getPath());
               FilesToUpload.add(myFile);

            }

        }
    }




    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
    private void show(){
         Toast.makeText(this, lat + " : " + lng, Toast.LENGTH_LONG).show();
    }

    // The definition of our task class
    private class PostTask extends AsyncTask<String, Integer, String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            Log.i("Async : ","PRe Exec");
            pDialog = new ProgressDialog(AddPlaceActivity.this);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(true);
            pDialog.show();

        }

        @Override
        protected String doInBackground(String... params) {
            // for debug worker thread
            if(android.os.Debug.isDebuggerConnected())
                android.os.Debug.waitForDebugger();

            Log.i("Async : ","Do back");
            String url=params[0];
            doPlaceUpload(url);

            return "All Done!";
        }

        //Upload Function
        private void doPlaceUpload(String Url){
            Log.i("Async : ","Do placeUpload");
            String urlString = Url;
            try
            {

                HttpClient client = new DefaultHttpClient();
                HttpPost post = new HttpPost(urlString);
                FileBody bin1 = new FileBody(FilesToUpload.get(0));
                MultipartEntity reqEntity = new MultipartEntity();
                reqEntity.addPart("uploadedfile1", bin1);
                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 {
//                                Toast.makeText(getApplicationContext(),response_str, Toast.LENGTH_LONG).show();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }
            }
            catch (Exception ex){
                String ExceptionString = ex.getMessage();
                Log.e("Debug", "UploadError: " + ex.getMessage(), ex);

            }
        }


        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            Log.i("Async : ","P-UPDATE");
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            Log.i("Async : ","POSt Exec");
            if (pDialog.isShowing())
                pDialog.dismiss();

        }
    }
}

我的问题是如何从ACTION_OPEN_DOCUMENT获取文件并将其保存在ArrayList中,就像我的情况FilesToUpload一样。因为文档可能包含视频以及图像如何分别处理它们。

1 个答案:

答案 0 :(得分:0)

  

我想我无法从绝对路径获取文件

没有&#34;绝对路径&#34;。 ACTION_OPEN_DOCUMENT无法打开文件。它打开了一条内容。该内容由Uri中的onActivityResult()表示。 The documentation for the Storage Access Framework向您展示了如何使用Uri,例如使用ContentResolveropenInputStream()

另见: