2013-11-24 1 views
-1

Это мой LogCat для моего приложения com.pmssЯ не вижу никакой ошибки в моем кодировании, но при запуске на моих приложениях это сила закрыт

11-24 23:31:04.799: D/AndroidRuntime(22791): Shutting down VM 
11-24 23:31:04.799: W/dalvikvm(22791): threadid=1: thread exiting with uncaught exception (group=0x40018578) 
11-24 23:31:04.809: E/AndroidRuntime(22791): FATAL EXCEPTION: main 
11-24 23:31:04.809: E/AndroidRuntime(22791): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.pmss/com.pmss.Login}: java.lang.NullPointerException 
11-24 23:31:04.809: E/AndroidRuntime(22791): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1573) 
11-24 23:31:04.809: E/AndroidRuntime(22791): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667) 
11-24 23:31:04.809: E/AndroidRuntime(22791): at android.app.ActivityThread.access$1500(ActivityThread.java:117) 
11-24 23:31:04.809: E/AndroidRuntime(22791): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935) 
11-24 23:31:04.809: E/AndroidRuntime(22791): at android.os.Handler.dispatchMessage(Handler.java:99) 
11-24 23:31:04.809: E/AndroidRuntime(22791): at android.os.Looper.loop(Looper.java:130) 
11-24 23:31:04.809: E/AndroidRuntime(22791): at android.app.ActivityThread.main(ActivityThread.java:3687) 
11-24 23:31:04.809: E/AndroidRuntime(22791): at java.lang.reflect.Method.invokeNative(Native Method) 
11-24 23:31:04.809: E/AndroidRuntime(22791): at java.lang.reflect.Method.invoke(Method.java:507) 
11-24 23:31:04.809: E/AndroidRuntime(22791): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867) 
11-24 23:31:04.809: E/AndroidRuntime(22791): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625) 
11-24 23:31:04.809: E/AndroidRuntime(22791): at dalvik.system.NativeStart.main(Native Method) 
11-24 23:31:04.809: E/AndroidRuntime(22791): Caused by: java.lang.NullPointerException 
11-24 23:31:04.809: E/AndroidRuntime(22791): at android.app.Activity.findViewById(Activity.java:1647) 
11-24 23:31:04.809: E/AndroidRuntime(22791): at com.pmss.Login.<init>(Login.java:14) 
11-24 23:31:04.809: E/AndroidRuntime(22791): at java.lang.Class.newInstanceImpl(Native Method) 
11-24 23:31:04.809: E/AndroidRuntime(22791): at java.lang.Class.newInstance(Class.java:1409) 
11-24 23:31:04.809: E/AndroidRuntime(22791): at android.app.Instrumentation.newActivity(Instrumentation.java:1021) 
11-24 23:31:04.809: E/AndroidRuntime(22791): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1565) 
11-24 23:31:04.809: E/AndroidRuntime(22791): ... 11 more 

Это мой файл манифеста, как показано ниже

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
package="com.pmss" 
android:versionCode="1" 
android:versionName="1.0" > 

<uses-sdk 
    android:minSdkVersion="7" 
    android:targetSdkVersion="19" /> 

<application 
    android:allowBackup="true" 
    android:icon="@drawable/ic_launcher" 
    android:label="@string/app_name" 
    android:theme="@style/Theme.AppCompat.Light.DarkActionBar" > 
    <activity 
     android:name="com.pmss.Login" 
     android:label="@string/app_main" > 
     <intent-filter android:label="@string/app_name" > 
      <action android:name="android.intent.action.MAIN" /> 

      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
    </activity> 
    <activity 
     android:name="com.pmss.Register" 
     android:label="@string/button_register" 
     android:parentActivityName="com.pmss.Login" > 
     <meta-data 
      android:name="android.support.PARENT_ACTIVITY" 
      android:value="com.pmss.Login" /> 
    </activity> 
    <activity 
     android:name="com.pmss.MainMenu" 
     android:label="@string/mainmenu" 
     android:parentActivityName="com.pmss.Login" > 
     <meta-data 
      android:name="android.support.PARENT_ACTIVITY" 
      android:value="com.pmss.Login" /> 
    </activity> 
</application> 

Я не знаю, в чем проблема, поскольку в моей кодировке не было ошибок.

Это мой Login.java ниже

package com.pmss; 

import android.annotation.SuppressLint; 
import android.content.Intent; 
import android.os.Build; 
import android.os.Bundle; 
import android.support.v7.app.ActionBarActivity; 
import android.view.Menu; 
import android.view.View; 
import android.widget.Button; 

public class Login extends ActionBarActivity { 

Button login = (Button) findViewById(R.id.login); 
Button register = (Button) findViewById(R.id.register); 

@SuppressLint("NewApi") 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_login); 
    getSupportActionBar().setDisplayHomeAsUpEnabled(false); 

    login.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      // TODO Auto-generated method stub 
      Intent intent = new Intent(Login.this, MainMenu.class); 
      startActivity(intent); 
     } 
    }); 

    register.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      // TODO Auto-generated method stub 
      Intent intent = new Intent(Login.this, Register.class); 
      startActivity(intent); 
     } 
    }); 

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { 
     // For the main activity, make sure the app icon in the action bar 
     // does not behave as a button 
     getSupportActionBar().setDisplayHomeAsUpEnabled(true); 
    } 
} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.login, menu); 
    return true; 
} 

} 

Это мой Login.xml ниже

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:id="@+id/RelativeLayout1" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:useDefaultMargins="true" 
tools:ignore="ExtraText" > 

<EditText 
    android:id="@+id/password" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_centerHorizontal="true" 
    android:layout_centerVertical="true" 
    android:ems="10" 
    android:inputType="textPassword" /> 

<Button 
    android:id="@+id/register" 
    android:layout_width="100dp" 
    android:layout_height="50dp" 
    android:layout_alignParentBottom="true" 
    android:layout_alignRight="@+id/password" 
    android:layout_marginBottom="26dp" 
    android:gravity="center" 
    android:text="@string/button_register" /> 

<TextView 
    android:id="@+id/newuser" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_above="@+id/register" 
    android:layout_centerHorizontal="true" 
    android:layout_marginBottom="14dp" 
    android:text="@string/newuser" /> 

<EditText 
    android:id="@+id/userid" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_above="@+id/textView3" 
    android:layout_alignRight="@+id/password" 
    android:layout_marginBottom="14dp" 
    android:ems="10" 
    android:inputType="textPersonName" > 

    <requestFocus /> 
</EditText> 

<TextView 
    android:id="@+id/textView2" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_above="@+id/userid" 
    android:layout_centerHorizontal="true" 
    android:text="@string/userid" 
    android:textSize="20sp" /> 

<TextView 
    android:id="@+id/textView3" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_above="@+id/password" 
    android:layout_centerHorizontal="true" 
    android:text="@string/password" 
    android:textSize="20sp" /> 

<Button 
    android:id="@+id/login" 
    android:layout_width="100dp" 
    android:layout_height="50dp" 
    android:layout_alignLeft="@+id/textView3" 
    android:layout_below="@+id/password" 
    android:layout_marginTop="14dp" 
    android:gravity="center" 
    android:text="@string/button_login" /> 

</RelativeLayout> 
+0

Сообщение код вашего 'LoginActivity'. –

+0

, чтобы ответить на этот вопрос, было бы хорошо видеть код действия 'Login', а также xml с макетом –

+2

Вы должны понимать разницу между ошибкой компилятора (никаких ошибок в моем кодировании - если это было правдой, ваше приложение не потерпит крах!). Вы не можете получить ошибку времени выполнения, пока не исправите ошибки компилятора, так как вы не сможете запустить приложение до тех пор, пока не сделаете это. 'Caused by: java.lang.NullPointerException 11-24 23: 31: 04.809: E/AndroidRuntime (22791): at android.app.Activity.findViewById (Activity.java:1647) 11-24 23: 31: 04.809 : E/AndroidRuntime (22791): в com.pmss.Login. (Login.java:14) 'Нам нужно увидеть класс Login и показать, что такое строка 14. – Simon

ответ

1

Вы должны получить ваши элементы после накачивания макета, в противном случае будет findViewById возврат null и, следовательно, вы получите NPE по адресу login.setOnClickListener(/**/).

onCreate(Bundle) - это то, где вы инициализируете свою деятельность. В большинстве случаев здесь обычно вызывается setContentView(int) с ресурсом макета , определяющим ваш пользовательский интерфейс, а с помощью findViewById(int) - - получить виджеты в этом пользовательском интерфейсе, которые необходимо взаимодействовать с программным обеспечением .


Button login; 
Button register; 

@SuppressLint("NewApi") 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_login); //<-- here the layout is inflated 
    //Now you can retrieve your elements from the XML file. 
    login = (Button) findViewById(R.id.login); 
    register = (Button) findViewById(R.id.register); 
    /*****/ 
} 
+0

Значит, это означает, что «login = (Button) findViewById (R.id.login)»; не следует объявлять перед setContentView? – Nick

+0

@Nick Вам всегда нужно раздувать макет, содержащий элементы, прежде чем пытаться их восстановить. –

0

Ваша проблема в вашем OnCreate:

login.setOnClickListener(new View.OnClickListener()... 

"Логин" будет аннулирована здесь, так как findViewById() требует макет уже загружен, в противном случае он не будет найдите элемент, и он будет равен нулю.

Добавьте это право перед установкой слушателя:

login = (Button) findViewById(R.id.login); 
+0

okok Я думаю, я понимаю, что вы все значит ... Спасибо за помощь – Nick

Смежные вопросы