0

我正在开发一个 android 应用程序,我需要从图库中选择图像并将其上传到服务器。我有 URI 并且能够使用 getRealPathFromURI 获取图像文件的实际路径。当我必须使用 httpPost 将其上传到 API 时,问题就开始了(我也需要传递一些参数)。我不断收到 nullpointerException。我浏览了各种帖子,但似乎无法找出问题所在。以下是我的代码

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



      if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
              case 1:

                  String action = "update_user_image";
                  HashMap<String, String> user = session.getUserDetails();       
                  String token = user.get(SessionManagement.KEY_TOKEN);


                  List<NameValuePair> params = new ArrayList<NameValuePair>();
                  params.add(new BasicNameValuePair("action", action));
                  String  device_identifier =   android.os.Build.ID; 



                  currImageURI = data.getData();
                  Intent intent = new Intent(this, ProfilePrivateActivity.class);
                  intent.putExtra("imageUri", currImageURI.toString());



                  String selectedImagePath = getRealPathFromURI(currImageURI).toString();

                  try {

                     HttpClient httpClient = new DefaultHttpClient();
                    HttpPost postRequest = new HttpPost(UPLOAD_URL);
                    postRequest.setEntity(new UrlEncodedFormEntity(params));
                    postRequest.addHeader(BasicScheme.authenticate(
                             new UsernamePasswordCredentials(device_identifier, token),"UTF-8", false));

                    bm = BitmapFactory.decodeFile(selectedImagePath);

                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    bm.compress(CompressFormat.JPEG, 20, bos);
                    byte[] data2 = bos.toByteArray();

                    ByteArrayBody bab = new ByteArrayBody(data2, selectedImagePath);
                    // File file= new File("/mnt/sdcard/forest.png");
                    // FileBody bin = new FileBody(file);
                    MultipartEntity reqEntity = new MultipartEntity(
                            HttpMultipartMode.BROWSER_COMPATIBLE);
                    reqEntity.addPart("uploaded", bab);
                    //reqEntity.addPart("photoCaption", new StringBody("sfsdfsdf"));
                    postRequest.setEntity(reqEntity);
                    HttpResponse response = httpClient.execute(postRequest);
                    BufferedReader reader = new BufferedReader(new InputStreamReader(
                            response.getEntity().getContent(), "UTF-8"));
                    String sResponse;
                    StringBuilder s = new StringBuilder();

                    while ((sResponse = reader.readLine()) != null) {
                        s = s.append(sResponse);
                    }
                    System.out.println("Response: " + s);







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


                  startActivity(intent);



                break;

这是我获取实际路径的代码

private Object getRealPathFromURI(Uri currImageURI2) {
        try
        {
            String[] proj = {MediaStore.Images.Media.DATA};
            Cursor cursor = managedQuery(currImageURI2, proj, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        }
        catch (Exception e)
        {
            return currImageURI2.getPath();
        }

以下是日志:

03-15 19:52:54.718: I/ResolverActivity(5574): mcc=234
03-15 19:52:56.428: D/CLIPBOARD(5574): Hide Clipboard dialog at Starting input: finished by someone else... !
03-15 19:52:58.578: D/AndroidRuntime(5574): Shutting down VM
03-15 19:52:58.578: W/dalvikvm(5574): threadid=1: thread exiting with uncaught exception (group=0x40c621f8)
03-15 19:52:58.583: E/AndroidRuntime(5574): FATAL EXCEPTION: main
03-15 19:52:58.583: E/AndroidRuntime(5574): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { dat=content:xxxxx (has extras) }} to activity {com.example.threesixty_android/com.example.threesixty_android.MyDialogBox}: java.lang.NullPointerException
03-15 19:52:58.583: E/AndroidRuntime(5574):     at android.app.ActivityThread.deliverResults(ActivityThread.java:2991)
03-15 19:52:58.583: E/AndroidRuntime(5574):     at android.app.ActivityThread.handleSendResult(ActivityThread.java:3034)
03-15 19:52:58.583: E/AndroidRuntime(5574):     at android.app.ActivityThread.access$1100(ActivityThread.java:127)
03-15 19:52:58.583: E/AndroidRuntime(5574):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1188)
03-15 19:52:58.583: E/AndroidRuntime(5574):     at android.os.Handler.dispatchMessage(Handler.java:99)
03-15 19:52:58.583: E/AndroidRuntime(5574):     at android.os.Looper.loop(Looper.java:137)
03-15 19:52:58.583: E/AndroidRuntime(5574):     at android.app.ActivityThread.main(ActivityThread.java:4511)
03-15 19:52:58.583: E/AndroidRuntime(5574):     at java.lang.reflect.Method.invokeNative(Native Method)
03-15 19:52:58.583: E/AndroidRuntime(5574):     at java.lang.reflect.Method.invoke(Method.java:511)
03-15 19:52:58.583: E/AndroidRuntime(5574):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:986)
03-15 19:52:58.583: E/AndroidRuntime(5574):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:753)
03-15 19:52:58.583: E/AndroidRuntime(5574):     at dalvik.system.NativeStart.main(Native Method)
03-15 19:52:58.583: E/AndroidRuntime(5574): Caused by: java.lang.NullPointerException
03-15 19:52:58.583: E/AndroidRuntime(5574):     at com.example.threesixty_android.MyDialogBox.onActivityResult(MyDialogBox.java:156)
03-15 19:52:58.583: E/AndroidRuntime(5574):     at android.app.Activity.dispatchActivityResult(Activity.java:4654)
03-15 19:52:58.583: E/AndroidRuntime(5574):     at android.app.ActivityThread.deliverResults(ActivityThread.java:2987)
03-15 19:52:58.583: E/AndroidRuntime(5574):     ... 11 more
4

1 回答 1

0

您必须将 http 代码放在线程或异步任务中。您的清单文件中需要 INTERNET 权限。为什么还要创建意图并开始活动?

于 2013-03-15T22:08:02.663 回答