Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/370.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 试图将活动转换为片段_Java_Php_Android_Android Fragments - Fatal编程技术网

Java 试图将活动转换为片段

Java 试图将活动转换为片段,java,php,android,android-fragments,Java,Php,Android,Android Fragments,我试图从网站上的一个教程中创建一个程序。本程序将文件上传到PHP服务器,应用程序正在运行 我的项目名称是将文件上载到服务器 它有1个主活动和1个文件路径 这是主布局的代码: <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" an

我试图从网站上的一个教程中创建一个程序。本程序将文件上传到PHP服务器,应用程序正在运行

我的项目名称是将文件上载到服务器 它有1个主活动和1个文件路径

这是主布局的代码:

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="@dimen/activity_vertical_margin"
android:background="@color/colorAccent"
tools:context="me.pratamax.uploadfiletoserver.MainActivity">

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:textSize="18sp"
    android:id="@+id/tvHeading"
    android:text="Touch the icon below to upload file to server"
    android:textColor="#fff"
    android:textStyle="bold"/>
<ImageView
    android:id="@+id/ivAttachment"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:src="@mipmap/ic_launcher"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"/>

<TextView
    android:id="@+id/tv_file_name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textColor="#fff"
    android:layout_marginTop="10dp"
    android:gravity="center"
    android:layout_below="@+id/ivAttachment"
    android:layout_centerHorizontal="true"/>

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/b_upload"
    android:text="Upload"
    android:textStyle="bold"
    android:textSize="20sp"
    android:layout_alignParentBottom="true"
    android:gravity="center"
    android:textColor="#fff"
    android:background="#039be5"/>
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:titleTextColor="@color/colorBlack"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabMode="fixed"
            app:tabGravity="fill"
            android:background="@color/colorGreenDark"
            app:tabIndicatorColor="@color/colorGray"
            app:tabIndicatorHeight="6dp"/>
    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"  />
</android.support.design.widget.CoordinatorLayout>
对于文件路径代码:

package me.pratamax.uploadfiletoserver;

/**
 * Created by ditaa on 30/08/2016.
 */
import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;

public class FilePath {

    /**
     * Method for return file path of Gallery image/ Document / Video / Audio
     *
     * @param context
     * @param uri
     * @return path of the selected image file from gallery
     */
    @TargetApi(Build.VERSION_CODES.KITKAT)
    public static String getPath(final Context context, final Uri uri) {

        // check here to KITKAT or new version
        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {

            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/"
                            + split[1];
                }
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"),
                        Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[] { split[1] };

                return getDataColumn(context, contentUri, selection,
                        selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {

            // Return the remote address
            if (isGooglePhotosUri(uri))
                return uri.getLastPathSegment();

            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context
     *            The context.
     * @param uri
     *            The Uri to query.
     * @param selection
     *            (Optional) Filter used in the query.
     * @param selectionArgs
     *            (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public static String getDataColumn(Context context, Uri uri,
                                       String selection, String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = { column };

        try {
            cursor = context.getContentResolver().query(uri, projection,
                    selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                final int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**
     * @param uri
     *            The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri
                .getAuthority());
    }

    /**
     * @param uri
     *            The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri
                .getAuthority());
    }

    /**
     * @param uri
     *            The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri
                .getAuthority());
    }

    /**
     * @param uri
     *            The Uri to check.
     * @return Whether the Uri authority is Google Photos.
     */
    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri
                .getAuthority());
    }
}
还有一些PHP代码在我的web服务器上。这就是工作

之后,我想做一个新的项目上传和下载标签。所以我必须把它变成碎片

它有主活动、片段下载、片段上传和文件路径

主要布局如下:

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="@dimen/activity_vertical_margin"
android:background="@color/colorAccent"
tools:context="me.pratamax.uploadfiletoserver.MainActivity">

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:textSize="18sp"
    android:id="@+id/tvHeading"
    android:text="Touch the icon below to upload file to server"
    android:textColor="#fff"
    android:textStyle="bold"/>
<ImageView
    android:id="@+id/ivAttachment"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:src="@mipmap/ic_launcher"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"/>

<TextView
    android:id="@+id/tv_file_name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textColor="#fff"
    android:layout_marginTop="10dp"
    android:gravity="center"
    android:layout_below="@+id/ivAttachment"
    android:layout_centerHorizontal="true"/>

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/b_upload"
    android:text="Upload"
    android:textStyle="bold"
    android:textSize="20sp"
    android:layout_alignParentBottom="true"
    android:gravity="center"
    android:textColor="#fff"
    android:background="#039be5"/>
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:titleTextColor="@color/colorBlack"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabMode="fixed"
            app:tabGravity="fill"
            android:background="@color/colorGreenDark"
            app:tabIndicatorColor="@color/colorGray"
            app:tabIndicatorHeight="6dp"/>
    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"  />
</android.support.design.widget.CoordinatorLayout>

以下是java的主要活动:

package me.pratamax.uploaddownload;

import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private int[] tabIcons = {
            R.drawable.ic_unarchive_black_24dp,
            R.drawable.ic_archive_black_24dp
    };

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

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
//        getSupportActionBar().setDisplayHomeAsUpEnabled(true);  // Kode untuk kasih tombol back

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewPager);

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);
        setupTabIcons();
    }

    private void setupTabIcons() {
        tabLayout.getTabAt(0).setIcon(tabIcons[0]);
        tabLayout.getTabAt(1).setIcon(tabIcons[1]);
    }

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFrag(new UploadFragment(), "Upload");
        adapter.addFrag(new DownloadFragment(), "Download");
        viewPager.setAdapter(adapter);
    }

    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        public void addFrag(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }
}
package me.pratamax.uploaddownload;
导入android.support.design.widget.TabLayout;
导入android.support.v4.app.Fragment;
导入android.support.v4.app.FragmentManager;
导入android.support.v4.app.FragmentPagerAdapter;
导入android.support.v4.view.ViewPager;
导入android.support.v7.app.AppActivity;
导入android.os.Bundle;
导入android.support.v7.widget.Toolbar;
导入java.util.ArrayList;
导入java.util.List;
公共类MainActivity扩展了AppCompatActivity{
专用工具栏;
私人摊位摊位;
私人视页机视页机;
私有int[]选项卡图标={
R.drawable.ic_unarchive_black_24dp,
R.drawable.ic\u归档\u黑色\u 24dp
};
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar=(toolbar)findviewbyd(R.id.toolbar);
设置支持操作栏(工具栏);
//getSupportActionBar().setDisplayHomeAsUpEnabled(true);//返回
viewPager=(viewPager)findViewById(R.id.viewPager);
设置viewPager(viewPager);
tabLayout=(tabLayout)findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
setupTabIcons();
}
私有void setupTabIcons(){
tabLayout.getTabAt(0).setIcon(tabIcons[0]);
tabLayout.getTabAt(1).setIcon(tabIcons[1]);
}
专用无效设置ViewPager(ViewPager ViewPager){
ViewPagerAdapter适配器=新的ViewPagerAdapter(getSupportFragmentManager());
addFrag(newuploadfragment(),“Upload”);
addFrag(newdownloadfragment(),“Download”);
viewPager.setAdapter(适配器);
}
类ViewPagerAdapter扩展了FragmentPagerAdapter{
私有最终列表MFFragmentList=new ArrayList();
私有最终列表MFFragmentTitleList=new ArrayList();
公共视图页面编辑器(碎片管理器){
高级经理;
}
@凌驾
公共片段getItem(int位置){
返回MFFragmentList.get(位置);
}
@凌驾
public int getCount(){
返回MFFragmentList.size();
}
public void addFrag(片段、字符串标题){
添加(片段);
MFFragmentTitleList.add(标题);
}
@凌驾
公共字符序列getPageTitle(int位置){
返回MFFragmentTitleList.get(位置);
}
}
}
我使用上一个项目中的FilePath.java、UploadFragment.java和fragment_upload.xml


但是我不知道如何使它工作并将其活动转换为片段。

我将给出Upload fragment类的实现部分。使用相同的方式实现下载片段类。您的ViewPager包含两个片段,一个是上载,另一个是下载。因此,通过扩展Fragment类并重写onCreateView方法来实现这两个类。因此,无论您在活动的onCreate中执行什么,都要遵循相同的操作,并从upload_fragment.xml获取引用

upload_片段的布局代码与主布局文件相同

UploadFragment类

public class UploadFragment extends Fragment implements View.OnClickListener{
private static final int PICK_FILE_REQUEST = 1;
private static final String TAG = MainActivity.class.getSimpleName();
private String selectedFilePath;
private String SERVER_URL = "http://192.168.0.29/aji/AndroidFileUpload/UploadToServer.php";
ImageView ivAttachment;
Button bUpload;
TextView tvFileName;
ProgressDialog dialog;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View rootView;
    rootView = inflater.inflate(R.layout.upload_frament,container,false);
    ivAttachment = (ImageView) rootView.findViewById(R.id.ivAttachment);
    bUpload = (Button) rootView.findViewById(R.id.b_upload);
    tvFileName = (TextView) rootView.findViewById(R.id.tv_file_name);
    ivAttachment.setOnClickListener(this);
    bUpload.setOnClickListener(this);
    return rootView;
}

@Override
public void onClick(View v) {
    if(v== ivAttachment){

        //on attachment icon click
        showFileChooser();
    }
    if(v== bUpload){

        //on upload button Click
        if(selectedFilePath != null){
            dialog = ProgressDialog.show(getActivity(),"","Uploading File...",true);

            new Thread(new Runnable() {
                @Override
                public void run() {
                    //creating new thread to handle Http Operations
                    uploadFile(selectedFilePath);
                }
            }).start();
        }else{
            Toast.makeText(getActivity(),"Please choose a File First",Toast.LENGTH_SHORT).show();
        }

    }
}

private void showFileChooser() {
    Intent intent = new Intent();
    //sets the select file to all types of files
    intent.setType("file/*");
    //allows to select data and return it
    intent.setAction(Intent.ACTION_GET_CONTENT);
    //starts new activity to select file and return data
    startActivityForResult(Intent.createChooser(intent,"Choose File to Upload.."),PICK_FILE_REQUEST);
}

//android upload file to server
public int uploadFile(final String selectedFilePath){

    int serverResponseCode = 0;

    HttpURLConnection connection;
    DataOutputStream dataOutputStream;
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";


    int bytesRead,bytesAvailable,bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;
    File selectedFile = new File(selectedFilePath);


    String[] parts = selectedFilePath.split("/");
    final String fileName = parts[parts.length-1];

    if (!selectedFile.isFile()){
        dialog.dismiss();

        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tvFileName.setText("Source File Doesn't Exist: " + selectedFilePath);
            }
        });
        return 0;
    }else{
        try{
            FileInputStream fileInputStream = new FileInputStream(selectedFile);
            URL url = new URL(SERVER_URL);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);//Allow Inputs
            connection.setDoOutput(true);//Allow Outputs
            connection.setUseCaches(false);//Don't use a cached Copy
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("ENCTYPE", "multipart/form-data");
            connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
            connection.setRequestProperty("uploaded_file",selectedFilePath);

            //creating new dataoutputstream
            dataOutputStream = new DataOutputStream(connection.getOutputStream());

            //writing bytes to data outputstream
            dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
            dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
                    + selectedFilePath + "\"" + lineEnd);

            dataOutputStream.writeBytes(lineEnd);

            //returns no. of bytes present in fileInputStream
            bytesAvailable = fileInputStream.available();
            //selecting the buffer size as minimum of available bytes or 1 MB
            bufferSize = Math.min(bytesAvailable,maxBufferSize);
            //setting the buffer as byte array of size of bufferSize
            buffer = new byte[bufferSize];

            //reads bytes from FileInputStream(from 0th index of buffer to buffersize)
            bytesRead = fileInputStream.read(buffer,0,bufferSize);

            //loop repeats till bytesRead = -1, i.e., no bytes are left to read
            while (bytesRead > 0){
                //write the bytes read from inputstream
                dataOutputStream.write(buffer,0,bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable,maxBufferSize);
                bytesRead = fileInputStream.read(buffer,0,bufferSize);
            }

            dataOutputStream.writeBytes(lineEnd);
            dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

            serverResponseCode = connection.getResponseCode();
            String serverResponseMessage = connection.getResponseMessage();

            Log.i(TAG, "Server Response is: " + serverResponseMessage + ": " + serverResponseCode);

            //response code of 200 indicates the server status OK
            if(serverResponseCode == 200){
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tvFileName.setText("File Upload completed.\n\n You can see the uploaded file here: \n\n" + "http://coderefer.com/extras/uploads/"+ fileName);
                    }
                });
            }

            //closing the input and output streams
            fileInputStream.close();
            dataOutputStream.flush();
            dataOutputStream.close();



        } catch (FileNotFoundException e) {
            e.printStackTrace();
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getActivity(),"File Not Found",Toast.LENGTH_SHORT).show();
                }
            });
        } catch (MalformedURLException e) {
            e.printStackTrace();
            Toast.makeText(getActivity(), "URL error!", Toast.LENGTH_SHORT).show();

        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(getActivity(), "Cannot Read/Write File!", Toast.LENGTH_SHORT).show();
        }
        dialog.dismiss();
        return serverResponseCode;
    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(resultCode == Activity.RESULT_OK){
        if(requestCode == PICK_FILE_REQUEST){
            if(data == null){
                //no data present
                return;
            }


            Uri selectedFileUri = data.getData();
            selectedFilePath = FilePath.getPath(this,selectedFileUri);
            Log.i(TAG,"Selected File Path:" + selectedFilePath);

            if(selectedFilePath != null && !selectedFilePath.equals("")){
                tvFileName.setText(selectedFilePath);
            }else{
                Toast.makeText(getActivity(),"Cannot upload file to server",Toast.LENGTH_SHORT).show();
            }
        }
    }
}

}

我在一个片段中使用了相同的代码。您只需要在异步任务中进行网络调用

 class RetrieveFeedTask extends AsyncTask<String, Void, Integer> {
    @Override
    protected Integer doInBackground(String... strings) {
        int serverResponseCode = 0;

        HttpURLConnection connection;
        DataOutputStream dataOutputStream;
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";


        int bytesRead,bytesAvailable,bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;
        File selectedFile = new File(strings[0]);


        String[] parts = strings[0].split("/");
        final String fileName = parts[parts.length-1];


        try{
            FileInputStream fileInputStream = new FileInputStream(selectedFile);
            URL url = new URL("url");
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);//Allow Inputs
            connection.setDoOutput(true);//Allow Outputs
            connection.setUseCaches(false);//Don't use a cached Copy
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("ENCTYPE", "multipart/form-data");
            connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
            connection.setRequestProperty("uploaded_file",strings[0]);

            //creating new dataoutputstream
            dataOutputStream = new DataOutputStream(connection.getOutputStream());

            //writing bytes to data outputstream
            dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
            dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
                    + strings[0] + "\"" + lineEnd);

            dataOutputStream.writeBytes(lineEnd);

            //returns no. of bytes present in fileInputStream
            bytesAvailable = fileInputStream.available();
            //selecting the buffer size as minimum of available bytes or 1 MB
            bufferSize = Math.min(bytesAvailable,maxBufferSize);
            //setting the buffer as byte array of size of bufferSize
            buffer = new byte[bufferSize];

            //reads bytes from FileInputStream(from 0th index of buffer to buffersize)
            bytesRead = fileInputStream.read(buffer,0,bufferSize);

            //loop repeats till bytesRead = -1, i.e., no bytes are left to read
            while (bytesRead > 0){
                //write the bytes read from inputstream
                dataOutputStream.write(buffer,0,bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable,maxBufferSize);
                bytesRead = fileInputStream.read(buffer,0,bufferSize);
            }

            dataOutputStream.writeBytes(lineEnd);
            dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

            serverResponseCode = connection.getResponseCode();
            String serverResponseMessage = connection.getResponseMessage();

            Log.i(TAG, "Server Response is: " + serverResponseMessage + ": " + serverResponseCode);

            //response code of 200 indicates the server status OK
            if(serverResponseCode == 200){
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // tvFileName.setText("File Upload completed.\n\n You can see the uploaded file here: \n\n" + "http://coderefer.com/extras/uploads/"+ fileName);
                    }
                });
            }

            //closing the input and output streams
            fileInputStream.close();
            dataOutputStream.flush();
            dataOutputStream.close();



        } catch (FileNotFoundException e) {
            e.printStackTrace();
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getActivity(),"File Not Found",Toast.LENGTH_SHORT).show();
                }
            });
        } catch (MalformedURLException e) {
            e.printStackTrace();
            Toast.makeText(getActivity(), "URL error!", Toast.LENGTH_SHORT).show();

        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getActivity(), "Cannot Read/Write File!", Toast.LENGTH_SHORT).show();
        }
        //dialog.dismiss();
        return serverResponseCode;


    }

}
class RetrieveFeedTask扩展了AsyncTask{
@凌驾
受保护的整数doInBackground(字符串…字符串){
int serverResponseCode=0;
httpurl连接;
DataOutputStream DataOutputStream;
字符串lineEnd=“\r\n”;
字符串双连字符=“--”;
字符串边界=“*******”;
int字节读取,字节可用,缓冲区大小;
字节[]缓冲区;
int maxBufferSize=1*1024*1024;
File selectedFile=新文件(字符串[0]);
字符串[]部分=字符串[0]。拆分(“/”;
最终字符串文件名=零件[parts.length-1];
试一试{
FileInputStream FileInputStream=新的FileInputStream(selectedFile);
URL=新URL(“URL”);
connection=(HttpURLConnection)url.openConnection();
connection.setDoInput(true);//允许输入
connection.setDoOutput(true);//允许输出
connection.setUseCaches(false);//不要使用缓存副本
connection.setRequestMethod(“POST”);
setRequestProperty(“连接”,“保持活动”);
connection.setRequestProperty(“ENCTYPE”、“多部分/表单数据”);
connection.setRequestProperty(“内容类型”、“多部分/表单数据;边界=“+boundary”);
setRequestProperty(“上传的_文件”,字符串[0]);
//创建新的dataoutputstream
dataOutputStream=新的dataOutputStream(connection.getOutputStream());
//将字节写入数据输出流
dataOutputStream.writeBytes(两个连字符+边界+lineEnd);
dataOutputStream.writeBytes(“内容处置:表单数据;名称=\”上传的文件\“文件名=\”
+字符串[0]+“\”“+lineEnd);
dataOutputStream.writeBytes(lineEnd);
//返回