2016-06-11 14 views
-2

저는 Android가 처음인데 몇 가지 문제가 있습니다. DB.EmployeeOperations.open()에 전달 된 null 객체가있는 것 같지만 확실하지 않습니다. 내가 단계를 놓친 곳은 어디입니까? 도움을 주시면 감사하겠습니다.데이터베이스 객체를 사용할 때 NullPointerException이 발생했습니다.

미리 감사드립니다.

로그 캣 :

* 06-10 16:10:52.605 17203-17203/com.androidtutorialpoint.employeemanagementsystem E/AndroidRuntime: FATAL EXCEPTION: main 
     Process: com.androidtutorialpoint.employeemanagementsystem, PID: 17203 
     java.lang.RuntimeException: Unable to resume activity {com.androidtutorialpoint.employeemanagementsystem/com.androidtutorialpoint.employeemanagementsystem.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.androidtutorialpoint.employeemanagementsystem.DB.EmployeeOperations.open()' on a null object reference 
     at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3019) 
     at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3050) 
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2425) 
     at android.app.ActivityThread.access$900(ActivityThread.java:154) 
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321) 
     at android.os.Handler.dispatchMessage(Handler.java:102) 
     at android.os.Looper.loop(Looper.java:135) 
     at android.app.ActivityThread.main(ActivityThread.java:5294) 
     at java.lang.reflect.Method.invoke(Native Method) 
     at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904) 
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699) 
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.androidtutorialpoint.employeemanagementsystem.DB.EmployeeOperations.open()' on a null object reference 
     at com.androidtutorialpoint.employeemanagementsystem.MainActivity.onResume(MainActivity.java:148) 
     at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1257) 
     at android.app.Activity.performResume(Activity.java:6076) 
     at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3008) 
     at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3050) 
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2425) 
     at android.app.ActivityThread.access$900(ActivityThread.java:154) 
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321) 

자바 코드 :

public class MainActivity extends AppCompatActivity{ 

    private Button addEmployeeButton; 
    private Button editEmployeeButton; 
    private Button deleteEmployeeButton; 
    private Button viewAllEmployeeButton; 
    private EmployeeOperations employeeOps; 
    private static final String EXTRA_EMP_ID = "com.androidtutorialpoint.empId"; 
    private static final String EXTRA_ADD_UPDATE = "com.androidtutorialpoint.add_update"; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     setContentView(R.layout.activity_main); 
     addEmployeeButton = (Button) findViewById(R.id.button_add_employee); 
     editEmployeeButton = (Button) findViewById(R.id.button_edit_employee); 
     deleteEmployeeButton = (Button) findViewById(R.id.button_delete_employee); 
     viewAllEmployeeButton = (Button)findViewById(R.id.button_view_employees); 



     addEmployeeButton.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       Intent i = new Intent(MainActivity.this,AddUpdateEmployee.class); 
       i.putExtra(EXTRA_ADD_UPDATE, "Add"); 
       startActivity(i); 
      } 
     }); 
     editEmployeeButton.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       getEmpIdAndUpdateEmp(); 
      } 
     }); 
     deleteEmployeeButton.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       getEmpIdAndRemoveEmp(); 
      } 
     }); 
     viewAllEmployeeButton.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       Intent i = new Intent(MainActivity.this, ViewAllEmployees.class); 
       startActivity(i); 
      } 
     }); 

    } 


    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     getMenuInflater().inflate(R.menu.employee_menu, menu); 
     return true; 
    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     int id = item.getItemId(); 
     if (id == R.id.menu_item_settings) { 
      return true; 
     } 
     return super.onOptionsItemSelected(item); 
    } 


    public void getEmpIdAndUpdateEmp(){ 

     LayoutInflater li = LayoutInflater.from(this); 
     View getEmpIdView = li.inflate(R.layout.dialog_get_emp_id, null); 

     AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); 
     // set dialog_get_emp_id.xml to alertdialog builder 
     alertDialogBuilder.setView(getEmpIdView); 

     final EditText userInput = (EditText) getEmpIdView.findViewById(R.id.editTextDialogUserInput); 

     // set dialog message 
     alertDialogBuilder 
       .setCancelable(false) 
       .setPositiveButton("OK",new DialogInterface.OnClickListener() { 
          public void onClick(DialogInterface dialog,int id) { 
           // get user input and set it to result 
           // edit text 
           Intent i = new Intent(MainActivity.this,AddUpdateEmployee.class); 
           i.putExtra(EXTRA_ADD_UPDATE, "Update"); 
           i.putExtra(EXTRA_EMP_ID, Long.parseLong(userInput.getText().toString())); 
           startActivity(i); 
          } 
         }).create() 
       .show(); 

    } 


    public void getEmpIdAndRemoveEmp(){ 

     LayoutInflater li = LayoutInflater.from(this); 
     View getEmpIdView = li.inflate(R.layout.dialog_get_emp_id, null); 

     AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); 
     // set dialog_get_emp_id.xml to alertdialog builder 
     alertDialogBuilder.setView(getEmpIdView); 

     final EditText userInput = (EditText) getEmpIdView.findViewById(R.id.editTextDialogUserInput); 

     // set dialog message 
     alertDialogBuilder 
       .setCancelable(false) 
       .setPositiveButton("OK",new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog,int id) { 
         // get user input and set it to result 
         // edit text 
         employeeOps = new EmployeeOperations(MainActivity.this); 
         employeeOps.removeEmployee(employeeOps.getEmployee(Long.parseLong(userInput.getText().toString()))); 
         Toast t = Toast.makeText(MainActivity.this,"Employee removed successfully!",Toast.LENGTH_SHORT); 
         t.show(); 
        } 
       }).create() 
       .show(); 

    } 



    @Override 
    protected void onResume() { 
     super.onResume(); 
     employeeOps.open(); 
    } 

    @Override 
    protected void onPause() { 
     super.onPause(); 
     employeeOps.close(); 

    } 
} 
+0

어쨌든 대화 상자가 열렸을 때'onPause'가 호출되어 닫힌 데이터베이스를 얻었을 것입니다. –

답변

0

이 값이있어, 문제는 당신이 onResume()에서 employeeOps.open()를 호출하고, 그러나 employeeOps 아직 인스턴스화되지 않는다 여전히 null입니다.

Activity lifecycle을 살펴보십시오.

Activity이 생성되면 onResume() : onCreate()onStart() 앞에 두 개의 메소드가 호출됩니다.

open() 메서드를 EmployeeOperations이라고하고 onResume()이라고 말하면 그때까지 그 인스턴스를 가져야합니다.

전화 onCreate()에 다음 :

employeeOps = new EmployeeOperations(this); 
+0

예. 나는 그것을 가지고있다. 그것은 문제였다. 문제 해결, 감사합니다! – Julius

0

귀하의 문제는 Android lifecycle의 오해입니다. 특히, 해당 자원에서

onCreate() 완료 실행되면, 시스템은 빠르게 연속으로 onStart()onResume() 방법을 호출합니다.

employeeOps을 null이 아닌 값으로 설정하기 전에 onResume()이 발생한다는 의미입니다. 단추 누르기에 대한 응답으로 만 초기화하지만 onResume이 트리거되기 전에 활동이 매우 짧은 기간 동안 만 표시됩니다.

관련 문제