2017-02-10 7 views
0

я обладаю активностью, что я добавленным объект (пользовательский объект) и я инициализировать его внутри OnCreate метод:Ссылка устанавливается в OnCreate является нулем в onActivityResult

company=new HR_Company(); 

в начале деятельности я пишу это так:

HR_Company company; 

и когда я пытаюсь установить имя внутри этого объекта, как

company.setHr_company_location("dfdfd"); 

он возвращает мне исключение, что объект компании имеет значение null, как это? я пытаюсь установить внутри метода 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); 
+0

Просьба предоставить больше кода активности. На другой ноте, если вы действительно инициализируете поданную в 'onCreate()', невозможно, чтобы она была нулевой в 'onActivityResult()' (если вы не установили ее нулевой). 'onCreate()' гарантированно вызывается до 'onActivityResult()' и 'onActivityResult()' вызывается перед 'onResume()' –

+0

Похоже, вы используете его перед инициализацией. Возможно, вам следует опубликовать весь код или [MVCE] (http://stackoverflow.com/help/mcve) – iheanyi

+0

. Я добавил весь код –

ответ

0

Проблема, скорее всего, в

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

Check если у намерения есть дополнительные, иначе вы устанавливают значение null для ссылки.

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

Пожалуйста, обратите внимание, что ваш код не следует именовании и форматирование конвенций

+0

, поэтому if (HR_Company) i.getSerializableExtra («HR_Company»); пусто, я вставляю null в объект компании? –

+0

Я обновил ответ. Используйте if/else, который я предоставил, и удалите инициализацию в начале 'onCreate' или используйте только if if –