简体   繁体   中英

Selecting an image from a gallery and uploading to a server via API using httpPost

I am working on an android app where I need to select the image from gallery and upload it to the server. I have the URI and able to get the actual path of the image file using getRealPathFromURI. The problem starts when I have to upload it to the API using httpPost (I need to pass some parameters too). I keep getting nullpointerException. I have gone through various posts but cant seem to figure out the problem. Following is my code

@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;

And here is my code to get the actual path

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

Following is the Log:

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

You have to put the http code in a thread or asynctask. You need INTERNET permission in your manifest file. Why are creating an intent and starting an activity also?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM