2017-02-10 48 views
0

空我有添加的對象(自定義對象)活性和我初始化它裏面的OnCreate 方法:參考在的onCreate設定是在onActivityResult

company=new HR_Company(); 

在我把它寫像,該活動的開始:

HR_Company company; 

,當我嘗試設置一個名稱這個對象內部像

company.setHr_company_location("dfdfd"); 

它向我返回一個公司對象爲空的例外,那是怎麼回事? 我嘗試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()方法中不可能是null(除非你自己設置爲null)。在onResume()之前調用'onActivityResult()'和'onActivityResult()'之前調用'onCreate()'' –

+0

聽起來就像在初始化之前使用它。也許你應該發佈整個代碼或[MVCE](http://stackoverflow.com/help/mcve) – iheanyi

+0

我加了全部代碼 –

回答

0

的問題是最有可能在

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

檢查如果意圖有額外的,否則你將null設置爲引用。

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

請注意,您的代碼不下列命名和格式約定

+0

所以如果(HR_Company)i.getSerializableExtra(「HR_Company」);是空的我插入null公司對象? –

+0

我已經更新了答案。使用我提供的if/else,並在'onCreate'的開始處移除初始化,或僅使用if情況 –