java.lang.RuntimeException:将图像上传到服务器时无法恢复活动

时间:2015-04-21 04:35:52

标签: android file-upload

处理示例图片上传任务。遇到错误请告诉我你的看法

Java文件

 package com.imageupload;

import android.app.Activity;
import java.io.FileInputStream;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;


public class MainActivity extends Activity {

    Button button;

    Uri currImageURI;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       button = (Button) this.findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent, "Select Picture"),1);

            }
        });

    }
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == 1) {
                // currImageURI is the global variable I’m using to hold the content:
                currImageURI = data.getData();
                System.out.println("Current image Path is ----->" +getRealPathFromURI(currImageURI));
               TextView tv_path = (TextView) findViewById(R.id.path);
                tv_path.setText(getRealPathFromURI(currImageURI));

                doFileUpload();
            }

        }
    }

    //Convert the image URI to the direct file system path of the image file
    public String getRealPathFromURI(Uri contentUri) {
        String [] proj={MediaStore.Images.Media.DATA};
        android.database.Cursor cursor = managedQuery( contentUri,
                proj,     // Which columns to return
                null,     // WHERE clause; which rows to return (all rows)
                null,     // WHERE clause selection arguments (none)
                null);     // Order-by clause (ascending by name)
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }

    private void doFileUpload(){
        HttpURLConnection conn =    null;
        DataOutputStream dos = null;
        DataInputStream inStream = null;
        String exsistingFileName = currImageURI.toString();

// Is this the place are you doing something wrong.
        String lineEnd = "rn";
        String twoHyphens = "--";
        String boundary =  "*****";

        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1*1024*1024;
        String responseFromServer = "";
        String urlString = "http://nstwebbeta.com/wolftrax/api/?section=inventory&action=image";

        try
        {
            //------------------ CLIENT REQUEST
            Log.e("MediaPlayer","Inside second Method");
            FileInputStream fileInputStream = new FileInputStream(new    File(exsistingFileName) );

            // open a URL connection to the Servlet
            URL url = new URL(urlString);

            // Open a HTTP connection to the URL
            conn = (HttpURLConnection) url.openConnection();

            // Allow Inputs
            conn.setDoInput(true);

            // Allow Outputs
            conn.setDoOutput(true);

            // Don't use a cached copy.
            conn.setUseCaches(false);

            // Use a post method.
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);

            dos = new DataOutputStream( conn.getOutputStream() );
            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
                    + exsistingFileName + "\"" + lineEnd);
            dos.writeBytes(lineEnd);
            Log.e("MediaPlayer","Headers are written");

            // 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);
            }

            // send multipart form data necesssary after file data...
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

            // close streams
            Log.e("MediaPlayer","File is written");
            fileInputStream.close();
            dos.flush();
            dos.close();

        }

        catch (MalformedURLException ex)

        {
            Log.e("MediaPlayer", "error: " + ex.getMessage(), ex);
        }



        catch (IOException ioe)
        {
            Log.e("MediaPlayer", "error: " + ioe.getMessage(), ioe);
        }

        //------------------ read the SERVER RESPONSE
        try {
            inStream = new DataInputStream ( conn.getInputStream() );
            String str;

            while (( str = inStream.readLine()) != null)
            {
                Log.e("MediaPlayer","Server Response"+str);
            }

            inStream.close();
        }

        catch (IOException ioex){
            Log.e("MediaPlayer", "error: " + ioex.getMessage(), ioex);
        }

    }
}

清单文件

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

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-feature android:name="android.hardware.camera" />
    <uses-feature android:name="android.hardware.camera.autofocus" />

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

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

LOG

 FATAL EXCEPTION: main
    java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { dat=content://media/external/images/media/2795 (has extras) }} to activity {com.imageupload/com.imageupload.MainActivity}: java.lang.NullPointerException
            at android.app.ActivityThread.deliverResults(ActivityThread.java:3179)
            at android.app.ActivityThread.handleSendResult(ActivityThread.java:3222)
            at android.app.ActivityThread.access$1100(ActivityThread.java:140)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1276)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4895)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:994)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:761)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.NullPointerException
            at com.imageupload.MainActivity.doFileUpload(MainActivity.java:167)
            at com.imageupload.MainActivity.onActivityResult(MainActivity.java:56)
            at android.app.Activity.dispatchActivityResult(Activity.java:5347)
            at android.app.ActivityThread.deliverResults(ActivityThread.java:3175)
            at android.app.ActivityThread.handleSendResult(ActivityThread.java:3222)
            at android.app.ActivityThread.access$1100(ActivityThread.java:140)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1276)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4895)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:994)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:761)
            at dalvik.system.NativeStart.main(Native Method)

第#167行是inStream = new DataInputStream(conn.getInputStream()); 第56行是doFileUpload();

2 个答案:

答案 0 :(得分:1)

更改  String exsistingFileName = currImageURI.toString();

String exsistingFileName = getRealPathFromURI(currImageURI);

答案 1 :(得分:0)

你不应该在UI线程上下载一些东西。试着阅读有关AsyncTask http://developer.android.com/reference/android/os/AsyncTask.html的内容。在您的情况下UploadFilesTask

     private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
 protected Long doInBackground(URL... urls) {
     int count = urls.length;
     long totalSize = 0;
     for (int i = 0; i < count; i++) {
         totalSize += Downloader.downloadFile(urls[i]);
         publishProgress((int) ((i / (float) count) * 100));
         // Escape early if cancel() is called
         if (isCancelled()) break;
     }
     return totalSize;
 }

 protected void onProgressUpdate(Integer... progress) {
     setProgressPercent(progress[0]);
 }

 protected void onPostExecute(Long result) {
     showDialog("Downloaded " + result + " bytes");
 }
 }