0

我是android的新手。今天我尝试了以下示例,但我无法继续进行。因为我在使用 nexus 5 时遇到以下错误。

错误 :

06-12 14:52:01.348  20269-20269/com.example.imageuploader.app E/BitmapFactory﹕ Unable to decode stream: java.lang.NullPointerException

我在这个程序中遇到的任何问题。请建议

示例程序

package com.example.imageuploader.app;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends Activity implements OnClickListener{

    private TextView messageText;
    private Button uploadButton, btnselectpic;
    private ImageView imageview;
    private int serverResponseCode = 0;
    private ProgressDialog dialog = null;

    private String upLoadServerUri = null;
    private String imagepath=null;
    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        uploadButton = (Button)findViewById(R.id.uploadButton);
        messageText  = (TextView)findViewById(R.id.messageText);
        btnselectpic = (Button)findViewById(R.id.button_selectpic);
        imageview = (ImageView)findViewById(R.id.imageView_pic);

        btnselectpic.setOnClickListener(this);
        uploadButton.setOnClickListener(this);
        upLoadServerUri = "http://192.168.0.15/UploadToServer.php";
    }


    @Override
    public void onClick(View arg0) {
        if(arg0==btnselectpic)
        {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Complete action using"), 1);
        }
        else if (arg0==uploadButton) {

            dialog = ProgressDialog.show(MainActivity.this, "", "Uploading file...", true);
            messageText.setText("uploading started.....");
            new Thread(new Runnable() {
                public void run() {

                    uploadFile(imagepath);

                }
            }).start();
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == 1 && resultCode == RESULT_OK) {
            //Bitmap photo = (Bitmap) data.getData().getPath();

            Uri selectedImageUri = data.getData();
            imagepath = getPath(selectedImageUri);
            Bitmap bitmap=BitmapFactory.decodeFile(imagepath);
            imageview.setImageBitmap(bitmap);
            messageText.setText("Uploading file path:" +imagepath);

        }
    }
    public String getPath(Uri uri) {
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(uri, new String[] { android.provider.MediaStore.Images.ImageColumns.DATA }, null, null, null);
        cursor.moveToFirst();
        return cursor.getString(0);
    }

    public int uploadFile(String sourceFileUri) {


        String fileName = sourceFileUri;

        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;
        File sourceFile = new File(sourceFileUri);

        if (!sourceFile.isFile()) {

            dialog.dismiss();

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

            runOnUiThread(new Runnable() {
                public void run() {
                    messageText.setText("Source File not exist :"+ imagepath);
                }
            });

            return 0;

        }
        else
        {
            try {

                // open a URL connection to the Servlet
                FileInputStream fileInputStream = new FileInputStream(sourceFile);
                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");
                conn.setRequestProperty("Connection", "Keep-Alive");
                conn.setRequestProperty("ENCTYPE", "multipart/form-data");
                conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
                conn.setRequestProperty("uploaded_file", fileName);

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

                dos.writeBytes(twoHyphens + boundary + lineEnd);
                dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
                        + fileName + "\"" + 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);

                }

                // send multipart form data necesssary after file data...
                dos.writeBytes(lineEnd);
                dos.writeBytes(twoHyphens + boundary + twoHyphens + 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){

                    runOnUiThread(new Runnable() {
                        public void run() {
                            String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
                                    +" F:/wamp/wamp/www/uploads";
                            messageText.setText(msg);
                            Toast.makeText(MainActivity.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
                        }
                    });
                }

                //close the streams //
                fileInputStream.close();
                dos.flush();
                dos.close();

            } catch (MalformedURLException ex) {

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

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

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

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

                runOnUiThread(new Runnable() {
                    public void run() {
                        messageText.setText("Got Exception : see logcat ");
                        Toast.makeText(MainActivity.this, "Got Exception : see logcat ", Toast.LENGTH_SHORT).show();
                    }
                });
                Log.e("Upload file to server Exception", "Exception : "  + e.getMessage(), e);
            }
            dialog.dismiss();
            return serverResponseCode;

        } // End else block
    }


}

日志错误:

06-12 15:20:53.138  25602-25602/com.example.imageuploader.app D/AndroidRuntime﹕ Shutting down VM
    06-12 15:20:53.138  25602-25602/com.example.imageuploader.app W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41596ba8)
    06-12 15:20:53.148  25602-25602/com.example.imageuploader.app E/AndroidRuntime﹕ FATAL EXCEPTION: main
        Process: com.example.imageuploader.app, PID: 25602
        java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { dat=content://com.google.android.apps.docs.storage/document/acc=1;doc=677 flg=0x1 }} to activity {com.example.imageuploader.app/com.example.imageuploader.app.MainActivity}: java.lang.IllegalArgumentException: Unknown column requested: _data
                at android.app.ActivityThread.deliverResults(ActivityThread.java:3351)
                at android.app.ActivityThread.handleSendResult(ActivityThread.java:3394)
                at android.app.ActivityThread.access$1300(ActivityThread.java:135)
                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1244)
                at android.os.Handler.dispatchMessage(Handler.java:102)
                at android.os.Looper.loop(Looper.java:136)
                at android.app.ActivityThread.main(ActivityThread.java:5001)
                at java.lang.reflect.Method.invokeNative(Native Method)
                at java.lang.reflect.Method.invoke(Method.java:515)
                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
                at dalvik.system.NativeStart.main(Native Method)
         Caused by: java.lang.IllegalArgumentException: Unknown column requested: _data
                at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:167)
                at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:137)
                at android.content.ContentProviderProxy.query(ContentProviderNative.java:413)
                at android.content.ContentResolver.query(ContentResolver.java:461)
                at android.content.ContentResolver.query(ContentResolver.java:404)
                at com.example.imageuploader.app.MainActivity.getPath(MainActivity.java:93)
                at com.example.imageuploader.app.MainActivity.onActivityResult(MainActivity.java:84)
                at android.app.Activity.dispatchActivityResult(Activity.java:5423)
                at android.app.ActivityThread.deliverResults(ActivityThread.java:3347)
                at android.app.ActivityThread.handleSendResult(ActivityThread.java:3394)
                at android.app.ActivityThread.access$1300(ActivityThread.java:135)
                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1244)
                at android.os.Handler.dispatchMessage(Handler.java:102)
                at android.os.Looper.loop(Looper.java:136)
                at android.app.ActivityThread.main(ActivityThread.java:5001)
                at java.lang.reflect.Method.invokeNative(Native Method)
                at java.lang.reflect.Method.invoke(Method.java:515)
                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
                at dalvik.system.NativeStart.main(Native Method)
4

2 回答 2

1

在 onActivityResult 方法中使用以下代码

Uri selectedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = getContentResolver().query(selectedImage, filePath,
                    null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
imageFile = new File(c.getString(columnIndex));
imagePath = imageFile.getAbsolutePath();
c.close();
imageData = (BitmapFactory.decodeFile(imagePath));

而不是这个

       //Bitmap photo = (Bitmap) data.getData().getPath();

        Uri selectedImageUri = data.getData();
        imagepath = getPath(selectedImageUri);
        Bitmap bitmap=BitmapFactory.decodeFile(imagepath);
        imageview.setImageBitmap(bitmap);
        messageText.setText("Uploading file path:" +imagepath);
于 2014-06-12T10:15:54.997 回答
0

我已经使用多部分实体上传图片这里是代码。uploadFile 是图片的路径

public String reportCrime(String uploadFile, int userid, int crimetype,
        String crimedetails, String lat, String longi, String reporteddate) {
    String url;
    MultipartEntity entity;
    try {
        url = String.format(Constant.SERVER_URL
                + "push_notification/reportCrime.php");

        entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        //
        File file = new File(uploadFile);
        if (!file.equals("Image not Provided.")) {
            if (file.exists()) {

                Bitmap bmp = BitmapFactory.decodeFile(uploadFile);
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                bmp.compress(CompressFormat.JPEG, 70, bos);
                InputStream in = new ByteArrayInputStream(bos.toByteArray());
                ContentBody foto = new InputStreamBody(in, "image/jpeg", uploadFile);
                entity.addPart("image", foto);
            }
        } else {
            FormBodyPart image = new FormBodyPart("image", new StringBody(
                    ""));
            entity.addPart(image);
        }

        FormBodyPart userId = new FormBodyPart("userId", new StringBody(
                String.valueOf(userid)));
        entity.addPart(userId);

        FormBodyPart crimeType = new FormBodyPart("crimetype",
                new StringBody(String.valueOf(crimetype)));
        entity.addPart(crimeType);

        FormBodyPart crimeDetails = new FormBodyPart("crimedetail",
                new StringBody(crimedetails));
        entity.addPart(crimeDetails);

        FormBodyPart latittude = new FormBodyPart("latittude",
                new StringBody(lat));
        entity.addPart(latittude);

        FormBodyPart longitude = new FormBodyPart("longitude",
                new StringBody(longi));
        entity.addPart(longitude);

        FormBodyPart reportedDate = new FormBodyPart("reporteddatetime",
                new StringBody(reporteddate));
        entity.addPart(reportedDate);

    } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace();
        return "error";
    }

    HttpParams httpParams = new BasicHttpParams();

    HttpContext httpContext = new BasicHttpContext();
    HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
    HttpConnectionParams.setSoTimeout(httpParams, 10000);

    try {
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(entity);
        client = new DefaultHttpClient();
        HttpResponse response = client.execute(httpPost);
        BufferedReader in = null;
        try {
            in = new BufferedReader(new InputStreamReader(response
                    .getEntity().getContent()));
            StringBuffer sb = new StringBuffer();
            String line = null;
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }

            result = sb.toString();
        } finally {
            if (in != null)
                in.close();
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return result;
}
于 2014-06-13T11:18:22.727 回答