onCreate 中的引用集在 onActivityResult 中为 null

Reference set in onCreate is null in onActivityResult

我有 activity 我添加了对象(自定义对象)并在 oncreate 中初始化它 方法:

 company=new HR_Company();

在activity开头我是这样写的:

HR_Company company;

当我尝试在这个对象中设置一个名称时

company.setHr_company_location("dfdfd");

它 return 我是公司对象为空的异常,这是怎么回事? 我尝试在 onActivityResult 方法中设置 这是代码

public class HR_DescriptionActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
public static final int CAMERA_REQUEST = 1;
public static final int GALLERY_REQUEST = 2;
HR_Company company;
EditText locationExitTxt;
EditText Company_name;
EditText desc;
TextView title;
ImageView viewImage;
Button up;
Button addPos;
Button save_hr_description;
ArrayList<Position> positions;
GoogleApiClient mGoogleApiClient;
GpsManger gps;
Bitmap cameraresized;
byte[] buffer=null;
ImageManager manager;
String[] permissions = new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION};
private ImageView imgphoto;

@Override
protected void onCreate(Bundle savedInstanceState) {
    gps=new GpsManger(HR_DescriptionActivity.this,mGoogleApiClient);
    super.onCreate(savedInstanceState);
    company=new HR_Company();
    setContentView(R.layout.activity_hr__description);

    //==================   get views  ===============
    Toolbar toolbar = (Toolbar) findViewById(R.id.hr_toolbar);
    imgphoto = (ImageView) findViewById(R.id.viewImage);
    viewImage=(ImageView)findViewById(R.id.viewImage);
    locationExitTxt = (EditText) findViewById(R.id.gps_company_location);
    Company_name=(EditText)findViewById(R.id.Company_name);
    desc=(EditText) findViewById(R.id.hr_description_desc);
    title=(TextView)findViewById(R.id.toolbar_title);
    addPos=(Button)findViewById(R.id.hr_add_position);
    save_hr_description=(Button)findViewById(R.id.save_hr_description);
    up = (Button) findViewById(R.id.upload);
    manager=new ImageManager(HR_DescriptionActivity.this,viewImage,company,Company_name,desc,locationExitTxt);
    //============================================




    //==================   toolbar configuration  ===============
    setSupportActionBar(toolbar);
    getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_clear_white_24dp);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayShowTitleEnabled(false);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    title.setText("Description");
    //============================================


    //==================   keyboard events  ===============
    locationExitTxt.addTextChangedListener(passwordWatcher);
    desc.addTextChangedListener(passwordWatcherfor3lines);
    Company_name.addTextChangedListener(passwordWatcher);








    if(ContextCompat.checkSelfPermission(HR_DescriptionActivity.this,Manifest.permission.CAMERA)!=PackageManager.PERMISSION_GRANTED)
    {
        ActivityCompat.requestPermissions(HR_DescriptionActivity.this,new String[]{Manifest.permission.CAMERA},0);
    }





    if (gps.hasPermission()) {

        gps.ConnectToGPS();
    }
    else
    {
        gps.requestPerms();
    }



    Company_name.setOnFocusChangeListener(new View.OnFocusChangeListener() {

        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if(hasFocus)
            {
                if (gps.hasPermission()) {

                    gps.ConnectToGPS();
                }
                else
                {
                    gps.requestPerms();
                }
            }
            if(!hasFocus)
            {
                gps.ConnectToGPS();

                locationExitTxt.setText(gps.getCity());
            }

        }
    });





    locationExitTxt.setOnFocusChangeListener(new View.OnFocusChangeListener() {

        @Override
        public void onFocusChange(View v, boolean hasFocus) {

                locationExitTxt.setText(gps.getCity());


        }
    });

    addPos.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {



            company=new HR_Company();


            company.setHr_company(Company_name.getText().toString());
            company.setHr_company_description(desc.getText().toString());
            company.setHr_company_location(desc.getText().toString());
            company.setHr_company_location(locationExitTxt.getText().toString());
            manager.LoadCompanyData(company);
            Intent i = new Intent(HR_DescriptionActivity.this, HR_Position_Activity.class);
            i.putExtra("HR_Company", company);
            startActivity(i);
            overridePendingTransition(R.anim.slide_in, R.anim.slide_out);

        }
    });


    save_hr_description.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

        }
    });


    up.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            selectImage();
        }
    });
    Intent i= getIntent();

    company= (HR_Company)i.getSerializableExtra("HR_Company");

    if(company!=null)
    {
        manager.LoadCompanyData(company);
    }






}

private final TextWatcher passwordWatcher = new TextWatcher() {
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if(s.toString().substring(start).contains("\n"))
        {
            View view=getCurrentFocus();
            InputMethodManager imm=(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(view.getWindowToken(),0);
        }
    }

    public void afterTextChanged(Editable s) {

    }
};
private final TextWatcher passwordWatcherfor3lines = new TextWatcher() {
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if(s.toString().substring(start).contains("\n")&& desc.getLineCount()>3)
        {
            View view=getCurrentFocus();
            InputMethodManager imm=(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(view.getWindowToken(),0);
        }
    }

    public void afterTextChanged(Editable s) {

    }
};

private void selectImage() {

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

    AlertDialog.Builder builder = new AlertDialog.Builder(HR_DescriptionActivity.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"))
            {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                startActivityForResult(intent, CAMERA_REQUEST);
            }
            else if (options[item].equals("Choose from Gallery"))
            {
                Intent intent = new   Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, GALLERY_REQUEST);

            }
            else if (options[item].equals("Cancel")) {
                dialog.dismiss();
            }
        }
    });
    builder.show();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode == RESULT_OK) {
        if (requestCode == CAMERA_REQUEST) {

            cameraresized=(Bitmap) data.getExtras().get("data");


            String path=  manager.saveToInternalStorage(cameraresized,getApplicationContext());
            File f=new File(path, "logo_image.jpg");
            InputStream is=null;

            try {
                 is = new FileInputStream(f);

                buffer=manager.readBytes(is);
                company.setLogo(buffer);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            Glide.with(this).load(company.getLogo()).skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE).into(imgphoto);

        } else if (requestCode == GALLERY_REQUEST) {

            Uri uri = data.getData();
            InputStream inputStream;
            try {
                inputStream=getContentResolver().openInputStream(uri);
                Bitmap bit = BitmapFactory.decodeStream(inputStream);
                imgphoto.setImageBitmap(bit);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

        }
    }
}


//  =================== back activity event ================
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            onBackPressed();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}
//  ========================================================

@Override
public void onConnected(@Nullable Bundle bundle) {}

@Override
public void onConnectionSuspended(int i) {}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {}

}

异常发生在

 company.setLogo(buffer);

问题最有可能出现在

company= (HR_Company)i.getSerializableExtra("HR_Company");

检查 Intent 是否有额外的,否则你正在将 null 设置为引用。

if(i.hasExtra("HR_Company"))
    company= (HR_Company)i.getSerializableExtra("HR_Company")
else
    company = new HR_Company();

请注意,您的代码未遵循命名和格式约定