0

로그인 페이지가 생성되고 있으며 LoginC가 작동을 멈췄다는 오류가 표시됩니다. 다음과 같은 메시지 로그 캣 표시오류 : 불행히도 안드로이드 에뮬레이터에서 <application name>이 (가) 중지되었습니다.

03-31 07:24:35.896: D/AndroidRuntime(1263): Shutting down VM 
03-31 07:24:35.906: W/dalvikvm(1263): threadid=1: thread exiting with uncaught exception (group=0xb3a1bba8) 
03-31 07:24:35.946: E/AndroidRuntime(1263): FATAL EXCEPTION: main 
03-31 07:24:35.946: E/AndroidRuntime(1263): Process: com.example.loginc, PID: 1263 
03-31 07:24:35.946: E/AndroidRuntime(1263): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.loginc/com.example.loginc.MainActivity}: java.lang.NullPointerException 
03-31 07:24:35.946: E/AndroidRuntime(1263):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195) 
03-31 07:24:35.946: E/AndroidRuntime(1263):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245) 
03-31 07:24:35.946: E/AndroidRuntime(1263):  at android.app.ActivityThread.access$800(ActivityThread.java:135) 
03-31 07:24:35.946: E/AndroidRuntime(1263):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 
03-31 07:24:35.946: E/AndroidRuntime(1263):  at android.os.Handler.dispatchMessage(Handler.java:102) 
03-31 07:24:35.946: E/AndroidRuntime(1263):  at android.os.Looper.loop(Looper.java:136) 
03-31 07:24:35.946: E/AndroidRuntime(1263):  at android.app.ActivityThread.main(ActivityThread.java:5017) 
03-31 07:24:35.946: E/AndroidRuntime(1263):  at java.lang.reflect.Method.invokeNative(Native Method) 
03-31 07:24:35.946: E/AndroidRuntime(1263):  at java.lang.reflect.Method.invoke(Method.java:515) 
03-31 07:24:35.946: E/AndroidRuntime(1263):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) 
03-31 07:24:35.946: E/AndroidRuntime(1263):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 
03-31 07:24:35.946: E/AndroidRuntime(1263):  at dalvik.system.NativeStart.main(Native Method) 
03-31 07:24:35.946: E/AndroidRuntime(1263): Caused by: java.lang.NullPointerException 
03-31 07:24:35.946: E/AndroidRuntime(1263):  at com.example.loginc.MainActivity.onCreate(MainActivity.java:35) 
03-31 07:24:35.946: E/AndroidRuntime(1263):  at android.app.Activity.performCreate(Activity.java:5231) 
03-31 07:24:35.946: E/AndroidRuntime(1263):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087) 
03-31 07:24:35.946: E/AndroidRuntime(1263):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159) 
03-31 07:24:35.946: E/AndroidRuntime(1263):  ... 11 more 

MainActivity.java

public class MainActivity extends ActionBarActivity { 

    private EditText username=null; 
    private EditText password=null; 
    private TextView attempts; 
    private Button login; 
    int counter = 3; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     username = (EditText)findViewById(R.id.editText1); 
     password = (EditText)findViewById(R.id.editText2); 
     attempts = (TextView)findViewById(R.id.textView5); 
     attempts.setText(Integer.toString(counter)); 
     login = (Button)findViewById(R.id.button1); 

    } 

    public void login(View view){ 
      if(username.getText().toString().equals("admin") && 
      password.getText().toString().equals("admin")){ 
      Toast.makeText(getApplicationContext(), "Redirecting...", 
      Toast.LENGTH_SHORT).show(); 
     }  
     else{ 
      Toast.makeText(getApplicationContext(), "Wrong Credentials", 
      Toast.LENGTH_SHORT).show(); 
      attempts.setBackgroundColor(Color.RED); 
      counter--; 
      attempts.setText(Integer.toString(counter)); 
      if(counter==0){ 
      login.setEnabled(false); 
      } 

     } 

    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 

     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.main, 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.action_settings) { 
      return true; 
     } 
     return super.onOptionsItemSelected(item); 
    } 

    /** 
    * A placeholder fragment containing a simple view. 
    */ 
    public static class PlaceholderFragment extends Fragment { 

     public PlaceholderFragment() { 
     } 

     @Override 
     public View onCreateView(LayoutInflater inflater, ViewGroup container, 
       Bundle savedInstanceState) { 
      View rootView = inflater.inflate(R.layout.fragment_main, container, 
        false); 
      return rootView; 
     } 
    } 

} 

위는

및 자세한 내용은 아래

이 fragment_main.xml 파일에 기록 된 mainactivity.java 파일로 작성된 코드

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:paddingBottom="@dimen/activity_vertical_margin" 
android:paddingLeft="@dimen/activity_horizontal_margin" 
android:paddingRight="@dimen/activity_horizontal_margin" 
android:paddingTop="@dimen/activity_vertical_margin" 
tools:context="com.example.loginc.MainActivity$PlaceholderFragment" > 

<TextView 
    android:id="@+id/textView1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignParentTop="true" 
    android:layout_centerHorizontal="true" 
    android:layout_marginTop="18dp" 
    android:text="@string/hello_world" 
    android:textAppearance="?android:attr/textAppearanceLarge" /> 

<TextView 
    android:id="@+id/textView2" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignParentLeft="true" 
    android:layout_below="@+id/textView1" 
    android:layout_marginTop="50dp" 
    android:text="@string/username" 
    android:textAppearance="?android:attr/textAppearanceMedium" /> 

<EditText 
    android:id="@+id/editText1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignBottom="@+id/textView2" 
    android:layout_marginLeft="32dp" 
    android:layout_toRightOf="@+id/textView2" 
    android:ems="10" 
    android:inputType="text" > 

    <requestFocus /> 
</EditText> 

<TextView 
    android:id="@+id/textView3" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignLeft="@+id/textView2" 
    android:layout_below="@+id/textView2" 
    android:layout_marginTop="38dp" 
    android:text="@string/password" 
    android:textAppearance="?android:attr/textAppearanceMedium" /> 

<EditText 
    android:id="@+id/editText2" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignBottom="@+id/textView3" 
    android:layout_alignLeft="@+id/editText1" 
    android:ems="10" 
    android:inputType="textPassword" /> 

<Button 
    android:id="@+id/button1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_below="@+id/editText2" 
    android:layout_centerHorizontal="true" 
    android:layout_marginTop="94dp" 
    android:onClick="login" 
    android:text="@string/Login" /> 

<TextView 
    android:id="@+id/textView4" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignLeft="@+id/textView3" 
    android:layout_below="@+id/textView3" 
    android:layout_marginLeft="30dp" 
    android:layout_marginTop="48dp" 
    android:text="@string/attempts" 
    android:textAppearance="?android:attr/textAppearanceMedium" /> 

<TextView 
    android:id="@+id/textView5" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignRight="@+id/textView1" 
    android:layout_alignTop="@+id/textView4" 
    android:text="TextView" /> 


</RelativeLayout> 
+0

레이아웃 XML과 함께 Java 코드를 게시하십시오. –

+1

MainActivity.java 게시 – Hariharan

+0

activity_main.xml도 게시하십시오. – Hariharan

답변

0

null PointerException은 사용자가 t o null (기본적으로 초기화되지 않음)으로 설정된 값에 대한 작업을 수행합니다. 프로그래밍되지 않은 신용 카드처럼 설정하지 않고도 가치를 생각할 수 있습니다. 주변에 가지고 다닐 수는 있지만 사용하려고하면 작동하지 않습니다. 따라서 onCreate 함수에서 어떤 값이 null 일 수 있습니까?

나는이 줄이 35라고 강력하게 의심하고, 그렇지 않다면이 답은 적용되지 않을 것이다. 귀하의 오류가 라인 (35)에, 또는 적어도 그와 관련된 : 나는 attempts 어떻게 든 널 있으리라 믿고있어

attempts.setText(Integer.toString(counter)); 

. 이 세트는 어디에 있습니까?

attempts = (TextView)findViewById(R.id.textView5); 

좋아, 뷰가 어떻게 든 후 시도가 null이 될 수를 찾을 수 없습니다 그래서 경우의이 findViewById

public View findViewById (int id)

Added in API level 1

Finds a view that was identified by the id attribute from the XML that was processed in onCreate(Bundle).

Returns: The view if found or null otherwise.

에 대한 설명서를 살펴 보자. 실제로 null인지 어떻게 알 수 있습니까? 이제 로그 문을 해보자는 findViewById

Log.v("Main","attempts="+attempts); 

좋아요 후이 권리를 포함,의는 실제로 null 값입니다 가정하자. 그러면 우리는 무엇을해야합니까? 글쎄, 문서에 따르면, 그것은 그것이 발견되지 않았다는 것을 의미합니다. 음,이 된 setContentView 문을 살펴 보자 :

setContentView(R.layout.activity_main); 

좋아,보기가 activity_main.xml에 있어야합니다. 귀하의 코드에있는 것을 볼 수 있지만, 파일 fragment_main.xml을 호출했습니다. 요컨대, 잘못된 XML 파일에서 attempts 값을 얻으려고합니다. 좋아요, 그럼 해결책은 뭔가요?

  1. 가장 좋은 방법은 fragment_main.xml 인 조각에서이 모든 것을 관리하는 것입니다. 이것은 약간의 작업이 필요할 수도 있지만 결국에는 최상의 성능을 제공 할 것입니다.
  2. 단편 (태블릿 지원 기능이 없거나 화면 회전 성능이 좋지 않을 경우 다른 결과가 나타날 수 있음)을 사용하지 않을 것이라는 확신이 들면 setContentViewR.layout.fragment_main으로 바꿀 수 있습니다.

어쨌든이 중 하나를 선택하면 문제가 사라집니다.

첫 번째 코드를 선택하면 onCreateView 안에 코드를 넣고 루트보기 (onCreateView가 반환하는 것)를 통해 참조해야합니다.view.findViewById과 같은 것입니다.

+0

당신이 말하려고하는 것이 있습니다. 제 1 옵션을 선택하면 어떤 변화가 필요할까요? – user3480948

+0

좋아요 ... fragment_main.xml과 activity_main.xml의 차이점을 알려주시겠습니까? 정확히 두 파일이 무엇인가? – user3480948

0
그 ID (들), activity_main.xml 않고, fragment_main.xml에 따라서 NPE만큼 onCreateView

username = (EditText)findViewById(R.id.editText1); 
    password = (EditText)findViewById(R.id.editText2); 
    attempts = (TextView)findViewById(R.id.textView5); 
    attempts.setText(Integer.toString(counter)); 
    login = (Button)findViewById(R.id.button1); 

이러한 이동

.

또한 rootView.findViewById을 사용하십시오.