上传文件时无法访问外部存储空间

时间:2016-06-19 13:01:51

标签: android image ftp

我想将文件上传到ftp。我正在使用此代码。但是每当我尝试从存储中取出图像时,它总是会让我异常无法选择文件。这是在我将android studio从android studio 1.5升级到最新版之后发生的事情。我也放弃了gradle build,但这并没有解决问题。你能告诉我为什么会这样吗?

Manifest.java

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.amobi.newlomapodfix">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="Article"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".ShopActivity"
            android:label="Shop"
            android:theme="@style/AppTheme.NoActionBar" />
        <activity
            android:name=".ReadArtikelActivity"
            android:label="Article" />
        <activity
            android:name=".SignUpActivity"
            android:label="Register" />
        <activity
            android:name=".LoginActivity"
            android:label="Login" />
        <activity
            android:name=".AccountActivity"
            android:label="@string/title_activity_account"
            android:theme="@style/AppTheme.NoActionBar" />
        <activity android:name=".EditAccountActivity" />
        <activity android:name=".UploadActivity" />
        <activity android:name=".CartActivity" />
        <activity android:name=".DetilBarangActivity"></activity>
        <!-- ATTENTION: This was auto-generated to add Google Play services to your project for
             App Indexing.  See https://g.co/AppIndexing/AndroidStudio for more information. -->
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
    </application>

</manifest>

UploadActivity.java

import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.amobi.newlomapodfix.util.SessionManagement;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.jibble.simpleftp.SimpleFTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class UploadActivity extends AppCompatActivity {

    private static final String URL_ID_TRANS = "http://amobipets.azurewebsites.net/getIdImage.php";
    private static final String URL_INSERT_IMAGE = "http://amobipets.azurewebsites.net/insertImage.php";
    private static final String URL_EDIT_TRANS = "http://amobipets.azurewebsites.net/editTrans.php";
    private static final String TAG_ID = "id";
    private static final String TAG_IMAGE_NAME = "image_name";
    private static final String TAG_STATUS = "Status";
    private static final String TAG_PESAN = "message";
    private static final String TAG_HASIL = "result";
    private static final String TAG_TRANS = "message";
    private static final String TAG_IMAGE_ID = "id_image";
    ProgressDialog pDialog;

    JSONParser jparser = new JSONParser();
    ArrayList<HashMap<String, String>> namelist, idList, imageList;
    JSONArray names, names1, names2;

    private static int RESULT_LOAD_IMG = 1;
    String imgDecodableString = null;
    Button btn;


    static final String FTP_HOST = "************";
    static final String FTP_USER = "************";
    static final String FTP_PASS = "************";
    String name, vid;
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client2;
    SessionManagement sessionManagement;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);

        sessionManagement =new SessionManagement(this);
        idList = new ArrayList<HashMap<String, String>>();
        imageList = new ArrayList<HashMap<String, String>>();

        Bundle bun = getIntent().getExtras();
        vid = bun.getString("id");

        btn = (Button) findViewById(R.id.buttonUploadPicture);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (imgDecodableString == null) {
                    Toast.makeText(UploadActivity.this, "Choose image first, please", Toast.LENGTH_LONG);
                } else {
                    File f = new File(imgDecodableString);
                    name = f.getName();
                    uploadFile(f);
                }
            }
        });

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client2 = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }


    public void loadImagefromGallery(View view) {
        // Create intent to Open Image applications like Gallery, Google Photos
        Intent galleryIntent = new Intent(Intent.ACTION_PICK,
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        // Start the Intent
        startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try {
            // When an Image is picked
            if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
                    && null != data) {
                // Get the Image from data


                Uri selectedImage = data.getData();
                String[] filePathColumn = {MediaStore.Images.Media.DATA};

                // Get the cursor
                Cursor cursor = getContentResolver().query(selectedImage,
                        filePathColumn, null, null, null);
                // Move to first row
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                String filename = cursor.getString(columnIndex);
                imgDecodableString = cursor.getString(columnIndex);
                cursor.close();

                File f = new File("" + imgDecodableString);
                f.getName();
                ImageView imgView = (ImageView) findViewById(R.id.imgView);
                // Set the Image in ImageView after decoding the String
                imgView.setImageBitmap(BitmapFactory
                        .decodeFile(imgDecodableString));

            } else {
                Toast.makeText(this, "Pilih Bukti Transaksi",
                        Toast.LENGTH_LONG).show();
            }
        } catch (Exception e) {
            Toast.makeText(this, "Failed to Choose", Toast.LENGTH_LONG)
                    .show();
        }
    }

    public void uploadFile(File fileName) {

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        SimpleFTP ftp=new SimpleFTP();

        try {
            ftp.connect(FTP_HOST, 21, FTP_USER, FTP_PASS);
            ftp.bin();
            ftp.cwd("/img/");
            ftp.stor(fileName);
            ftp.disconnect();

        } catch (Exception e) {
            e.printStackTrace();
            try {
                ftp.disconnect();
                Toast.makeText(UploadActivity.this, "disconnect", Toast.LENGTH_LONG).show();
            } catch (Exception e2) {
                e2.printStackTrace();
                Toast.makeText(UploadActivity.this, "failed", Toast.LENGTH_LONG).show();
            }
        }

    }

    @Override
    public void onStart() {
        super.onStart();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client2.connect();
        Action viewAction = Action.newAction(
                Action.TYPE_VIEW, // TODO: choose an action type.
                "Upload Page", // TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,
                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.
                Uri.parse("http://host/path"),
                // TODO: Make sure this auto-generated app deep link URI is correct.
                Uri.parse("android-app://com.amobi.newlomapodfix/http/host/path")
        );
        AppIndex.AppIndexApi.start(client2, viewAction);
    }

    @Override
    public void onStop() {
        super.onStop();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        Action viewAction = Action.newAction(
                Action.TYPE_VIEW, // TODO: choose an action type.
                "Upload Page", // TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,
                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.
                Uri.parse("http://host/path"),
                // TODO: Make sure this auto-generated app deep link URI is correct.
                Uri.parse("android-app://com.amobi.newlomapodfix/http/host/path")
        );
        AppIndex.AppIndexApi.end(client2, viewAction);
        client2.disconnect();
    }

    /*******
     * Used to file upload and show progress
     **********/

  /*  public class MyTransferListener implements FTPDataTransferListener {

        public void started() {

            btn.setVisibility(View.GONE);
            // Transfer started
            Toast.makeText(getBaseContext(), " Upload Started ...", Toast.LENGTH_SHORT).show();

        }

        public void transferred(int length) {

            // Yet other length bytes has been transferred since the last time this
            // method was called
            Toast.makeText(getBaseContext(), " transferred ..." + length, Toast.LENGTH_SHORT).show();
        }

        public void completed() {

            btn.setVisibility(View.VISIBLE);
            // Transfer completed

            Toast.makeText(getBaseContext(), " completed ...", Toast.LENGTH_LONG).show();

            new InsertImage(name).execute();

        }

        public void aborted() {

            btn.setVisibility(View.VISIBLE);
            // Transfer aborted
            Toast.makeText(getBaseContext(), " transfer aborted , please try again...", Toast.LENGTH_SHORT).show();
        }

        public void failed() {

            btn.setVisibility(View.VISIBLE);
            // Transfer failed
            System.out.println(" failed ...");
        }
    }
*/
    class InsertImage extends AsyncTask<String, String, String> {
        int sukses = 0;
        String img;

        public InsertImage(String img) {
            this.img = img;
        }

        @Override
        protected void onPreExecute() {
        }

        @Override
        protected String doInBackground(String... args) {
            List<NameValuePair> params = new ArrayList<NameValuePair>();

            params.add(new BasicNameValuePair("image_name", img));
            try {
                JSONObject json = jparser.makeHttpRequest(URL_INSERT_IMAGE, "GET", params);

                if (json != null) {
                    sukses = json.getInt(TAG_PESAN);

                    if (sukses == 1) {
                        namelist = new ArrayList<HashMap<String, String>>();
                        Log.d("Semua Nama: ", json.toString());
                        names = json.getJSONArray(TAG_HASIL);

                        for (int i = 0; i < names.length(); i++) {
                            JSONObject c = names.getJSONObject(i);
                            String img = c.getString(TAG_IMAGE_NAME);
                            HashMap<String, String> map = new HashMap<String, String>();

                            map.put(TAG_IMAGE_NAME, img);

                            namelist.add(map);
                        }
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String file_url) {

            if (sukses == 1) {
                new getID().execute();
            }
        }
    }

    public class getID extends AsyncTask<String, String, String> {

        int sukses = 0;

        public getID() {
            pDialog = new ProgressDialog(UploadActivity.this);
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog.setMessage("Loading . . .");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        @Override
        protected String doInBackground(String... args) {

            List<NameValuePair> params = new ArrayList<NameValuePair>();
            try {
                JSONObject json = jparser.makeHttpRequest(URL_ID_TRANS, "GET", params);
                if (json != null) {
                    sukses = json.getInt(TAG_PESAN);
                    if (sukses == 1) {
                        idList = new ArrayList<HashMap<String, String>>();
                        Log.d("Semua Nama: ", json.toString());
                        names1 = json.getJSONArray(TAG_HASIL);

                        for (int i = 0; i < names1.length(); i++) {
                            JSONObject c = names1.getJSONObject(i);
                            String id = c.getString(TAG_ID);

                            HashMap<String, String> map = new HashMap<String, String>();

                            map.put(TAG_ID, id);
                            idList.add(map);
                        }
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            pDialog.dismiss();
            String id_image;
            if(idList.size()==0)
            {
                id_image="1";
            }
            else {id_image = idList.get(0).get(TAG_ID);}
            new editTrans(id_image, "Uploaded", vid).execute();
        }
    }

    class editTrans extends AsyncTask<String, String, String> {
        int sukses = 0;
        String id_image, status, id_trans;

        public editTrans(String id_image, String status, String id_trans) {
            this.id_image = id_image;
            this.status = status;
            this.id_trans = id_trans;
        }

        @Override
        protected void onPreExecute() {
        }

        @Override
        protected String doInBackground(String... args) {
            List<NameValuePair> params = new ArrayList<NameValuePair>();

            params.add(new BasicNameValuePair("id_image", id_image));
            params.add(new BasicNameValuePair("Status", status));
            params.add(new BasicNameValuePair("id_trans", id_trans));

            try {
                JSONObject json = jparser.makeHttpRequest(URL_EDIT_TRANS, "GET", params);

                if (json != null) {
                    sukses = json.getInt(TAG_PESAN);

                    if (sukses == 1) {
                        imageList = new ArrayList<HashMap<String, String>>();
                        Log.d("Semua Nama: ", json.toString());
                        names2 = json.getJSONArray(TAG_HASIL);

                        for (int i = 0; i < names2.length(); i++) {
                            JSONObject c = names2.getJSONObject(i);
                            String stat = c.getString(TAG_STATUS);
                            String image = c.getString(TAG_IMAGE_ID);
                            HashMap<String, String> map = new HashMap<String, String>();

                            map.put(TAG_IMAGE_ID, image);
                            map.put(TAG_STATUS, stat);

                            imageList.add(map);
                        }
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String file_url) {

            if (sukses == 1) {
                Intent i = new Intent(UploadActivity.this, AccountActivity.class);
                startActivity(i);
            }
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
            case R.id.action_settings:
                return true;
            case R.id.logout:
                sessionManagement.logoutUser();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
}

的build.gradle

申请插件:&#39; com.android.application&#39;

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "com.amobi.newlomapodfix"
        minSdkVersion 17
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    lintOptions {
        abortOnError false
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile project(':captcha')
    compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
    compile 'com.android.support:recyclerview-v7:23.1.1'
    compile 'com.android.support:support-v4:23.2.1'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.android.support:design:23.2.1'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.squareup.retrofit:retrofit:1.9.0'
    compile 'com.android.support:cardview-v7:23.1.1'
    compile 'com.google.android.gms:play-services-appindexing:8.1.0'
    compile files('libs/simpleftp.jar')
}

1 个答案:

答案 0 :(得分:0)

您的目标是API 23必须获得

以下的运行时权限
      private static final int REQUEST_RUNTIME_PERMISSION = 1;
      // Global Variable

       void checkPremission() {
            //select which permission you want
            final String permission = Manifest.permission.WRITE_EXTERNAL_STORAGE;
                // if in fragment use getActivity()
            if (ContextCompat.checkSelfPermission(ActivityName.this, permission)
                    != PackageManager.PERMISSION_GRANTED) {
                if (ActivityCompat.shouldShowRequestPermissionRationale(ActivityName.this, permission)) {

                } else {
                    ActivityCompat.requestPermissions(ActivityName.this, new String[]{permission}, REQUEST_CAMERA_PERMISSION);
                }
            } else {
                // you have permission go ahead
                // get access to storage
            } 
        }

        @Override
        public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
            switch (requestCode) {
                case REQUEST_RUNTIME_PERMISSION:
                    final int numOfRequest = grantResults.length;
                    final boolean isGranted = numOfRequest == 1
                            && PackageManager.PERMISSION_GRANTED == grantResults[numOfRequest - 1];
                    if (isGranted) {
                        // you have permission go ahead
                        // get access to storage

                    }else{
                        // you dont have permission show toast
                    }
                    break;
                default:
                    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
            }
        }
    }