java.lang.RuntimeException:传递结果失败ResultInfo {who = null,request = 2,result = -1,data = Intent

时间:2014-10-28 13:06:21

标签: java android android-intent

Activity

    package com.bpd.lemongroupchat.tabactivities.subactivity;


import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;

import com.bpd.lemongroupchat.R;
import com.bpd.lemongroupchat.utils.DialogUtils;
import com.bpd.lemongroupchat.utils.GraphicsUtil;
import com.bpd.lemongroupchat.utils.ImageHelper;
import com.quickblox.chat.QBChatService;
import com.quickblox.chat.model.QBDialog;
import com.quickblox.chat.model.QBDialogType;
import com.quickblox.core.QBEntityCallbackImpl;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class CreateOrUpdateGroupActivity extends Activity implements OnClickListener
{

    Button createBtn;
    ImageView groupImageIcon;   
    SharedPreferences sp;
    String user="";
    ImageView groupImage;
    TextView inviteUser,groupCode;
    EditText firstNameEdit;

    //Spinner ageSpinner;
    private static final int PICK_FROM_CAMERA = 1;
    private static final int PICK_FROM_GALLERY = 2;

    /************QuickBlox*************/
    Bitmap imgBitmap=null;
    String firstNameEditStr="",imagePath="";
    protected ProgressDialog progressDialog;
    ImageHelper imageHelper ;
    private Bitmap photo=null;

    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        //requestWindowFeature(Window.FEATURE_NO_TITLE);

        setContentView(R.layout.create_update_group_screen);

        sp=this.getSharedPreferences("lemon_messenger", MODE_WORLD_READABLE);
        user=sp.getString("CREATE_UPDATE", user);

        Log.d("Profile", "1");

        // set circle bitmap
        groupImage          =   (ImageView) findViewById(R.id.groupPic);
        groupImageIcon      =   (ImageView) findViewById(R.id.groupImgIcon);
        createBtn           =   (Button) findViewById(R.id.createBtn);
        inviteUser          =   (TextView) findViewById(R.id.inviteUser);
        groupCode           =   (TextView) findViewById(R.id.groupCode);
        firstNameEdit       =   (EditText) findViewById(R.id.firstNameEdit);

        progressDialog = DialogUtils.getProgressDialog(this);        
        progressDialog.setMessage("Please wait...");

        if(user.trim().equals("1"))
        {
            groupCode.setVisibility(View.VISIBLE);
            createBtn.setText("Update");
        }
        else
        {
            groupCode.setVisibility(View.GONE);
            createBtn.setText("Create");
        }

        createBtn.setOnClickListener(this);

        groupImageIcon.setOnClickListener(this);

    }   

    @Override   
    public void onClick(View v)
    {
        switch(v.getId())
        {
            case R.id.createBtn: 
                                firstNameEditStr    =   firstNameEdit.getText().toString().trim();
                                if(user.trim().equals("1"))
                                {
                                    Toast.makeText(getApplicationContext(), "Gorup Successfully Updated", Toast.LENGTH_LONG).show();
                                }
                                else
                                {   
                        //          if(imgBitmap!=null)                     
                        //          {
                                        if(!firstNameEditStr.trim().equalsIgnoreCase(""))
                                        {   
                                            progressDialog.show();
                                            createGroupChatMethod();
                                        }
                                        else
                                        {
                                            Toast.makeText(getApplicationContext(), "Please select a group name", Toast.LENGTH_LONG).show();
                                        }
                        //          }
                        //          else
                        //          {
                        //              Toast.makeText(getApplicationContext(), "Please choose a group photo first", Toast.LENGTH_LONG).show();
                        //          }                   
                                }
                                break;
            case R.id.groupImgIcon:
                                selectImage();
                                break;
        }
    }
      protected void createGroupChatMethod() 
      {
          // code will be here
      }


      private void selectImage() {

            final CharSequence[] options = { "Take Photo from Camera", "Choose from Gallery","Cancel" };

            AlertDialog.Builder builder = new AlertDialog.Builder(CreateOrUpdateGroupActivity.this);
            builder.setTitle("Add Photo!");
            builder.setItems(options, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int item) {
                    if (options[item].equals("Take Photo from Camera"))
                    {
                        // call android default camera
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                        intent.putExtra(MediaStore.EXTRA_OUTPUT,
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI.toString());
                        // ******** code for crop image
//                      intent.putExtra("crop", "true");
//                      intent.putExtra("aspectX", 1);
//                      intent.putExtra("aspectY", 1);
//                      intent.putExtra("outputX", 120);
//                      intent.putExtra("outputY", 120);

                        try {

                            intent.putExtra("return-data", true);
                            startActivityForResult(intent, PICK_FROM_CAMERA);

                        } catch (ActivityNotFoundException e) {
                        // Do nothing for now
                        }
                    }
                    else if (options[item].equals("Choose from Gallery"))
                    {
//                      Intent intent = new Intent();
//                      // call android default gallery
//                      intent.setType("image/*");
//                      intent.setAction(Intent.ACTION_GET_CONTENT);
//                      // ******** code for crop image
//                      intent.putExtra("crop", "true");
//                      intent.putExtra("aspectX", 1);
//                      intent.putExtra("aspectY", 1);
//                      intent.putExtra("outputX", 120);
//                      intent.putExtra("outputY", 120);
//
//                      try {
//
//                      intent.putExtra("return-data", true);
//                      startActivityForResult(Intent.createChooser(intent,
//                      "Complete action using"), PICK_FROM_GALLERY);
//
//                      } catch (ActivityNotFoundException e) {
//                      // Do nothing for now
//                      }
                        // GET IMAGE FROM THE GALLERY
//                      Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
//                      intent.setType("image/*");
//
//                      Intent chooser = Intent.createChooser(intent, "Choose a Picture");
//                      startActivityForResult(chooser, PICK_FROM_GALLERY);

                        Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        startActivityForResult(i, PICK_FROM_GALLERY);
                    }
                    else if (options[item].equals("Cancel")) {
                        dialog.dismiss();
                    }
                }
            });
            builder.show();
        }

        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) 
        {    
            if(resultCode == RESULT_OK){
                System.out.println("Data: " +  data.getStringExtra("path"));
            if(!data.getStringExtra("path").trim().equals(null))
            {
            System.out.println("Data: " +  data.getStringExtra("path"));
            if (requestCode == PICK_FROM_CAMERA) {
                if (data != null) {
                    Bitmap photo1 = (Bitmap) data.getExtras().get("data"); 

                    // CALL THIS METHOD TO GET THE URI FROM THE BITMAP
                    Uri tempUri = getImageUri(getApplicationContext(), photo1);

                    // CALL THIS METHOD TO GET THE ACTUAL PATH
                    String pathCam= getRealPathFromURI(tempUri);

                    try {
                        photo = imageHelper.getScaledBitmap(pathCam);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    if(photo != null){
                        GraphicsUtil graphicUtil = new GraphicsUtil();
                        groupImage.setImageBitmap(graphicUtil.getCircleBitmap(photo, 150));     

                    }                   
                }
            }

            if (requestCode == PICK_FROM_GALLERY) {
                if (data != null) {

                     Uri selectedImage = data.getData();
                        String[] filePathColumn = { MediaStore.Images.Media.DATA };
                        Cursor cursor = getContentResolver().query(selectedImage,
                                filePathColumn, null, null, null);
                        cursor.moveToFirst();
                        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                        String path = cursor.getString(columnIndex);
                        cursor.close();

                    try {
                        photo = imageHelper.getScaledBitmap(path);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    if(photo != null){
                        GraphicsUtil graphicUtil = new GraphicsUtil();
                        groupImage.setImageBitmap(graphicUtil.getCircleBitmap(photo, 150)); 

                    }
                }
            }
            }
            else
            {
                System.out.println("Null Data: " +  data.getStringExtra("path"));
            }
            }
        } 

        public Uri getImageUri(Context inContext, Bitmap inImage) {
             ByteArrayOutputStream bytes = new ByteArrayOutputStream();
             inImage.compress(Bitmap.CompressFormat.PNG, 100, bytes);
             String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
             return Uri.parse(path);
        }

        public String getRealPathFromURI(Uri uri) {
             Cursor cursor = getContentResolver().query(uri, null, null, null, null); 
             cursor.moveToFirst(); 
             int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); 
             return cursor.getString(idx); 
        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.menu_back, menu);
            return true;
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            int id = item.getItemId();
            if (id == R.id.back_btn) {

              finish();
                return true;
            }
            return super.onOptionsItemSelected(item);
        }
}

Log Cat错误:

    10-28 18:31:36.360: W/IInputConnectionWrapper(17544): showStatusIcon on inactive InputConnection
10-28 18:31:39.205: I/System.out(17544): Data: null
10-28 18:31:39.205: D/AndroidRuntime(17544): Shutting down VM
10-28 18:31:39.205: W/dalvikvm(17544): threadid=1: thread exiting with uncaught exception (group=0x41972700)
10-28 18:31:39.220: E/AndroidRuntime(17544): FATAL EXCEPTION: main
10-28 18:31:39.220: E/AndroidRuntime(17544): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=2, result=-1, data=Intent { dat=content://media/external/images/media/72092 (has extras) }} to activity {com.bpd.lemongroupchat/com.bpd.lemongroupchat.tabactivities.subactivity.CreateOrUpdateGroupActivity}: java.lang.NullPointerException
10-28 18:31:39.220: E/AndroidRuntime(17544):    at android.app.ActivityThread.deliverResults(ActivityThread.java:3500)
10-28 18:31:39.220: E/AndroidRuntime(17544):    at android.app.ActivityThread.handleSendResult(ActivityThread.java:3543)
10-28 18:31:39.220: E/AndroidRuntime(17544):    at android.app.ActivityThread.access$1200(ActivityThread.java:159)
10-28 18:31:39.220: E/AndroidRuntime(17544):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364)
10-28 18:31:39.220: E/AndroidRuntime(17544):    at android.os.Handler.dispatchMessage(Handler.java:99)
10-28 18:31:39.220: E/AndroidRuntime(17544):    at android.os.Looper.loop(Looper.java:176)
10-28 18:31:39.220: E/AndroidRuntime(17544):    at android.app.ActivityThread.main(ActivityThread.java:5419)
10-28 18:31:39.220: E/AndroidRuntime(17544):    at java.lang.reflect.Method.invokeNative(Native Method)
10-28 18:31:39.220: E/AndroidRuntime(17544):    at java.lang.reflect.Method.invoke(Method.java:525)
10-28 18:31:39.220: E/AndroidRuntime(17544):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
10-28 18:31:39.220: E/AndroidRuntime(17544):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
10-28 18:31:39.220: E/AndroidRuntime(17544):    at dalvik.system.NativeStart.main(Native Method)
10-28 18:31:39.220: E/AndroidRuntime(17544): Caused by: java.lang.NullPointerException
10-28 18:31:39.220: E/AndroidRuntime(17544):    at com.bpd.lemongroupchat.tabactivities.subactivity.CreateOrUpdateGroupActivity.onActivityResult(CreateOrUpdateGroupActivity.java:244)
10-28 18:31:39.220: E/AndroidRuntime(17544):    at android.app.Activity.dispatchActivityResult(Activity.java:5563)
10-28 18:31:39.220: E/AndroidRuntime(17544):    at android.app.ActivityThread.deliverResults(ActivityThread.java:3496)
10-28 18:31:39.220: E/AndroidRuntime(17544):    ... 11 more

错误是如何发生的?但是相同的代码适用于其他活动,但没有Menu

的概念

4 个答案:

答案 0 :(得分:1)

在对数据执行任何操作之前,应先检查。 确保请求代码与您发送的请求代码相等,并且结果代码等于ok,最后确保您的数据不为空

 (requestCode==what_you_assign&&data!=null&&resultCode== Activity.RESULT_OK)

答案 1 :(得分:0)

data.getStringExtra("path").trim().equals(null)

此行存在问题,您无法在trim()上调用null(或任何其他方法)..由于您的控制台显示

  

数据:null

这意味着data.getStringExtra("path")会返回null,所以你要做的事情基本上归结为null.trim(),它会抛出一个NPE。只需检查data.getStringExtra("path")是否在if语句中返回null(删除对trim的调用)。

解决方案:替换

if(!data.getStringExtra("path").trim().equals(null))

通过

if(data != null && data.getExtras("data")!=null)

整个onActivityResult方法会更好地重写:

  • 检查resultCode是否为RESULT_OK
  • 检查数据是否!= null
  • 启用requestCode
  • 在每个switch case中(你要处理的每个requestCode,请检查 如果数据包含您想要的数据
  • 使用数据

答案 2 :(得分:0)

您应首先确保数据不为空,然后data.getStringExtra("path")!=null。如果你试图确保它有文本,你可以在验证它不为空之后检查修剪过的字符串的长度。

答案 3 :(得分:0)

我是傻瓜。请检查我的代码,我只是错过了这一行

imageHelper = new ImageHelper(this);

ImageHelper是一个类,我忘了初具,因此它给了NPE。

感谢所有试图解决此问题的人。