本文介绍了安卓:使用片段和导航抽屉上传图片到服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

最初,我提出,使用的活动 ListActivity 上传照片到PHP服务器的应用程序。现在我切换相同应用的片段使用的抽屉式导航

我设法这样做:

我做了扩展的Java类的片段名为 MyGalleryFragment 并是这样的:

 公共类MyGalleryFragment扩展片段{    公共ImageLoader的ImageLoader的= ImageLoader.getInstance();    上下文语境;    公共MyGalleryFragment(){}    私人ProgressDialog对话框= NULL;
    私人诠释serverResponse code = 0;
    公共字符串imgPath = NULL;
    字符串upLoadServerUri =htt​​p://www.jhamel.com/print/Uplo​​adToServer.php;    SessionMngr会议;    字符串lineEnd =\\ r \\ n;
    串twoHypens = - ;
    字符串边界=*****;    TextView的tvMulMsg;    私人的ArrayList<串GT; imageUrls;
    私人DisplayImageOptions选择;
    私人ImageAdapter imageAdapter;    公共查看onCreateView(LayoutInflater充气器,容器的ViewGroup,
            捆绑savedInstanceState){        上下文= container.getContext();        查看rootView = inflater.inflate(R.layout.ac_image_grid,集装箱,FALSE);        最终的String [] =列{MediaStore.Images.Media.DATA,MediaStore.Images.Media._ID};
        最后弦乐ORDERBY = MediaStore.Images.Media.DATE_TAKEN;        光标imagecursor = getActivity()。getContentResolver()查询(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                列,
                空值,
                空值,
                排序依据);        this.imageUrls =新的ArrayList<串GT;();        的for(int i = 0; I< imagecursor.getCount();我++){
            imagecursor.moveToPosition(ⅰ);
            INT dataColumnIndex = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);
            imageUrls.add(imagecursor.getString(da​​taColumnIndex));            的System.out.println(=====>数组路径=>中+ imageUrls.get(ⅰ));
        }        选项​​=新DisplayImageOptions.Builder()
            .showStubImage(R.drawable.stub_image)
            .showImageForEmptyUri(R.drawable.image_for_empty_url)
            .cacheInMemory()
            .cacheOnDisc()
            。建立();        imageAdapter =新ImageAdapter(背景下,imageUrls);
        GridView控件的GridView =(GridView控件)rootView.findViewById(R.id.gridview);
        gridView.setAdapter(imageAdapter);        返回rootView;
    }    @覆盖
    公共无效的onStop(){
        imageLoader.stop();
        super.onStop();
    }    公共无效btnChoosePhotosClick(视图v){        最终的ArrayList<串GT; selectedItems = imageAdapter.getCheckedItems();        对话框= ProgressDialog.show(背景下,,上传文件...,真正的);
        新主题(新的Runnable接口(){
        公共无效的run(){
            UploadFile(selectedItems);
        }
        })。开始();
            }    公共类ImageAdapter延伸BaseAdapter {        ArrayList的<串GT; mList;
        LayoutInflater mInflater;
        上下文mContext;
        SparseBooleanArray msparseBooleanArray;        公共ImageAdapter(上下文的背景下,ArrayList的<串GT;图像列表){
            mContext =背景;
            mInflater = LayoutInflater.from(mContext);
            msparseBooleanArray =新SparseBooleanArray();
            mList =新的ArrayList<串GT;();
            this.mList =图像列表;
            imageLoader.init(ImageLoaderConfiguration.createDefault(上下文));
        }        公众的ArrayList<串GT; getCheckedItems(){
            ArrayList的<串GT; mTempArray =新的ArrayList<串GT;();            的for(int i = 0; I< mList.size();我++){
                如果(msparseBooleanArray.get(ⅰ)){
                    mTempArray.add(mList.get(I));
                }
            }
            返回mTempArray;
        }        @覆盖
        公众诠释的getCount(){
            返回imageUrls.size();
        }
        @覆盖
        公共对象的getItem(INT位置){//参数是位置
            返回null;
        }
        @覆盖
        众长getItemId(INT位置){//参数是位置
            返回的位置;
        }
        @覆盖
        公共查看getView(INT位置,查看convertView,父母的ViewGroup){            如果(convertView == NULL){
                convertView = mInflater.inflate(R.layout.row_multiphoto_item,NULL);
            }            复选框mCheckBox =(复选框)convertView.findViewById(R.id.checkBox1);            最后ImageView的ImageView的=(ImageView的)convertView.findViewById(R.id.imageView1);            imageLoader.displayImage(文件://+ imageUrls.get(位置),ImageView的,选项,新SimpleImageLoadingListener(){
                @覆盖
                公共无效onLoadingComplete(位图loadedImage){
                    动画动画= AnimationUtils.loadAnimation(背景下,R.anim.fade_in);
                    imageView.setAnimation(阿尼姆);
                    anim.start();
                }
            });            mCheckBox.setTag(位置);
            mCheckBox.setChecked(msparseBooleanArray.get(位置));
            mCheckBox.setOnCheckedChangeListener(mCheckedChangeListener);            返回convertView;
        }
        OnCheckedChangeListener mCheckedChangeListener =新OnCheckedChangeListener(){            @覆盖
            公共无效onCheckedChanged(CompoundButton buttonView,布尔器isChecked){
                msparseBooleanArray.put((整数)buttonView.getTag(),器isChecked);
            }
        };
    }
    保护INT UploadFile(ArrayList的<串GT; sourceFileUri){        ConnectionMngr厘米=新ConnectionMngr(背景);
        布尔连接= cm.hasConnection();
        如果(!连接){
            Toast.makeText(背景下,无Internet连接,请连接到互联网,然后再试一次,Toast.LENGTH_LONG).show();
            返回0;
        }        字符串文件名; // = sourceFileUri.get(2)的ToString();        HttpURLConnection的康恩= NULL;
        DataOutputStream类DOS = NULL;
        INT读取动作,方bytesAvailable,缓冲区大小;
        字节[]缓冲区;
        INT MAXBUFFERSIZE = 1 * 1024 * 1024;
        文件的SourceFile = NULL;            尝试{
                //打开一个URL连接到Servelet的
                的FileInputStream的FileInputStream = NULL;
                网址URL =新的URL(upLoadServerUri);                //打开HTTP连接的URL
                康恩=(HttpURLConnection类)url.openConnection();
                conn.setDoInput(真); //允许输入
                conn.setDoOutput(真); //允许输出
                conn.setUseCaches(假); //不要使用缓存副本
                conn.setRequestMethod(POST); //设置连接方法
                conn.setRequestProperty(连接,保持活动);
                conn.setRequestProperty(ENCTYPE,多部分/表单数据);
                conn.setRequestProperty(内容类型,的multipart / form-data的;边界=+边界);                的for(int i = 0; I< sourceFileUri.size();我++){                    的资源文件=新的文件(sourceFileUri.get(I));
                    //布尔标志= _ifIsFile(的资源文件);                    如果(!_ ifIsFile(的资源文件)){
                        返回0;
                    }                    文件名= sourceFile.toString();
                    的FileInputStream =新的FileInputStream(的资源文件);
                    //conn.setRequestProperty(uploaded_file [],文件名);                    DOS =新的DataOutputStream类(conn.getOutputStream());                    dos.writeBytes(twoHypens +边界+ lineEnd);
                    dos.writeBytes(内容处置:表格数据;名称= \\uploaded_file [] \\文件名= \\+文件名+\\+ lineEnd);
                    //dos.writeBytes(\"Content-Disposition:表格数据;名称= \\UID \\;文件名= \\+拉宾+\\+ lineEnd);
                    dos.writeBytes(lineEnd);                    //创建最大大小的缓冲区
                    参考bytesAvailable = fileInputStream.available();                    BUFFERSIZE = Math.min(方bytesAvailable,MAXBUFFERSIZE);
                    缓冲区=新的字节[缓冲区大小]                    //读取文件,并将其写入形式
                    读取动作= fileInputStream.read(缓冲液,0,缓冲区大小);                    而(读取动作大于0){
                        dos.write(缓冲液,0,缓冲区大小);
                        参考bytesAvailable = fileInputStream.available();
                        BUFFERSIZE = Math.min(方bytesAvailable,MAXBUFFERSIZE);
                        读取动作= fileInputStream.read(缓冲液,0,缓冲区大小);
                    }
                    //dos.writeBytes(lineEnd);
                    dos.writeBytes(twoHypens +边界+ lineEnd);
                    dos.writeBytes(内容处置:表格数据;名称= \\UID \\;值= \\+拉宾什雷斯塔+\\+ lineEnd);
                    dos.writeBytes(内容类型:text / plain的;字符集= US-ASCII+ lineEnd);
                    dos.writeBytes(内容传输编码:8位+ lineEnd);                    dos.writeBytes(lineEnd);
                }
                //发送必要的多部分表单数据文件中的数据后,
                dos.writeBytes(twoHypens +边界+ twoHypens + lineEnd);                //服务器的响应(code和消息)
                serverResponse code = conn.getResponse code();
                串serverResponseMessage = conn.getResponseMessage();                Log.i(一个UploadFile,HTTP响应是:
                        + serverResponseMessage +:+ serverResponse code);
                如果(serverResponse code == 200){如果创建// http响应
                    getActivity()。runOnUiThread(新的Runnable(){
                        公共无效的run(){
                            弦乐味精=文件上传完成。
                            //tvM​​ulMsg.setText(msg);
                            吐司面包= Toast.makeText(背景下,味精,Toast.LENGTH_SHORT);
                            toast.show();                        }
                    });
                }
                //关闭流//
                fileInputStream.close();
                dos.flush();
                dos.close();
            }
            赶上(MalformedURLException的前){                dialog.dismiss();
                ex.printStackTrace();                getActivity()。runOnUiThread(新的Runnable(){
                    公共无效的run(){
                        tvMulMsg.setText(MalformedURLException的例外情况:检查脚本网址。);
                        //Toast.makeText(Gallery.thisMalformedURLException的,Toast.LENGTH_SHORT).show();
                    }
                });                Log.e(上传文件到服务器,错误:+ ex.getMessage(),除息);
            }赶上(例外五){                dialog.dismiss();
                e.printStackTrace();                getActivity()。runOnUiThread(新的Runnable(){
                    公共无效的run(){
                        tvMulMsg.setText(得到的异常与服务器」);
                        //Toast.makeText(context,得到了异常与服务器,Toast.LENGTH_SHORT).show();
                    }
                });
                Log.e(上传文件到服务器异常,异常:+ e.getMessage(),E);
            }
            dialog.dismiss();
        返回serverResponse code;
    }    公共布尔_ifIsFile(档案文件){
        如果(!file.isFile()){
            dialog.dismiss();            Log.e(一个UploadFile,源文件不存在:+ imgPath);            getActivity()。runOnUiThread(新的Runnable(){                @覆盖
                公共无效的run(){
                    tvMulMsg.setText(源文件不存在:+ imgPath);
                }
            });
            返回false;
        }
        返回true;
    }}

控制台类是这样的:

  @覆盖
保护无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.dashboard);    mTitle = mDrawerTitle =的getTitle();
    mPlanetTitles = getResources()getStringArray(R.array.planets_array)。
    mDrawerLayout =(DrawerLayout)findViewById(R.id.drawer_layout);
    mDrawerList =(ListView控件)findViewById(R.id.left_drawer);    //抽屉打开时设置覆盖的主要内容自定义阴影
    mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,GravityCompat.START);
    //设置抽屉的列表视图与项目,然后点击监听器
    mDrawerList.setAdapter(新ArrayAdapter<串GT;(这一点,
            R.layout.drawer_list_item,mPlanetTitles));
    mDrawerList.setOnItemClickListener(新DrawerItemClickListener());    //使动作条的应用程序图标表现为动作切换导航抽屉
    getActionBar()setDisplayHomeAsUpEnabled(真)。
    getActionBar()setHomeButtonEnabled(真)。    // ActionBarDrawerToggle联系在一起的适当交互
    滑动抽屉以及操作栏的程序图标之间//
    mDrawerToggle =新ActionBarDrawerToggle(
            对此,/ *主机活动* /
            mDrawerLayout,/ * DrawerLayout对象* /
            R.drawable.ic_drawer,/ *导航抽屉图像替换上插入符* /
            R.string.drawer_open,/ *开放抽屉的描述可访问* /
            R.string.drawer_close / *关闭抽屉的描述可访问* /
            ){
        公共无效onDrawerClosed(查看视图){
            。getActionBar()的setTitle(mTitle);
            invalidateOptionsMenu(); //创建调用上prepareOptionsMenu()
        }        公共无效onDrawerOpened(查看drawerView){
            。getActionBar()的setTitle(mDrawerTitle);
            invalidateOptionsMenu(); //创建调用上prepareOptionsMenu()
        }
    };
    mDrawerLayout.setDrawerListener(mDrawerToggle);    如果(savedInstanceState == NULL){
        选择信息(0);
    }
}@覆盖
公共布尔onCreateOptionsMenu(菜单菜单){
    MenuInflater吹气= getMenuInflater();
    inflater.inflate(R.menu.main,菜单);
    返回super.onCreateOptionsMenu(菜单);
}/ *调用每当我们称之为invalidateOptionsMenu()* /
@覆盖
prepareOptionsMenu(菜单菜单)上公共布尔{
    //如果资产净值抽屉被打开,隐藏操作项相关内容视图
    布尔drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
    menu.findItem(R.id.action_websearch).setVisible(drawerOpen!);
    返回super.on prepareOptionsMenu(菜单);
}@覆盖
公共布尔onOptionsItemSelected(菜单项项){
     //操作栏的家/跟进行动应打开或关闭抽屉。
     // ActionBarDrawerToggle将照顾这。
    如果(mDrawerToggle.onOptionsItemSelected(项目)){
        返回true;
    }
    //手柄操作按钮
    开关(item.getItemId()){
    案例R.id.action_websearch:
        //创建意图为这个星球上执行网络搜索
        意向意图=新意图(Intent.ACTION_WEB_SEARCH);
        intent.putExtra(SearchManager.QUERY,getActionBar()的getTitle());
        //捕获事件,有没有活动处理的意图
        如果(intent.resolveActivity(getPackageManager())!= NULL){
            startActivity(意向);
        }其他{
            Toast.makeText(这一点,R.string.app_not_available,Toast.LENGTH_LONG).show();
        }
        返回true;
    默认:
        返回super.onOptionsItemSelected(项目);
    }
}/ *的点击听者在导航抽屉的ListView * /
私有类DrawerItemClickListener实现ListView.OnItemClickListener {
    @覆盖
    公共无效onItemClick(适配器视图<>母公司,观景,INT位置,长的id){
        选择信息(位置);
    }
}/ **片段互换的主要内容视图* /
私人无效选择信息(INT位置){
    片段片段= NULL;    开关(位置){
        情况下0:
            片段=新MyGalleryFragment();
            打破;
        情况1:
            片段=新MyGalleryFragment();
            打破;
        案例2:
            片段=新MyGalleryFragment();
            打破;
        案例3:
            片段=新MyGalleryFragment();
            打破;
        情况4:
            片段=新MyGalleryFragment();
            打破;
        情况5:
            片段=新PlanetFragment();
            打破;
        情况6:
            片段=新PlanetFragment();
            打破;
        案例7:
            片段=新PlanetFragment();
            打破;
        案例8:
            片段=新PlanetFragment();
            打破;
        案例9:
            片段=新PlanetFragment();
            打破;
        案例10:
            片段=新PlanetFragment();
            打破;
        案例11:
            片段=新PlanetFragment();
            打破;
        案例12:
            片段=新PlanetFragment();
            打破;        默认:
            打破;
    }    如果(位置> = 5){
        捆绑ARGS =新包();
        args.putInt(PlanetFragment.ARG_PLANET_NUMBER,位置);
        fragment.setArguments(参数);
        如果(片段!= NULL){
            FragmentManager fragmentManager = getFragmentManager();
            fragmentManager.beginTransaction()
                            .replace(R.id.content_frame,片段)
                            。承诺();            mDrawerList.setItemChecked(位置,真正的);
            mDrawerList.setSelection(位置);
            的setTitle(mPlanetTitles [位置]);
            mDrawerLayout.closeDrawer(mDrawerList);
        }
    }其他{
        意图I =新意图(Dashboard.this,MyGallery.class);
        startActivity(ⅰ);
    }    Toast.makeText(getApplicationContext(),Integer.toString(位置),Toast.LENGTH_LONG).show();}@覆盖
公共无效的setTitle(CharSequence的标题){
    mTitle =称号;
    。getActionBar()的setTitle(mTitle);
}/ **
 *当使用ActionBarDrawerToggle,你必须在调用它
 * onPostCreate()和onConfigurationChanged()...
 * /@覆盖
保护无效onPostCreate(捆绑savedInstanceState){
    super.onPostCreate(savedInstanceState);
    //同步onRestoreInstanceState后切换状态已经发生。
    mDrawerToggle.syncState();
}@覆盖
公共无效onConfigurationChanged(配置NEWCONFIG){
    super.onConfigurationChanged(NEWCONFIG);
    //把任何配置更改抽屉切换
    mDrawerToggle.onConfigurationChanged(NEWCONFIG);
}/ **
 出现在content_frame*片段,显示了星球
 * /
公共静态类PlanetFragment扩展片段{
    公共静态最后弦乐ARG_PLANET_NUMBER =planet_number;    公共PlanetFragment(){
        //为子片段需要空的构造
    }    @覆盖
    公共查看onCreateView(LayoutInflater充气器,容器的ViewGroup,
            捆绑savedInstanceState){
        查看rootView = inflater.inflate(R.layout.fragment_planet,集​​装箱,FALSE);
        。INT I = getArguments()调用getInt(ARG_PLANET_NUMBER);
        。字符串星球= getResources()getStringArray(R.array.planets_array)[我]        INT imageId = getResources()。则getIdentifier(planet.toLowerCase(Locale.getDefault()),
                        绘制,getActivity()getPackageName());
        ((ImageView的)rootView.findViewById(R.id.image))setImageResource(imageId)。
        getActivity()的setTitle(行星)。
        返回rootView;
    }
}

也是我对你的Git可以派生的。

如果您已经下载了这个项目比的用户名:密码作为应用程序的测试:测试

我是新来的Andr​​oid,也片段很新的给我。

请帮助


解决方案

 找不到在活动课jsoft.projects.photoprint_v1_1.Dashboard上的onClick处理程序的方法btnChoosePhotosClick(视图)视图类android.widget.Button id为按钮1

您必须创建方法btnChoosePhotosClick(查看)中Dashboard.java。我不喜欢从布局调用方法,我preFER做这样的事情:

 按钮按钮=(按钮)findViewById(R.id.button1);
button.setOnClickListener(新OnClickListener(){@覆盖
公共无效的onClick(视图v){
    btnChoosePhotosClick(五);
}
});

Initially I made an app that uploads photos to a php server using Activity and ListActivity. Now I am switching the same app to fragments using navigation drawer.

I managed to do like this:

I made a java class extending Fragment called MyGalleryFragment and is like this:

public class MyGalleryFragment extends Fragment {

    public ImageLoader imageLoader = ImageLoader.getInstance();

    Context context;

    public MyGalleryFragment() {}

    private ProgressDialog dialog = null;
    private int serverResponseCode = 0;
    public String imgPath = null;
    String upLoadServerUri = "http://www.jhamel.com/print/UploadToServer.php";

    SessionMngr session;

    String lineEnd = "\r\n";
    String twoHypens = "--";
    String boundary = "*****";

    TextView tvMulMsg;

    private ArrayList<String> imageUrls;
    private DisplayImageOptions options;
    private ImageAdapter imageAdapter;

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        context = container.getContext();

        View rootView = inflater.inflate(R.layout.ac_image_grid, container, false);

        final String[] columns = { MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID };
        final String orderBy = MediaStore.Images.Media.DATE_TAKEN;

        Cursor imagecursor = getActivity().getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                columns,
                null,
                null,
                orderBy);

        this.imageUrls = new ArrayList<String>();

        for (int i = 0; i < imagecursor.getCount(); i++) {
            imagecursor.moveToPosition(i);
            int dataColumnIndex = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);
            imageUrls.add(imagecursor.getString(dataColumnIndex));

            System.out.println("=====> Array path => "+imageUrls.get(i));
        }

        options = new DisplayImageOptions.Builder()
            .showStubImage(R.drawable.stub_image)
            .showImageForEmptyUri(R.drawable.image_for_empty_url)
            .cacheInMemory()
            .cacheOnDisc()
            .build();

        imageAdapter = new ImageAdapter(context, imageUrls);


        GridView gridView = (GridView) rootView.findViewById(R.id.gridview);
        gridView.setAdapter(imageAdapter);

        return rootView;
    }

    @Override
    public void onStop() {
        imageLoader.stop();
        super.onStop();
    }

    public void btnChoosePhotosClick(View v){

        final ArrayList<String> selectedItems = imageAdapter.getCheckedItems();

        dialog = ProgressDialog.show(context, "", "Uploading file...",true);
        new Thread(new Runnable(){
        public void run(){
            UploadFile(selectedItems);
        }
        }).start();
            }

    public class ImageAdapter extends BaseAdapter{

        ArrayList<String> mList;
        LayoutInflater mInflater;
        Context mContext;
        SparseBooleanArray msparseBooleanArray;

        public ImageAdapter(Context context, ArrayList<String> imageList) {
            mContext = context;
            mInflater = LayoutInflater.from(mContext);
            msparseBooleanArray = new SparseBooleanArray();
            mList = new ArrayList<String>();
            this.mList = imageList;
            imageLoader.init(ImageLoaderConfiguration.createDefault(context));
        }

        public ArrayList<String> getCheckedItems(){
            ArrayList<String> mTempArray = new ArrayList<String>();

            for(int i=0;i<mList.size();i++){
                if(msparseBooleanArray.get(i)){
                    mTempArray.add(mList.get(i));
                }
            }
            return mTempArray;
        }

        @Override
        public int getCount() {
            return imageUrls.size();
        }
        @Override
        public Object getItem(int position) { //argument is position
            return null;
        }
        @Override
        public long getItemId(int position) { //argument is position
            return position;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            if(convertView == null){
                convertView = mInflater.inflate(R.layout.row_multiphoto_item, null);
            }

            CheckBox mCheckBox = (CheckBox) convertView.findViewById(R.id.checkBox1);

            final ImageView imageView =(ImageView) convertView.findViewById(R.id.imageView1);

            imageLoader.displayImage("file://"+imageUrls.get(position), imageView, options, new SimpleImageLoadingListener() {
                @Override
                public void onLoadingComplete(Bitmap loadedImage) {
                    Animation anim = AnimationUtils.loadAnimation(context, R.anim.fade_in);
                    imageView.setAnimation(anim);
                    anim.start();
                }
            });

            mCheckBox.setTag(position);
            mCheckBox.setChecked(msparseBooleanArray.get(position));
            mCheckBox.setOnCheckedChangeListener(mCheckedChangeListener);

            return convertView;
        }
        OnCheckedChangeListener mCheckedChangeListener = new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                msparseBooleanArray.put((Integer) buttonView.getTag(), isChecked);
            }
        };
    }


    protected int UploadFile(ArrayList<String> sourceFileUri){

        ConnectionMngr cm = new ConnectionMngr(context);
        boolean connection = cm.hasConnection();
        if(!connection){
            Toast.makeText(context, "No Internet Connection. Please connect to the internet and try again", Toast.LENGTH_LONG).show();
            return 0;
        }

        String fileName;// = sourceFileUri.get(2).toString();

        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1*1024*1024;
        File sourceFile = null;

            try{
                // Open a URL connection to the Servelet
                FileInputStream fileInputStream = null;
                URL url = new URL(upLoadServerUri);

                // Open a HTTP connection to the URL
                conn = (HttpURLConnection)url.openConnection();
                conn.setDoInput(true); // Allow Inputs
                conn.setDoOutput(true); // Allow Outputs
                conn.setUseCaches(false); // Don't use a Cached copy
                conn.setRequestMethod("POST"); //Sets connection method
                conn.setRequestProperty("Connection", "Keep-Alive");
                conn.setRequestProperty("ENCTYPE", "multipart/form-data");
                conn.setRequestProperty("Content-Type", "multipart/form-data; boundary="+boundary);

                for(int i=0 ; i<sourceFileUri.size() ; i++){

                    sourceFile = new File(sourceFileUri.get(i));
                    //boolean flag = _ifIsFile(sourceFile);

                    if(!_ifIsFile(sourceFile)){
                        return 0;
                    }

                    fileName = sourceFile.toString();
                    fileInputStream = new FileInputStream(sourceFile);
                    //conn.setRequestProperty("uploaded_file[]", fileName);

                    dos = new DataOutputStream(conn.getOutputStream());

                    dos.writeBytes(twoHypens + boundary + lineEnd);
                    dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file[]\";filename=\"" + fileName+"\""+lineEnd);
                    //dos.writeBytes("Content-Disposition: form-data; name=\"uid\";filename=\"" + "rabin"+"\""+lineEnd);
                    dos.writeBytes(lineEnd);

                    // create a buffer of maximum size
                    bytesAvailable = fileInputStream.available();

                    bufferSize = Math.min(bytesAvailable, maxBufferSize);
                    buffer = new byte[bufferSize];

                    // read file and write it into form
                    bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                    while(bytesRead>0){
                        dos.write(buffer, 0, bufferSize);
                        bytesAvailable = fileInputStream.available();
                        bufferSize = Math.min(bytesAvailable, maxBufferSize);
                        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                    }
                    //dos.writeBytes(lineEnd);
                    dos.writeBytes(twoHypens + boundary + lineEnd);
                    dos.writeBytes("Content-Disposition: form-data; name=\"uid\";value=\"" + "rabin shrestha" +"\""+lineEnd);
                    dos.writeBytes("Content-Type: text/plain; charset=US-ASCII" + lineEnd);
                    dos.writeBytes("Content-Transfer-Encoding: 8bit" + lineEnd);

                    dos.writeBytes(lineEnd);
                }
                // send multipart form data necessary after file data
                dos.writeBytes(twoHypens+boundary+twoHypens+lineEnd);

                // Responses from the server(code and message)
                serverResponseCode = conn.getResponseCode();
                String serverResponseMessage = conn.getResponseMessage();

                Log.i("uploadFile","HTTP Response is : "
                        + serverResponseMessage + ": " + serverResponseCode);
                if(serverResponseCode == 200){ //if http response is created
                    getActivity().runOnUiThread(new Runnable(){
                        public void run(){
                            String msg = "File Upload Completed.";
                            //tvMulMsg.setText(msg);
                            Toast toast = Toast.makeText(context, msg, Toast.LENGTH_SHORT);
                            toast.show();

                        }
                    });
                }
                //close the streams //
                fileInputStream.close();
                dos.flush();
                dos.close();
            }
            catch (MalformedURLException ex) {

                dialog.dismiss();
                ex.printStackTrace();

                getActivity().runOnUiThread(new Runnable() {
                    public void run() {
                        tvMulMsg.setText("MalformedURLException Exception : check script url.");
                        //Toast.makeText(Gallery.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
                    }
                });

                Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
            } catch (Exception e) {

                dialog.dismiss();
                e.printStackTrace();

                getActivity().runOnUiThread(new Runnable() {
                    public void run() {
                        tvMulMsg.setText("Got Exception with server");
                        //Toast.makeText(context, "Got Exception with server ", Toast.LENGTH_SHORT).show();
                    }
                });
                Log.e("Upload file to server Exception", "Exception : "  + e.getMessage(), e);
            }
            dialog.dismiss();
        return serverResponseCode;
    }

    public boolean _ifIsFile(File file){
        if(!file.isFile()){
            dialog.dismiss();

            Log.e("uploadFile", "Source File not exist : " + imgPath);

            getActivity().runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    tvMulMsg.setText("Source File not exist : " + imgPath);
                }
            });
            return false;
        }
        return true;
    }

}

and a Dashboard class like this:

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

    mTitle = mDrawerTitle = getTitle();
    mPlanetTitles = getResources().getStringArray(R.array.planets_array);
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerList = (ListView) findViewById(R.id.left_drawer);

    // set a custom shadow that overlays the main content when the drawer opens
    mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
    // set up the drawer's list view with items and click listener
    mDrawerList.setAdapter(new ArrayAdapter<String>(this,
            R.layout.drawer_list_item, mPlanetTitles));
    mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

    // enable ActionBar app icon to behave as action to toggle nav drawer
    getActionBar().setDisplayHomeAsUpEnabled(true);
    getActionBar().setHomeButtonEnabled(true);

    // ActionBarDrawerToggle ties together the the proper interactions
    // between the sliding drawer and the action bar app icon
    mDrawerToggle = new ActionBarDrawerToggle(
            this,                  /* host Activity */
            mDrawerLayout,         /* DrawerLayout object */
            R.drawable.ic_drawer,  /* nav drawer image to replace 'Up' caret */
            R.string.drawer_open,  /* "open drawer" description for accessibility */
            R.string.drawer_close  /* "close drawer" description for accessibility */
            ) {
        public void onDrawerClosed(View view) {
            getActionBar().setTitle(mTitle);
            invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
        }

        public void onDrawerOpened(View drawerView) {
            getActionBar().setTitle(mDrawerTitle);
            invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
        }
    };
    mDrawerLayout.setDrawerListener(mDrawerToggle);

    if (savedInstanceState == null) {
        selectItem(0);
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main, menu);
    return super.onCreateOptionsMenu(menu);
}

/* Called whenever we call invalidateOptionsMenu() */
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    // If the nav drawer is open, hide action items related to the content view
    boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
    menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
    return super.onPrepareOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
     // The action bar home/up action should open or close the drawer.
     // ActionBarDrawerToggle will take care of this.
    if (mDrawerToggle.onOptionsItemSelected(item)) {
        return true;
    }
    // Handle action buttons
    switch(item.getItemId()) {
    case R.id.action_websearch:
        // create intent to perform web search for this planet
        Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
        intent.putExtra(SearchManager.QUERY, getActionBar().getTitle());
        // catch event that there's no activity to handle intent
        if (intent.resolveActivity(getPackageManager()) != null) {
            startActivity(intent);
        } else {
            Toast.makeText(this, R.string.app_not_available, Toast.LENGTH_LONG).show();
        }
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

/* The click listner for ListView in the navigation drawer */
private class DrawerItemClickListener implements ListView.OnItemClickListener {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        selectItem(position);
    }
}

/** Swaps fragments in the main content view */
private void selectItem(int position) {


    Fragment fragment = null;

    switch(position){
        case 0:
            fragment = new MyGalleryFragment();
            break;
        case 1:
            fragment = new MyGalleryFragment();
            break;
        case 2:
            fragment = new MyGalleryFragment();
            break;
        case 3:
            fragment = new MyGalleryFragment();
            break;
        case 4:
            fragment = new MyGalleryFragment();
            break;
        case 5:
            fragment = new PlanetFragment();
            break;
        case 6:
            fragment = new PlanetFragment();
            break;
        case 7:
            fragment = new PlanetFragment();
            break;
        case 8:
            fragment = new PlanetFragment();
            break;
        case 9:
            fragment = new PlanetFragment();
            break;
        case 10:
            fragment = new PlanetFragment();
            break;
        case 11:
            fragment = new PlanetFragment();
            break;
        case 12:
            fragment = new PlanetFragment();
            break;

        default:
            break;
    }

    if(position>=5){
        Bundle args = new Bundle();
        args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
        fragment.setArguments(args);
        if(fragment != null){
            FragmentManager fragmentManager = getFragmentManager();
            fragmentManager.beginTransaction()
                            .replace(R.id.content_frame, fragment)
                            .commit();

            mDrawerList.setItemChecked(position, true);
            mDrawerList.setSelection(position);
            setTitle(mPlanetTitles[position]);
            mDrawerLayout.closeDrawer(mDrawerList);
        }
    }else{
        Intent i = new Intent(Dashboard.this, MyGallery.class);
        startActivity(i);
    }



    Toast.makeText(getApplicationContext(), Integer.toString(position), Toast.LENGTH_LONG).show();

}

@Override
public void setTitle(CharSequence title) {
    mTitle = title;
    getActionBar().setTitle(mTitle);
}

/**
 * When using the ActionBarDrawerToggle, you must call it during
 * onPostCreate() and onConfigurationChanged()...
 */

@Override
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    // Sync the toggle state after onRestoreInstanceState has occurred.
    mDrawerToggle.syncState();
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    // Pass any configuration change to the drawer toggles
    mDrawerToggle.onConfigurationChanged(newConfig);
}

/**
 * Fragment that appears in the "content_frame", shows a planet
 */
public static class PlanetFragment extends Fragment {
    public static final String ARG_PLANET_NUMBER = "planet_number";

    public PlanetFragment() {
        // Empty constructor required for fragment subclasses
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_planet, container, false);
        int i = getArguments().getInt(ARG_PLANET_NUMBER);
        String planet = getResources().getStringArray(R.array.planets_array)[i];

        int imageId = getResources().getIdentifier(planet.toLowerCase(Locale.getDefault()),
                        "drawable", getActivity().getPackageName());
        ((ImageView) rootView.findViewById(R.id.image)).setImageResource(imageId);
        getActivity().setTitle(planet);
        return rootView;
    }
}

also I have a repo on git you can fork that here.

I managed to get fragments and is able to display the images from the mobile gallery but now when i tried to upload the images it throws errors

Stack Trace:

03-21 04:06:19.033: E/AndroidRuntime(2620): FATAL EXCEPTION: main
03-21 04:06:19.033: E/AndroidRuntime(2620): Process: jsoft.projects.photoprint_v1_1, PID: 2620
03-21 04:06:19.033: E/AndroidRuntime(2620): java.lang.IllegalStateException: Could not find a method btnChoosePhotosClick(View) in the activity class jsoft.projects.photoprint_v1_1.Dashboard for onClick handler on view class android.widget.Button with id 'button1'
03-21 04:06:19.033: E/AndroidRuntime(2620):     at android.view.View$1.onClick(View.java:3810)
03-21 04:06:19.033: E/AndroidRuntime(2620):     at android.view.View.performClick(View.java:4438)
03-21 04:06:19.033: E/AndroidRuntime(2620):     at android.view.View$PerformClick.run(View.java:18422)
03-21 04:06:19.033: E/AndroidRuntime(2620):     at android.os.Handler.handleCallback(Handler.java:733)
03-21 04:06:19.033: E/AndroidRuntime(2620):     at android.os.Handler.dispatchMessage(Handler.java:95)
03-21 04:06:19.033: E/AndroidRuntime(2620):     at android.os.Looper.loop(Looper.java:136)
03-21 04:06:19.033: E/AndroidRuntime(2620):     at android.app.ActivityThread.main(ActivityThread.java:5017)
03-21 04:06:19.033: E/AndroidRuntime(2620):     at java.lang.reflect.Method.invokeNative(Native Method)
03-21 04:06:19.033: E/AndroidRuntime(2620):     at java.lang.reflect.Method.invoke(Method.java:515)
03-21 04:06:19.033: E/AndroidRuntime(2620):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
03-21 04:06:19.033: E/AndroidRuntime(2620):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
03-21 04:06:19.033: E/AndroidRuntime(2620):     at dalvik.system.NativeStart.main(Native Method)
03-21 04:06:19.033: E/AndroidRuntime(2620): Caused by: java.lang.NoSuchMethodException: btnChoosePhotosClick [class android.view.View]
03-21 04:06:19.033: E/AndroidRuntime(2620):     at java.lang.Class.getConstructorOrMethod(Class.java:472)
03-21 04:06:19.033: E/AndroidRuntime(2620):     at java.lang.Class.getMethod(Class.java:857)
03-21 04:06:19.033: E/AndroidRuntime(2620):     at android.view.View$1.onClick(View.java:3803)
03-21 04:06:19.033: E/AndroidRuntime(2620):     ... 11 more

I want to upload the images and btnChoosePhotosClick method is called when Upload Selected button is clicked. btnChoosePhotosClick method is there in MyGalleryFragment class but it seeks from next activity i.e Dashboard. You can view the files in github.

if you had downloaded the project than the username : password for the app is test:test

I am new to Android and also fragment is very new to me.

Please Help

解决方案
Could not find a method btnChoosePhotosClick(View) in the activity class jsoft.projects.photoprint_v1_1.Dashboard for onClick handler on view class android.widget.Button with id 'button1'

You have to create the method btnChoosePhotosClick(View) in Dashboard.java. I don't like call methods from layout, I prefer do something like that:

Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
    btnChoosePhotosClick(v);
}
});

这篇关于安卓:使用片段和导航抽屉上传图片到服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 18:41